谷粒商城125、全文检索-ElasticSearch-整合-SpringBoot整合high-level-client

1.7、elasticsearch-Rest-Client
java操作es有两种方式

9300: TCP
spring-data-elasticsearch:transport-api.jar;
springboot版本不同,ransport-api.jar不同,不能适配es版本
7.x已经不建议使用,8以后就要废弃
9200: HTTP
有诸多包
jestClient: 非官方,更新慢;
RestTemplate:模拟HTTP请求,ES很多操作需要自己封装,麻烦;
HttpClient:同上;
Elasticsearch-Rest-Client:官方RestClient,封装了ES操作,API层次分明,上手简单;
最终选择Elasticsearch-Rest-Client(elasticsearch-rest-high-level-client)

https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high.html

转载自博客
https://blog.csdn.net/m0_49183244/article/details/123955156

1.8、SpringBoot整合ES


创建项目 gulimall-search

选择依赖web,但不要在里面选择es。 并做降版本处理

1.8.1、配置基本的项目


第一步、导入依赖

这里的版本要和所按照的ELK版本匹配

<?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.2.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.atguigu.gulimall</groupId>
    <artifactId>gulimall-search</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>gulimall-search</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Hoxton.SR3</spring-cloud.version>
        <elasticsearch.version>7.9.2</elasticsearch.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.atguigu.gulimall</groupId>
            <artifactId>gulimall-common</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.9.2</version>
        </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>
            </plugin>
        </plugins>
    </build>

</project>

默认情况下在spring-boot-dependencies中所依赖的ES版本位6.8.4,要改掉,如何去掉了

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Hoxton.SR3</spring-cloud.version>
        <elasticsearch.version>7.9.2</elasticsearch.version>
    </properties>

 

查是否去掉:查看maven依赖的库是否正确,如果没有去掉下面的依赖的包为6.8.4

 

 

第二步、编写配置,给容器中注入一个 RestHighLevelClient
编写配置,给容器中注入一个 RestHighLevelClient

在 com.hgw.gulimall.search.config包下创建一个ES的配置类

请求测试项,比如es添加了安全访问规则,访问es需要添加一个安全头,就可以通过requestOptions设置

官方建议把requestOptions创建成单实例

@Configuration
public class GulimallElasticSearchConfig {
    public static final RequestOptions COMMON_OPTIONS;

    static {
        RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
        COMMON_OPTIONS = builder.build();
    }

    @Bean
    public RestHighLevelClient esRestClient() {
        RestClientBuilder builder = null;
        // 可以指定多个es
        builder = RestClient.builder(new HttpHost("124.222.223.222",9200,"http"));
        RestHighLevelClient client = new RestHighLevelClient(builder);
        return client;
    }
}

我们的es集群使用了用户名和密码

package com.atguigu.gulimall.search;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 1、导入依赖
 * 2、编写配置,给容器中注入一个RestHighLevelClient
 * 3、参照API https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.4/index.html
 */
@Configuration
public class GulimallElasticSearchConfig {

    private String hosts;
    public static final RequestOptions COMMON_OPTIONS;

    static {
        RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
//        builder.addHeader("Authorization", "Bearer " + TOKEN);
//        builder.setHttpAsyncResponseConsumerFactory(
//                new HttpAsyncResponseConsumerFactory
//                        .HeapBufferedResponseConsumerFactory(30 * 1024 * 1024 * 1024));
        COMMON_OPTIONS = builder.build();
    }

    @Bean
    public RestHighLevelClient esRestClient() {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,

                new UsernamePasswordCredentials("elastic", "123456"));

        RestClientBuilder builder = RestClient.builder(new HttpHost("192.168.175.144", 9200))

                .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {

                    @Override

                    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {

                        return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);

                    }

                });

        RestHighLevelClient client = new RestHighLevelClient(builder);
        return client;
    }

}

1.8.2、具体的Api测试


1.8.2.1、创建索引
package com.atguigu.gulimall.search;

import lombok.ToString;
import org.elasticsearch.action.index.IndexResponse;
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.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.Avg;
import org.elasticsearch.search.aggregations.metrics.AvgAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.runner.RunWith;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.alibaba.fastjson.JSON;
import lombok.Data;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@SpringBootTest
@RunWith(SpringRunner.class)
public class GulimallSearchApplicationTests {

    @Resource
    private RestHighLevelClient client;




