elasticsearch java工具类
阅读原文时间:2023年07月12日阅读:3

docker运行elasticsearch

docker pull elasticsearch:7.8.1
docker run -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" elasticsearch:7.8.1

pom

<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>7.8.1</version>
</dependency>

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

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.12</version>
</dependency>

配置文件

/**
 * ES builder
 */
public class EsConfig {
    /**
     * es restful client builder
     * @return restful client
     */
    @Bean
    public RestClientBuilder restClientBuilder(){
        // 设置IP
        HttpHost esHost = new HttpHost("localhost", 9200);

        RestClientBuilder restClientBuilder = RestClient.builder(esHost);
        // setPassword(restClientBuilder);
        // setTImeout(restClientBuilder);

        return restClientBuilder;
    }

    /**
     * 设置超时时间
     */
    private void setTImeout(RestClientBuilder restClientBuilder) {
        restClientBuilder.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
            @Override
            public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder builder) {
                return builder.setConnectTimeout(1000)
                        .setSocketTimeout(1000);
            }
        });
    }

    /**
     * 设置ES密码
     */
    private void setPassword(RestClientBuilder restClientBuilder) {
        // 设置密码
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("userName", "password"));

        restClientBuilder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
            @Override
            public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) {
                return httpAsyncClientBuilder
                        .setDefaultCredentialsProvider(credentialsProvider)
                        .setDefaultIOReactorConfig(
                                IOReactorConfig.custom()
                                .setIoThreadCount(4)
                                .build()
                        );
            }
        });
    }
}

工具类

public class EsTools {
    public static final String INDEX = "search";

    private RestClientBuilder restClientBuilder;
    private RestHighLevelClient restHighLevelClient;

    public EsTools(){
        EsConfig esConfig = new EsConfig();
        restClientBuilder = esConfig.restClientBuilder();
        restHighLevelClient = new RestHighLevelClient(restClientBuilder);
    }

    /**
     * 通过id获取数据
     */
    public GetResponse get(String id) throws IOException {
        GetRequest request = new GetRequest(INDEX, id);
        return restHighLevelClient.get(request, RequestOptions.DEFAULT);
    }

    /**
     * 删除index
     */
    public DeleteResponse deleteIndex(String index) throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest(INDEX);
        return restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
    }

    /**
     * 插入json数据
     */
    public IndexResponse insertJson(String content) throws IOException {
        IndexRequest indexRequest = new IndexRequest(INDEX);
        indexRequest.source(content, XContentType.JSON);
        // indexRequest.id("4");
        return restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
    }

    /**
     * 批量插入json数据
     */
    public BulkResponse insertBatchJson(List<String> contentList) throws IOException{
        BulkRequest bulkRequest = new BulkRequest();
        IndexRequest indexRequest;
        for(String item : contentList){
            indexRequest = new IndexRequest(INDEX);
            indexRequest.source(item, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        return restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
    }

    public SearchResponse search(QueryBuilder queryBuilder) throws IOException {
        SearchRequest request = new SearchRequest();
        request.indices(INDEX);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(queryBuilder);
        request.source(searchSourceBuilder);

        return restHighLevelClient.search(request, RequestOptions.DEFAULT);

    }

    public static void main(String[] args) throws IOException {
        // 批量插入
        String content = "{\n" +
                "    \"search_id\":1,\n" +
                "    \"search_type\":\"task\",\n" +
                "    \"title\":\"保单贷款是什么\",\n" +
                "    \"descript\":\"保单贷款是以寿险保单的现金价值作担保,从保险公司获得的贷款。这类贷款的一次可贷款金额取决于保单的有效年份;保单签发时被保人的年龄、死亡赔偿金额。\"\n" +
                "}";
        EsTools esTools = new EsTools();
        List<String> contentList = new ArrayList<>();
        contentList.add(content);
        contentList.add(content);
        BulkResponse indexResponse = esTools.insertBatchJson(contentList);
        System.out.println(indexResponse.toString());

        String query = "贷款";
        esTools = new EsTools();
        QueryBuilder search = esTools.searchBuild(query);
        SearchResponse response = esTools.search(search);
        System.out.println(response.toString());

        if(response.getHits().getHits() != null) {
            Map result = response.getHits().getHits()[0].getSourceAsMap();
            System.out.println(result.toString());
        }
    }

    private QueryBuilder searchBuild(String query){
        /**
         * {
         *   "query": {
         *     "bool": {
         *       "must": [
         *         {
         *           "multi_match":{
         *             "query":"担保",
         *             "fields": ["title", "descript"]
         *           }
         *         },
         *         {
         *           "term":{
         *             "search_type":"batch"
         *           }
         *         }
         *       ]
         *     }
         *   }
         * }
         */
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("search_type", "task");
        boolQueryBuilder.filter(termQueryBuilder);

        MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery(query, "title", "descript");
        boolQueryBuilder.must(multiMatchQueryBuilder);
        return boolQueryBuilder;
    }
}