主頁 >  其他 > SpringBoot 整合 Elasticsearch

SpringBoot 整合 Elasticsearch

2022-03-06 07:39:10 其他

目錄

  • 1. 引入依賴
  • 2. 添加組態檔
  • 3. 創建ES配置類
  • 4. swagger配置類
  • 5. 訊息回傳體
  • 6. 創建保存檔案的物體
  • 7. 索引操作service
  • 8. 創建索引controller
  • 9. 測驗索引操作
    • 9.1 創建索引
    • 9.2 判斷索引是否存在
    • 9.3 洗掉索引
  • 10. 檔案操作service
  • 11. 創建檔案controller
  • 12. 測驗檔案操作
    • 12.1 插入檔案
    • 12.2 查詢檔案
    • 12.3 更新檔案
    • 12.4 洗掉檔案
  • 13. search操作service
  • 14. search操作controller
  • 15. 測驗search介面操作
    • 15.1 _search介面基本用法
    • 15.2 基于詞項的查詢
    • 15.3 基于全文的查詢
    • 15.4 基于全文的模糊查詢
    • 15.5 組合查詢
  • 16. 聚集操作service
  • 17. 聚集查詢controller
  • 18. 測驗聚集查詢
  • 代碼下載地址

1. 引入依賴

  • 這里使用springboot 2.5.4 版本,es使用 7.14.0 版本
  • 可以參考es 官方檔案 ,在Java REST Client 下找到對應的版本

在這里插入圖片描述

  • 這里使用7.14.0的 Java High Level REST Client

在這里插入圖片描述

  • 右下角有詳細的使用說明

在這里插入圖片描述

  • 需要同時使用elasticsearch和elasticsearch-rest-high-level-client

在這里插入圖片描述

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- es-->
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.14.0</version>
        </dependency>

        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.14.0</version>
        </dependency>

        <!-- fastjson-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.57</version>
        </dependency>

        <!-- Swagger2 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

2. 添加組態檔

#es
elasticsearch.host=192.168.42.111
elasticsearch.port=9200
#jackson
spring.jackson.default-property-inclusion=non_null

3. 創建ES配置類

package com.example.demo.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ESConfig {

    @Value("${elasticsearch.host}")
    private String host;

    @Value("${elasticsearch.port}")
    private int port;

    @Bean
    public RestHighLevelClient highLevelClient() {
        HttpHost httpHost = new HttpHost(host, port, "http");
        // 如果是集群模式,可以添加HttpHost陣列
        RestClientBuilder restClientBuilder = RestClient.builder(httpHost);
        return new RestHighLevelClient(restClientBuilder);
    }

}

4. swagger配置類

package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
                .apis(RequestHandlerSelectors.basePackage("com.example.demo")).build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().version("1.0").build();
    }

}

5. 訊息回傳體

  • 用來包裝回傳資料
package com.example.demo.vo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class AjaxResult<T> {

    private Integer code;

    private String message;

    private T data;

    public static <T> AjaxResult<T> ok(T data) {
        return new AjaxResult<>(0, "success", data);
    }

    public static <T> AjaxResult<T> error(T data) {
        return new AjaxResult<>(1, "error", data);
    }

}

6. 創建保存檔案的物體

package com.example.demo.vo;

import lombok.Data;

@Data
public class User {

    private String firstName;

    private String secondName;

    private String content;

    private Integer age;

}

7. 索引操作service

  • 這里對索引進行創建,判斷索引是否存在和洗掉索引
package com.example.demo.service;

import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;

@Service
public class OperateIndex {

    @Resource
    private RestHighLevelClient restHighLevelClient;