    /**
     * 测试存储数据到es
     */
    @Test
    public void indexData() throws IOException {
       IndexRequest indexRequest = new IndexRequest("users");//向users下存数据
        indexRequest.id("1");//不设会自动生成
//        indexRequest.source("userName", "zhangsan","age", 18,"gender", "男");//数据内容形式,k-v形式
        User user= new User();
        user.setUserName("zhangsan");
        user.setAge(18);
        user.setGender("");
        String jsonString = JSON.toJSONString(user);
        indexRequest.source(jsonString, XContentType.JSON);//数据内容形式,json形式
        //执行操作。索引数据不存在数据就生成,存在就更新
        IndexResponse index = client.index(indexRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
        System.out.println(index);
    }
    @Data
    static
    class User{
        private String userName;
        private Integer age;
        private String gender;
    }


    /**
     * 复杂检索:在bank中搜索address中包含mill的所有人的年龄分布以及平均年龄,平均薪资
     * @throws IOException
     */
    @Test
    public void searchData() throws IOException {
        //1. 创建检索请求
        SearchRequest searchRequest = new SearchRequest();

        //1.1)指定索引
        searchRequest.indices("bank");
        //1.2)构造检索条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(QueryBuilders.matchQuery("address","Mill"));

        //1.2.1)按照年龄分布进行聚合
        TermsAggregationBuilder ageAgg= AggregationBuilders.terms("ageAgg").field("age").size(10);
        sourceBuilder.aggregation(ageAgg);

        //1.2.2)计算平均年龄
        AvgAggregationBuilder ageAvg = AggregationBuilders.avg("ageAvg").field("age");
        sourceBuilder.aggregation(ageAvg);
        //1.2.3)计算平均薪资
        AvgAggregationBuilder balanceAvg = AggregationBuilders.avg("balanceAvg").field("balance");
        sourceBuilder.aggregation(balanceAvg);

        System.out.println("检索条件:"+sourceBuilder);
        searchRequest.source(sourceBuilder);
        //2. 执行检索
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        System.out.println("检索结果:"+searchResponse);

        //3. 将检索结果封装为Bean
        SearchHits hits = searchResponse.getHits();
        SearchHit[] searchHits = hits.getHits();
        for (SearchHit searchHit : searchHits) {
            String sourceAsString = searchHit.getSourceAsString();
            Account account = JSON.parseObject(sourceAsString, Account.class);
            System.out.println(account);

        }

        //4. 获取聚合信息
        Aggregations aggregations = searchResponse.getAggregations();

        Terms ageAgg1 = aggregations.get("ageAgg");

        for (Terms.Bucket bucket : ageAgg1.getBuckets()) {
            String keyAsString = bucket.getKeyAsString();
            System.out.println("年龄:"+keyAsString+" ==> "+bucket.getDocCount());
        }
        Avg ageAvg1 = aggregations.get("ageAvg");
        System.out.println("平均年龄:"+ageAvg1.getValue());

        Avg balanceAvg1 = aggregations.get("balanceAvg");
        System.out.println("平均薪资:"+balanceAvg1.getValue());


    }


    /**
     * SearchRequest 搜索请求
     * SearchSourceBuilder 条件构造
     * HighlightBuilder 构建高亮
     * TermQueryBuilder 精确查询
     * MatchAllQueryBuilder 匹配所有
     * XXXQueryBuilder 对应所有命令
     */
    @Test
    public void testSearch() throws IOException {
        // 1、创建检索的请求
        SearchRequest searchRequest = new SearchRequest("bank");

        // 2、封装检索的构建
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 2.1)构件检索条件
        sourceBuilder.query(QueryBuilders.matchQuery("address","mill"));
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        // 3、构建放到请求里面
        searchRequest.source(sourceBuilder);

        // 4、执行请求
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        System.out.println(JSON.toJSON(searchResponse.getHits()));
        System.out.println("=====================");
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            System.out.println(hit.getSourceAsMap());
        }

    }

    @ToString
    @Data
    static class Account {
        private int account_number;
        private int balance;
        private String firstname;
        private String lastname;
        private int age;
        private String gender;
        private String address;
        private String employer;
        private String email;
        private String city;
        private String state;
    }


}
// 测试索引的创建 Request
@Test
public void testCreateIndex() throws IOException {
    // 1、创建索引请求
    CreateIndexRequest request = new CreateIndexRequest("hgw_index");
    // 2、执行创建请求 IndicesClient,请求后获得响应
    CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
    System.out.println(createIndexResponse);
}

 

 

1.8.2.2、获取索引(判断索引是否存在)

获取索引

// 测试获取索引
@Test
public void testGetIndex() throws IOException {
    GetIndexRequest request = new GetIndexRequest("hgw_index");
    boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
    System.out.println(exists);
}
1.8.2.3、删除索引

删除索引

// 测试删除索引
@Test
public void testDeleteIndex() throws IOException {
    DeleteIndexRequest request = new DeleteIndexRequest("hgw_index");
    AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
    System.out.println(delete.isAcknowledged());
}
1.8.2.4、CRUD文档

1.8.2.4.1、增加
@Test
public void testAddDocument() throws IOException {
    // 创建请求体内容
    User user = new User();
    user.setName("hgw");
    user.setGender("");
    user.setAge(21);
    String UserJson = JSON.toJSONString(user);

    // 创建请求
    IndexRequest request = new IndexRequest("hgw_index");

    // 规则 PUT /hgw_index/_doc/1
    request.id("1");
    request.timeout(TimeValue.timeValueSeconds(1));
    request.timeout("1s");

    // 将我们的数据放入请求JSON, 并且指定泛指的类型
    request.source(UserJson, XContentType.JSON);

    // 客户端发送请求,获取响应的结果
    IndexResponse indexResponse = client.index(request, GulimallElasticSearchConfig.COMMON_OPTIONS);

    System.out.println(indexResponse.toString());   
    System.out.println(indexResponse.status()); // 对应我们命令返回的状态 CREATED

}

IndexResponse[index=hgw_index,type=_doc,id=1,version=1,result=created,seqNo=0,primaryTerm=1,shards={"total":2,"successful":1,"failed":0}]

批量增加
————————————————