    public boolean createIndex(String indexName) {
        boolean acknowledged = false;
        try {
            /**
             * 可以根據需要設定欄位屬性,如果不設定,es會根據添加檔案時的欄位型別自動推斷
             * put /{indexName}/_mapping
             * {
             *     "properties": {
             *         "firstName": {
             *             "type": "keyword"
             *         },
             *         "secondName": {
             *             "type": "keyword"
             *         },
             *         "age": {
             *             "type": "integer"
             *         },
             *         "content": {
             *             "type": "text"
             *         }
             *     }
             * }
             */
            XContentBuilder xContentBuilder = XContentFactory.jsonBuilder()
                    .startObject()
                    .field("properties").startObject()
                    .field("firstName").startObject().field("type", "keyword").endObject()
                    .field("secondName").startObject().field("type", "keyword").endObject()
                    .field("age").startObject().field("type", "integer").endObject()
                    .field("content").startObject().field("type", "text").endObject()
                    .endObject()
                    .endObject();
            CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName);
            createIndexRequest.mapping(xContentBuilder);
            CreateIndexResponse createIndexResponse =
                    restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
            acknowledged = createIndexResponse.isAcknowledged();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return acknowledged;
    }

    public boolean isIndexExists(String indexName) {
        GetIndexRequest getIndexRequest = new GetIndexRequest(indexName);
        getIndexRequest.humanReadable(true);
        boolean exists = false;
        try {
            exists = restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return exists;
    }

    public boolean deleteIndex(String indexName) {
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(indexName);
        // 忽略索引不存在的情況;如果不設定,索引不存在時,會報錯
        deleteIndexRequest.indicesOptions(IndicesOptions.LENIENT_EXPAND_OPEN);
        boolean acknowledged = false;
        try {
            AcknowledgedResponse delete =
                    restHighLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
            acknowledged = delete.isAcknowledged();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return acknowledged;
    }

}

8. 創建索引controller

package com.example.demo.controller;

import com.example.demo.service.OperateIndex;
import com.example.demo.vo.AjaxResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/index")
public class IndexController {

    @Resource
    private OperateIndex operateIndex;

    /*
     * 創建索引
     */
    @PostMapping("/create")
    public AjaxResult<Boolean> createIndex(@RequestParam String indexName) {
        return AjaxResult.ok(operateIndex.createIndex(indexName));
    }

    /**
     * 索引是否存在
     */
    @PostMapping("/exit")
    public AjaxResult<Boolean> indexExit(@RequestParam String indexName) {
        return AjaxResult.ok(operateIndex.isIndexExists(indexName));
    }

    /**
     * 洗掉索引
     */
    @PostMapping("/delete")
    public AjaxResult<Boolean> deleteIndex(@RequestParam String indexName) {
        return AjaxResult.ok(operateIndex.deleteIndex(indexName));
    }
}

9. 測驗索引操作

9.1 創建索引

在這里插入圖片描述

  • 查看是否創建成功

在這里插入圖片描述

9.2 判斷索引是否存在

在這里插入圖片描述

9.3 洗掉索引

在這里插入圖片描述

  • 再次查看索引是否存在

在這里插入圖片描述

10. 檔案操作service

package com.example.demo.service;

import com.alibaba.fastjson.JSON;
import com.example.demo.vo.AjaxResult;
import com.example.demo.vo.User;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.get.GetResult;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Objects;

@Service
public class OperateDoc {

    @Resource
    private RestHighLevelClient restHighLevelClient;

    public AjaxResult<String> insertDoc(User user, String indexName, String docId) {
        IndexRequest indexRequest = new IndexRequest(indexName);
        //設定檔案id,如果不設定id,es會自動生成全域唯一的id
        indexRequest.id(docId);
        //設定檔案資料和格式
        indexRequest.source(JSON.toJSONString(user), XContentType.JSON);
        try {
            //獲取回傳的response
            IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
            if (Objects.nonNull(indexResponse)) {
                String id = indexResponse.getId();
                DocWriteResponse.Result result = indexResponse.getResult();
                // 如果設定的id不存在,則新增檔案;如果id已存在,則覆寫檔案
                if (Objects.equals(result, DocWriteResponse.Result.CREATED)) {
                    return new AjaxResult<>(0, "新增檔案成功!", id);
                } else if (Objects.equals(result, DocWriteResponse.Result.UPDATED)) {
                    return new AjaxResult<>(0, "覆寫檔案成功!", id);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public AjaxResult<String> getDoc(String indexName, String docId) {
        GetRequest getRequest = new GetRequest(indexName, docId);
        try {
            GetResponse getResponse = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
            if (getResponse.isExists()) {
                return AjaxResult.ok(getResponse.getSourceAsString());
            } else {
                return AjaxResult.error("檔案不存在!");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public AjaxResult<String> updateDoc(String indexName, String docId, String fieldName,String fieldValue) {
        try {
            XContentBuilder xContentBuilder = XContentFactory.jsonBuilder();
            xContentBuilder.startObject();
            xContentBuilder.field(fieldName, fieldValue);
            xContentBuilder.endObject();
            UpdateRequest updateRequest = new UpdateRequest(indexName, docId);
            updateRequest.doc(xContentBuilder);
            //id不存在則添加檔案
            updateRequest.docAsUpsert(true);
            //在應答里包含當前檔案的內容
            updateRequest.fetchSource(true);
            UpdateResponse updateResponse = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
            GetResult getResult = updateResponse.getGetResult();
            if (getResult.isExists()) {
                return AjaxResult.ok(getResult.sourceAsString());
            } else {
                return AjaxResult.error("更新檔案失敗!");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public AjaxResult<String> deleteDoc(String indexName, String docId) {
        DeleteRequest deleteRequest = new DeleteRequest(indexName, docId);
        try {
            DeleteResponse deleteResponse = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
            if (Objects.equals(deleteResponse.getResult(), DocWriteResponse.Result.DELETED)) {
                return AjaxResult.ok("檔案洗掉成功!");
            } else if (Objects.equals(deleteResponse.getResult(), DocWriteResponse.Result.NOT_FOUND)) {
                return AjaxResult.error("檔案不存在");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

11. 創建檔案controller

package com.example.demo.controller;

import com.example.demo.service.OperateDoc;
import com.example.demo.vo.AjaxResult;
import com.example.demo.vo.User;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/doc")
public class DocController {

    @Resource
    private OperateDoc operateDoc;

    /**
     * 插入檔案
     */
    @PostMapping("/insert")
    public AjaxResult<String> insertDoc(@RequestBody User user, @RequestParam String indexName,
                                        @RequestParam String docId) {
        return operateDoc.insertDoc(user, indexName, docId);
    }

    /**
     * 查詢檔案
     */
    @PostMapping("/query")
    public AjaxResult<String> getDoc(@RequestParam String indexName, @RequestParam String docId) {
        return operateDoc.getDoc(indexName, docId);
    }

    /**
     * 更新檔案
     */
    @PostMapping("/updata")
    public AjaxResult<String> updateDoc(@RequestParam String indexName, @RequestParam String docId,
                                        @RequestParam String fieldName, @RequestParam String fieldValue) {
        return operateDoc.updateDoc(indexName, docId, fieldName, fieldValue);
    }

    /**
     * 洗掉檔案
     */
    @PostMapping("/delete")
    public AjaxResult<String> deleteDoc(@RequestParam String indexName, @RequestParam String docId) {
        return operateDoc.deleteDoc(indexName, docId);
    }

}

12. 測驗檔案操作

12.1 插入檔案

在這里插入圖片描述
在這里插入圖片描述

12.2 查詢檔案

在這里插入圖片描述

12.3 更新檔案

在這里插入圖片描述
在這里插入圖片描述

12.4 洗掉檔案

在這里插入圖片描述
在這里插入圖片描述

13. search操作service

package com.example.demo.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.vo.AjaxResult;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.FuzzyQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;

@Service
public class NormalSearch {

    @Resource
    private RestHighLevelClient restHighLevelClient;

    /**
     * 處理回傳結果中的hits部分
     */
    public AjaxResult<JSONArray> send(String indexName, SearchSourceBuilder searchSourceBuilder) {
        try {
            SearchRequest searchRequest = new SearchRequest();
            searchRequest.indices(indexName);
            searchRequest.source(searchSourceBuilder);
            SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits hits = search.getHits();
            JSONArray jsonArray = new JSONArray();
            for (SearchHit hit : hits) {
                String src = hit.getSourceAsString();
                JSONObject jsonObject = JSON.parseObject(src);
                jsonArray.add(jsonObject);
            }
            return AjaxResult.ok(jsonArray);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * _search介面基本用法
     */
    public AjaxResult<JSONArray> searchExample(String indexName) {
        /**
         * 拼接查詢條件
         * get kibana_sample_data_flights/_search
         * {
         * 	"from":0,
         * 	"size":5,
         * 	"query":{
         * 		"match_all":{}
         *   },
         * 	"_source":["Origin*","*Weather"],
         * 	"sort":[{"DistanceKilometers":"asc"},{"FlightNum":"desc"}]
         * }
         */
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.from(0);
        searchSourceBuilder.size(5);
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        String[] includeFields = new String[]{"Origin*", "*Weather"};
        searchSourceBuilder.fetchSource(includeFields, null);
        searchSourceBuilder.sort(new FieldSortBuilder("DistanceKilometers").order(SortOrder.ASC));
        searchSourceBuilder.sort(new FieldSortBuilder("FlightNum").order(SortOrder.DESC));
        return send(indexName, searchSourceBuilder);
    }

    /**
     * 基于詞項的查詢
     */
    public AjaxResult<JSONArray> termsSearch(String indexName) {
        /**
         * get kibana_sample_data_flights/_search
         * {
         * 	"query":{
         * 		"term":{
         * 			"dayOfWeek":3
         *       }
         *   }
         * }
         */
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("dayOfWeek", 3);
        searchSourceBuilder.query(termQueryBuilder);
        return send(indexName, searchSourceBuilder);
    }

    /**
     * 基于全文的查詢
     */
    public AjaxResult<JSONArray> matchSearch(String indexName) {
        /**
         *  POST /kibana_sample_data_flights/_search
         * {
         * 	"query": {
         * 		"multi_match": {
         * 			"query":"AT",
         * 			"fields":["DestCountry", "OriginCountry"]
         *       }
         *   }
         * }
         */
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.multiMatchQuery("AT", "DestCountry", "OriginCountry"));
        return send(indexName, searchSourceBuilder);
    }

    /**
     * 基于全文的模糊查詢
     */
    public AjaxResult<JSONArray> fuzzySearch(String indexName) {
        /**
         * get kibana_sample_data_logs/_search
         * {
         *     "query": {
         *         "fuzzy": {
         *             "message": {
         *                 "value": "firefix",
         *                 "fuzziness": "1"
         *             }
         *         }
         *     }
         * }
         */
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        FuzzyQueryBuilder fuzzyQueryBuilder = QueryBuilders.fuzzyQuery("message", "firefix");
        fuzzyQueryBuilder.fuzziness(Fuzziness.ONE);
        searchSourceBuilder.query(fuzzyQueryBuilder);
        return send(indexName, searchSourceBuilder);
    }

    /**
     * 組合查詢范例
     */
    public AjaxResult<JSONArray> boolSearch(String indexName) {
        /**
         * POST /kibana_sample_data_logs/_search
         * {
         * 	"query": {
         * 		"bool": {
         * 			"must":[
         *                {"match": { "message": "firefox"} }
         * 			],
         * 			"should":[
         *                {"term": { "geo. src": "CN"}},
         *                {"term": { "geo. dest": "CN"}}
         * 			]
         *        }
         *    }
         * }
         */
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.matchQuery("message", "firefox"))
                .should(QueryBuilders.termQuery("geo.src", "CN"))
                .should(QueryBuilders.termQuery("geo.dest", "CN"));
        searchSourceBuilder.query(boolQueryBuilder);
        return send(indexName, searchSourceBuilder);
    }

}

14. search操作controller

package com.example.demo.controller;

import com.alibaba.fastjson.JSONArray;
import com.example.demo.service.NormalSearch;
import com.example.demo.vo.AjaxResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/search")
public class SearchController {

    private final static String KIBANA_SAMPLE_DATA_FLIGHTS = "kibana_sample_data_flights";

    private final static String KIBANA_SAMPLE_DATA_LOGS = "kibana_sample_data_logs";
    
    @Resource
    private NormalSearch normalSearch;

    /**
     * _search介面基本用法
     */
    @PostMapping("/example")
    public AjaxResult<JSONArray> searchExample() {
        return normalSearch.searchExample(KIBANA_SAMPLE_DATA_FLIGHTS);
    }

    /**
     * 基于詞項的查詢
     */
    @PostMapping("/term")
    public AjaxResult<JSONArray> termsSearch() {
        return normalSearch.termsSearch(KIBANA_SAMPLE_DATA_FLIGHTS);
    }

    /**
     * 基于全文的查詢
     */
    @PostMapping("/match")
    public AjaxResult<JSONArray> matchSearch() {
        return normalSearch.matchSearch(KIBANA_SAMPLE_DATA_FLIGHTS);
    }

    /**
     * 基于全文的模糊查詢
     */
    @PostMapping("/fuzzy")
    public AjaxResult<JSONArray> fuzzySearch() {
        return normalSearch.fuzzySearch(KIBANA_SAMPLE_DATA_LOGS);
    }

    /**
     * 組合查詢范例
     */
    @PostMapping("/combination")
    public AjaxResult<JSONArray> combinationSearch() {
        return normalSearch.boolSearch(KIBANA_SAMPLE_DATA_LOGS);
    }

}

15. 測驗search介面操作

  • 測驗之前需要提前匯入es提供的樣例資料kibana_sample_data_flights和kibana_sample_data_logs,參考資料檢索和分析

15.1 _search介面基本用法

在這里插入圖片描述

15.2 基于詞項的查詢

在這里插入圖片描述

15.3 基于全文的查詢

在這里插入圖片描述

15.4 基于全文的模糊查詢

在這里插入圖片描述

15.5 組合查詢

在這里插入圖片描述

16. 聚集操作service

package com.example.demo.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.vo.AjaxResult;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
import org.elasticsearch.search.aggregations.metrics.ParsedAvg;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@Service
public class AggsSearch {

    @Resource
    private RestHighLevelClient restHighLevelClient;

    /**
     * 處理回傳結果中的hits和聚集
     */
    public AjaxResult<JSONArray> send(String indexName, SearchSourceBuilder searchSourceBuilder) {
        try {
            SearchRequest searchRequest = new SearchRequest();
            searchRequest.indices(indexName);
            searchRequest.source(searchSourceBuilder);
            SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits hits = search.getHits();
            JSONArray jsonArray = new JSONArray();
            //hits部分
            for (SearchHit hit : hits) {
                String src = hit.getSourceAsString();
                JSONObject jsonObject = JSON.parseObject(src);
                jsonArray.add(jsonObject);
            }
            //聚集部分
            Aggregations aggregations = search.getAggregations();
            for (Aggregation aggregation : aggregations) {
                String jsonString = JSON.toJSONString(aggregation);
                jsonArray.add(JSON.parseObject(jsonString));
                //這里可以拿到具體的桶聚集,做特殊處理
                List<? extends Histogram.Bucket> buckets = ((Histogram) aggregation).getBuckets();
                for (Histogram.Bucket bucket : buckets) {
                    System.out.println("--------------------------------------");
                    System.out.println(bucket.getKeyAsString());
                    System.out.println(bucket.getDocCount());
                    ParsedAvg parsedAvg = (ParsedAvg) bucket.getAggregations().getAsMap().get("avg_price");
                    System.out.println(parsedAvg.getValueAsString());
                }
            }
            return AjaxResult.ok(jsonArray);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return AjaxResult.error(null);
    }

    /**
     * 聚集查詢
     */
    public AjaxResult aggsExampleSearch(String indexName) {
        /**
         * high level client不能使用過濾條件filter_path,如果要使用,只能使用low level client
         * POST /kibana_sample_data_flights/_search?filter_path=aggregations
         * {
         * 	"query": {
         * 		"term": {"OriginCountry": "CN"}
         *        },
         * 	"aggs":
         *    {
         * 		"date_price_histogram": {
         * 			"date_histogram": {
         * 				"field": "timestamp",
         * 				"fixed_interval": "30d"
         *            },
         * 			"aggs": {
         * 				"avg_price": {"avg": {"field": "FlightDelayMin"}}
         *            }
         *        }
         *    }
         * }
         */
        // 拼接query部分
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.termQuery("OriginCountry", "CN"));

        //拼接聚集部分
        DateHistogramAggregationBuilder date_price_histogram
                = AggregationBuilders.dateHistogram("date_price_histogram");
        date_price_histogram.field("timestamp").fixedInterval(DateHistogramInterval.days(30));
        //嵌套聚集部分
        date_price_histogram.subAggregation(AggregationBuilders.avg("avg_price").field("FlightDelayMin"));
        searchSourceBuilder.aggregation(date_price_histogram);

        return send(indexName, searchSourceBuilder);
    }

}

17. 聚集查詢controller

package com.example.demo.controller;

import com.alibaba.fastjson.JSONArray;
import com.example.demo.service.AggsSearch;
import com.example.demo.vo.AjaxResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/aggs")
public class AggsController {

    private final static String KIBANA_SAMPLE_DATA_FLIGHTS = "kibana_sample_data_flights";

    @Resource
    private AggsSearch aggsSearch;

    /**
     * 聚集查詢
     */
    @PostMapping("/query")
    public AjaxResult<JSONArray> aggsQuery() {
        return aggsSearch.aggsExampleSearch(KIBANA_SAMPLE_DATA_FLIGHTS);
    }

}

18. 測驗聚集查詢

  • 直接使用kibana查詢的結果

在這里插入圖片描述

  • 介面呼叫結果

在這里插入圖片描述

  • 控制臺列印

在這里插入圖片描述

代碼下載地址

https://gitee.com/fisher3652/es_demo

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/438081.html

標籤:其他

上一篇:kafka-python消費者讀取資料時自定義偏移量,自定義資料讀取的順序

下一篇:RabbitMQ延遲訊息問題(含Demo工程)

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 網閘典型架構簡述

    網閘架構一般分為兩種:三主機的三系統架構網閘和雙主機的2+1架構網閘。 三主機架構分別為內端機、外端機和仲裁機。三機無論從軟體和硬體上均各自獨立。首先從硬體上來看,三機都用各自獨立的主板、記憶體及存盤設備。從軟體上來看,三機有各自獨立的作業系統。這樣能達到完全的三機獨立。對于“2+1”系統,“2”分為 ......

    uj5u.com 2020-09-10 02:00:44 more
  • 如何從xshell上傳檔案到centos linux虛擬機里

    如何從xshell上傳檔案到centos linux虛擬機里及:虛擬機CentOs下執行 yum -y install lrzsz命令,出現錯誤:鏡像無法找到軟體包 前言 一、安裝lrzsz步驟 二、上傳檔案 三、遇到的問題及解決方案 總結 前言 提示:其實很簡單,往虛擬機上安裝一個上傳檔案的工具 ......

    uj5u.com 2020-09-10 02:00:47 more
  • 一、SQLMAP入門

    一、SQLMAP入門 1、判斷是否存在注入 sqlmap.py -u 網址/id=1 id=1不可缺少。當注入點后面的引數大于兩個時。需要加雙引號, sqlmap.py -u "網址/id=1&uid=1" 2、判斷文本中的請求是否存在注入 從文本中加載http請求,SQLMAP可以從一個文本檔案中 ......

    uj5u.com 2020-09-10 02:00:50 more
  • Metasploit 簡單使用教程

    metasploit 簡單使用教程 浩先生, 2020-08-28 16:18:25 分類專欄: kail 網路安全 linux 文章標簽: linux資訊安全 編輯 著作權 metasploit 使用教程 前言 一、Metasploit是什么? 二、準備作業 三、具體步驟 前言 Msfconsole ......

    uj5u.com 2020-09-10 02:00:53 more
  • 游戲逆向之驅動層與用戶層通訊

    驅動層代碼: #pragma once #include <ntifs.h> #define add_code CTL_CODE(FILE_DEVICE_UNKNOWN,0x800,METHOD_BUFFERED,FILE_ANY_ACCESS) /* 更多游戲逆向視頻www.yxfzedu.com ......

    uj5u.com 2020-09-10 02:00:56 more
  • 北斗電力時鐘(北斗授時服務器)讓網路資料更精準

    北斗電力時鐘(北斗授時服務器)讓網路資料更精準 北斗電力時鐘(北斗授時服務器)讓網路資料更精準 京準電子科技官微——ahjzsz 近幾年,資訊技術的得了快速發展,互聯網在逐漸普及,其在人們生活和生產中都得到了廣泛應用,并且取得了不錯的應用效果。計算機網路資訊在電力系統中的應用,一方面使電力系統的運行 ......

    uj5u.com 2020-09-10 02:01:03 more
  • 【CTF】CTFHub 技能樹 彩蛋 writeup

    ?碎碎念 CTFHub:https://www.ctfhub.com/ 筆者入門CTF時時剛開始刷的是bugku的舊平臺,后來才有了CTFHub。 感覺不論是網頁UI設計,還是題目質量,賽事跟蹤,工具軟體都做得很不錯。 而且因為獨到的金幣制度的確讓人有一種想去刷題賺金幣的感覺。 個人還是非常喜歡這個 ......

    uj5u.com 2020-09-10 02:04:05 more
  • 02windows基礎操作

    我學到了一下幾點 Windows系統目錄結構與滲透的作用 常見Windows的服務詳解 Windows埠詳解 常用的Windows注冊表詳解 hacker DOS命令詳解(net user / type /md /rd/ dir /cd /net use copy、批處理 等) 利用dos命令制作 ......

    uj5u.com 2020-09-10 02:04:18 more
  • 03.Linux基礎操作

    我學到了以下幾點 01Linux系統介紹02系統安裝,密碼啊破解03Linux常用命令04LAMP 01LINUX windows: win03 8 12 16 19 配置不繁瑣 Linux:redhat,centos(紅帽社區版),Ubuntu server,suse unix:金融機構,證券,銀 ......

    uj5u.com 2020-09-10 02:04:30 more
  • 05HTML

    01HTML介紹 02頭部標簽講解03基礎標簽講解04表單標簽講解 HTML前段語言 js1.了解代碼2.根據代碼 懂得挖掘漏洞 (POST注入/XSS漏洞上傳)3.黑帽seo 白帽seo 客戶網站被黑帽植入劫持代碼如何處理4.熟悉html表單 <html><head><title>TDK標題,描述 ......

    uj5u.com 2020-09-10 02:04:36 more
最新发布
  • 2023年最新微信小程式抓包教程

    01 開門見山 隔一個月發一篇文章,不過分。 首先回顧一下《微信系結手機號資料庫被脫庫事件》,我也是第一時間得知了這個訊息,然后跟蹤了整件事情的經過。下面是這起事件的相關截圖以及近日流出的一萬條資料樣本: 個人認為這件事也沒什么,還不如關注一下之前45億快遞資料查詢渠道疑似在近日復活的訊息。 訊息是 ......

    uj5u.com 2023-04-20 08:48:24 more
  • web3 產品介紹:metamask 錢包 使用最多的瀏覽器插件錢包

    Metamask錢包是一種基于區塊鏈技術的數字貨幣錢包,它允許用戶在安全、便捷的環境下管理自己的加密資產。Metamask錢包是以太坊生態系統中最流行的錢包之一,它具有易于使用、安全性高和功能強大等優點。 本文將詳細介紹Metamask錢包的功能和使用方法。 一、 Metamask錢包的功能 數字資 ......

    uj5u.com 2023-04-20 08:47:46 more
  • vulnhub_Earth

    前言 靶機地址->>>vulnhub_Earth 攻擊機ip:192.168.20.121 靶機ip:192.168.20.122 參考文章 https://www.cnblogs.com/Jing-X/archive/2022/04/03/16097695.html https://www.cnb ......

    uj5u.com 2023-04-20 07:46:20 more
  • 從4k到42k,軟體測驗工程師的漲薪史,給我看哭了

    清明節一過,盲猜大家已經無心上班,在數著日子準備過五一,但一想到銀行卡里的余額……瞬間心情就不美麗了。最近,2023年高校畢業生就業調查顯示,本科畢業月平均起薪為5825元。調查一出,便有很多同學表示自己又被平均了。看著這一資料,不免讓人想到前不久中國青年報的一項調查:近六成大學生認為畢業10年內會 ......

    uj5u.com 2023-04-20 07:44:00 more
  • 最新版本 Stable Diffusion 開源 AI 繪畫工具之中文自動提詞篇

    🎈 標簽生成器 由于輸入正向提示詞 prompt 和反向提示詞 negative prompt 都是使用英文,所以對學習母語的我們非常不友好 使用網址:https://tinygeeker.github.io/p/ai-prompt-generator 這個網址是為了讓大家在使用 AI 繪畫的時候 ......

    uj5u.com 2023-04-20 07:43:36 more
  • 漫談前端自動化測驗演進之路及測驗工具分析

    隨著前端技術的不斷發展和應用程式的日益復雜,前端自動化測驗也在不斷演進。隨著 Web 應用程式變得越來越復雜,自動化測驗的需求也越來越高。如今,自動化測驗已經成為 Web 應用程式開發程序中不可或缺的一部分,它們可以幫助開發人員更快地發現和修復錯誤,提高應用程式的性能和可靠性。 ......

    uj5u.com 2023-04-20 07:43:16 more
  • CANN開發實踐:4個DVPP記憶體問題的典型案例解讀

    摘要:由于DVPP媒體資料處理功能對存放輸入、輸出資料的記憶體有更高的要求(例如,記憶體首地址128位元組對齊),因此需呼叫專用的記憶體申請介面,那么本期就分享幾個關于DVPP記憶體問題的典型案例,并給出原因分析及解決方法。 本文分享自華為云社區《FAQ_DVPP記憶體問題案例》,作者:昇騰CANN。 DVPP ......

    uj5u.com 2023-04-20 07:43:03 more
  • msf學習

    msf學習 以kali自帶的msf為例 一、msf核心模塊與功能 msf模塊都放在/usr/share/metasploit-framework/modules目錄下 1、auxiliary 輔助模塊,輔助滲透(埠掃描、登錄密碼爆破、漏洞驗證等) 2、encoders 編碼器模塊,主要包含各種編碼 ......

    uj5u.com 2023-04-20 07:42:59 more
  • Halcon軟體安裝與界面簡介

    1. 下載Halcon17版本到到本地 2. 雙擊安裝包后 3. 步驟如下 1.2 Halcon軟體安裝 界面分為四大塊 1. Halcon的五個助手 1) 影像采集助手:與相機連接,設定相機引數,采集影像 2) 標定助手:九點標定或是其它的標定,生成標定檔案及內參外參,可以將像素單位轉換為長度單位 ......

    uj5u.com 2023-04-20 07:42:17 more
  • 在MacOS下使用Unity3D開發游戲

    第一次發博客,先發一下我的游戲開發環境吧。 去年2月份買了一臺MacBookPro2021 M1pro(以下簡稱mbp),這一年來一直在用mbp開發游戲。我大致分享一下我的開發工具以及使用體驗。 1、Unity 官網鏈接: https://unity.cn/releases 我一般使用的Apple ......

    uj5u.com 2023-04-20 07:40:19 more