@Test
public void testBulkRequest() throws IOException {
    BulkRequest bulkRequest = new BulkRequest();
    bulkRequest.timeout("10s");

    ArrayList<User> userList = new ArrayList<>();
    userList.add(new User("hwg1", "", 18));
    userList.add(new User("hwg2", "", 19));
    userList.add(new User("hwg3", "", 20));
    userList.add(new User("hwg4", "", 21));
    userList.add(new User("hly5", "", 22));

    // 批处理请求
    for (int i = 0; i < userList.size(); i++) {
        bulkRequest.add(new IndexRequest("hgw_index")
                .id(""+(i+1))
                .source(JSON.toJSONString(userList.get(i)), XContentType.JSON)
        );
    }
    BulkResponse bulk = client.bulk(bulkRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
    System.out.println(bulk.hasFailures()); // 是否失败,返回false表示成功
}
1.8.2.4.2、查找

获取文档的信息

// 获取文档的信息
@Test
public void testGetDocument() throws IOException {
    GetRequest getRequest = new GetRequest("hgw_index","1");
    GetResponse getResponse = client.get(getRequest,  GulimallElasticSearchConfig.COMMON_OPTIONS);
    System.out.println(getResponse.getSourceAsString());    // 打印文档的内容
    System.out.println(getResponse);   // 返回的全部内容和命令是一样的
}

获取文档 (判断是否存在)

// 获取文档,判断是否存在 get /index/doc/1
@Test
public void testIsExists() throws IOException {
    GetRequest getRequest = new GetRequest("hgw_index", "1");
    // 不获取返回的 _source 的上下文了
    getRequest.fetchSourceContext(new FetchSourceContext(false));
    getRequest.storedFields("_none_");

    boolean exists = client.exists(getRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
    System.out.println(exists);
}
1.8.2.4.3、修改

更新文档的信息

// 更新文档的信息
@Test
public void testUpdateDocument() throws IOException {
    UpdateRequest updateRequest = new UpdateRequest("hgw_index","1");
    updateRequest.timeout("1s");

    User user = new User("黄龚伟", "",50);
    updateRequest.doc(JSON.toJSONString(user),XContentType.JSON);

    UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
    System.out.println(updateResponse.status());
}
1.8.2.4.4、删除

删除文档记录

// 删除文档的纪律
@Test
public void testDeleteRequest() throws IOException {
    DeleteRequest deleteRequest = new DeleteRequest("hgw_index","1");
    deleteRequest.timeout("1s");

    DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
    System.out.println(deleteResponse.status());
}
1.8.2.5.1、普通检索

普通检索

/**
 * SearchRequest 搜索请求
 * SearchSourceBuilder 条件构造
 * HighlightBuilder 构建高亮
 * TermQueryBuilder 精确查询
 * MatchAllQueryBuilder 匹配所有
 * XXXQueryBuilder 对应所有命令
 */
@Test
public void testSearch() throws IOException {
    // 1、创建检索的请求
    SearchRequest searchRequest = new SearchRequest("bank");

    // 2、封装检索的构建
    SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
    // 2.1)构件检索条件
    sourceBuilder.query(QueryBuilders.matchQuery("address","mill"));
    sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

    // 3、构建放到请求里面
    searchRequest.source(sourceBuilder);

    // 4、执行请求
    SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
    System.out.println(JSON.toJSON(searchResponse.getHits()));
    System.out.println("=====================");
    for (SearchHit hit : searchResponse.getHits().getHits()) {
        System.out.println(hit.getSourceAsMap());
    }

}
1.8.2.5.2、复杂检索

搜索address中包含mill的所有人的年龄分布,平均薪资

@Test
public void searchData() throws IOException {
    // 1、创建检索请求
    SearchRequest searchRequest = new SearchRequest();
    // 指定索引
    searchRequest.indices("bank");
    // 指定DSL,索引条件
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    // 1.1)构件检索条件
    searchSourceBuilder.query(QueryBuilders.matchQuery("address", "mill"));
    // 按照年年龄的值分布进行聚合
    TermsAggregationBuilder ageAgg = AggregationBuilders.terms("ageAgg").field("age").size(10);
    searchSourceBuilder.aggregation(ageAgg);
    // 计算平均薪资进行聚合
    AvgAggregationBuilder balanceAvg = AggregationBuilders.avg("balanceAvg").field("balance");
    searchSourceBuilder.aggregation(balanceAvg);
    
    searchRequest.source(searchSourceBuilder);

    // 2、执行检索
    SearchResponse searchResponse = client.search(searchRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);

    // 3、分析结果
    System.out.println(searchResponse.toString());

 

 

 

博客2:

https://blog.csdn.net/qq_41596346/article/details/121989068

https://blog.csdn.net/qq_41596346/article/details/121989068

 

 

 

 

 

 

 

1.search API详情请参考添加链接描述


2.查询条件

@Testpublic void searchData() throws IOException {    //1. 创建检索请求    SearchRequest searchRequest = new SearchRequest();
    //1.1)指定索引    searchRequest.indices("bank");    //1.2)构造检索条件    SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();    sourceBuilder.query(QueryBuilders.matchQuery("address", "Mill"));
    System.out.println("检索条件: " + sourceBuilder);    searchRequest.source(sourceBuilder);        //2. 执行检索    SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);    System.out.println("检索结果: " + searchResponse);}123456789101112131415161718结果:
检索条件: {"query":{"match":{"address":{"query":"Mill","operator":"OR","prefix_length":0,"max_expansions":50,"fuzzy_transpositions":true,"lenient":false,"zero_terms_query":"NONE","auto_generate_synonyms_phrase_query":true,"boost":1.0}}}}
检索结果: {"took":6,"timed_out":false,"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},"hits":{"total":{"value":4,"relation":"eq"},"max_score":5.4032025,"hits":[{"_index":"bank","_type":"account","_id":"970","_score":5.4032025,"_source":{"account_number":970,"balance":19648,"firstname":"Forbes","lastname":"Wallace","age":28,"gender":"M","address":"990 Mill Road","employer":"Pheast","email":"forbeswallace@pheast.com","city":"Lopezo","state":"AK"}},{"_index":"bank","_type":"account","_id":"136","_score":5.4032025,"_source":{"account_number":136,"balance":45801,"firstname":"Winnie","lastname":"Holland","age":38,"gender":"M","address":"198 Mill Lane","employer":"Neteria","email":"winnieholland@neteria.com","city":"Urie","state":"IL"}},{"_index":"bank","_type":"account","_id":"345","_score":5.4032025,"_source":{"account_number":345,"balance":9812,"firstname":"Parker","lastname":"Hines","age":38,"gender":"M","address":"715 Mill Avenue","employer":"Baluba","email":"parkerhines@baluba.com","city":"Blackgum","state":"KY"}},{"_index":"bank","_type":"account","_id":"472","_score":5.4032025,"_source":{"account_number":472,"balance":25571,"firstname":"Lee","lastname":"Long","age":32,"gender":"F","address":"288 Mill Street","employer":"Comverges","email":"leelong@comverges.com","city":"Movico","state":"MT"}}]}}12343.聚合条件
在测试类中添加静态内部类
@ToString@Datastatic class Account {    private int account_number;    private int balance;    private String firstname;    private String lastname;    private int age;    private String gender;    private String address;    private String employer;    private String email;    private String city;    private String state;}123456789101112131415测试方法
@Testpublic void searchData() throws IOException {     //1. 创建检索请求     SearchRequest searchRequest = new SearchRequest();
     //1.1)指定索引     searchRequest.indices("bank");     //1.2)构造检索条件     SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();     sourceBuilder.query(QueryBuilders.matchQuery("address", "Mill"));

     //1.2.1)按照年龄分布进行聚合     TermsAggregationBuilder ageAgg = AggregationBuilders.terms("ageAgg").field("age").size(10);     sourceBuilder.aggregation(ageAgg);
     //1.2.2)计算平均年龄     AvgAggregationBuilder ageAvg = AggregationBuilders.avg("ageAvg").field("age");     sourceBuilder.aggregation(ageAvg);
     //1.2.3)计算平均薪资     AvgAggregationBuilder balanceAvg = AggregationBuilders.avg("balanceAvg").field("balance");     sourceBuilder.aggregation(balanceAvg);
     System.out.println("检索条件: " + sourceBuilder);     searchRequest.source(sourceBuilder);     System.out.println();
     //2. 执行检索     SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);     System.out.println("检索结果: " + searchResponse);     System.out.println();
     //3. 将检索结果封装为Bean     SearchHits hits = searchResponse.getHits();     SearchHit[] searchHits = hits.getHits();     for (SearchHit searchHit : searchHits) {         String sourceAsString = searchHit.getSourceAsString();         Account account = JSON.parseObject(sourceAsString, Account.class);         System.out.println(account);     } }123456789101112131415161718192021222324252627282930313233343536373839404142结果如下:
在线JSON格式化后与我们在kibana中是一致的

4.分析结果

 /**  * 复杂检索:在bank中搜索address中包含mill的所有人的年龄分布以及平均年龄,平均薪资  * @throws IOException  */ @Test public void searchData() throws IOException {     //1. 创建检索请求     SearchRequest searchRequest = new SearchRequest();
     //1.1)指定索引     searchRequest.indices("bank");     //1.2)构造检索条件     SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();     sourceBuilder.query(QueryBuilders.matchQuery("address", "Mill"));

     //1.2.1)按照年龄分布进行聚合     TermsAggregationBuilder ageAgg = AggregationBuilders.terms("ageAgg").field("age").size(10);     sourceBuilder.aggregation(ageAgg);
     //1.2.2)计算平均年龄     AvgAggregationBuilder ageAvg = AggregationBuilders.avg("ageAvg").field("age");     sourceBuilder.aggregation(ageAvg);
     //1.2.3)计算平均薪资     AvgAggregationBuilder balanceAvg = AggregationBuilders.avg("balanceAvg").field("balance");     sourceBuilder.aggregation(balanceAvg);
     System.out.println("检索条件: " + sourceBuilder);     searchRequest.source(sourceBuilder);     System.out.println();
     //2. 执行检索     SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);     System.out.println("检索结果: " + searchResponse);     System.out.println();
     //3. 将检索结果封装为Bean     SearchHits hits = searchResponse.getHits();     SearchHit[] searchHits = hits.getHits();     for (SearchHit searchHit : searchHits) {         String sourceAsString = searchHit.getSourceAsString();         Account account = JSON.parseObject(sourceAsString, Account.class);         System.out.println(account);     }     System.out.println();
     //4. 获取聚合信息     Aggregations aggregations = searchResponse.getAggregations();     Terms ageAgg1 = aggregations.get("ageAgg");     for (Terms.Bucket bucket : ageAgg1.getBuckets()) {         String keyAsString = bucket.getKeyAsString();         System.out.println("年龄: " + keyAsString + " ==> " + bucket.getDocCount());     }          Avg ageAvg1 = aggregations.get("ageAvg");     System.out.println("平均年龄: " + ageAvg1.getValue());     System.out.println();
     Avg balanceAvg1 = aggregations.get("balanceAvg");     System.out.println("平均薪资: " + balanceAvg1.getValue()); }1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162

————————————————版权声明:本文为CSDN博主「Java小生不才」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。原文链接:https://blog.csdn.net/qq_41596346/article/details/121989068

posted on 2022-07-19 16:57  luzhouxiaoshuai  阅读(270)  评论(0编辑  收藏  举报

导航