java操作ElasticSearch(包含聚合查询)

1、引入依赖

xml 复制代码
<!-- es工具-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
		</dependency>

2、配置es连接信息

yaml 复制代码
sring:
  elasticsearch:
    rest:
      uris: "http://localhost:9200"

3、构建索引

java 复制代码
@Document(indexName = "test_index_person")
public class TestPerson{
    public TestPerson( String personName, Integer personId, String gmtCreate, String gmtModified) {
        this.personName = personName;
        this.personId = personId;
        this.gmtCreate = gmtCreate;
        this.gmtModified = gmtModified;
    }
    public TestPerson() {

    }
    @Override
    public String toString() {
        return "TestPerson{" +
                "id='" + id + '\'' +
                ", personName='" + personName + '\'' +
                ", personId=" + personId +
                ", gmtCreate=" + gmtCreate +
                ", gmtModified=" + gmtModified +
                '}';
    }

    @Id
    private String id;

    @Field(type = FieldType.Text, analyzer = "ik_analyzer",name = "person_name")
    private String personName;
    @Field(type = FieldType.Integer,name = "person_id")
    private Integer personId;

    @Field(type = FieldType.Date,name = "gmt_create")
    private String gmtCreate;

    @Field(type = FieldType.Date,name = "gmt_modified")
    private String gmtModified;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getPersonName() {
        return personName;
    }

    public void setPersonName(String personName) {
        this.personName = personName;
    }

    public Integer getPersonId() {
        return personId;
    }

    public void setPersonId(Integer personId) {
        this.personId = personId;
    }

    public String getGmtCreate() {
        return gmtCreate;
    }

    public void setGmtCreate(String gmtCreate) {
        this.gmtCreate = gmtCreate;
    }

    public String getGmtModified() {
        return gmtModified;
    }

    public void setGmtModified(String gmtModified) {
        this.gmtModified = gmtModified;
    }
}

4、查询(包含自定义聚合查询)

java 复制代码
    @Autowired
    ElasticsearchOperations elasticsearchOperations;
    /***
     * 自定义 match 查询
     */
    @Test
    public void test6(){
        // 构建查询条件
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        // 添加基本分词查询
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("person_name", "小黑子");
        queryBuilder.withQuery(matchQueryBuilder);
        SearchHits<TestPerson> searchHits = elasticsearchOperations.search(queryBuilder.build(), TestPerson.class);
        searchHits.forEach(item ->{
            System.out.println(item);
        });
    }
    /***
     * 自定义 term 查询
     */
    @Test
    public void test7(){
        // 构建查询条件
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        // 添加基本分词查询
        TermQueryBuilder personId = QueryBuilders.termQuery("person_id", "1");
        queryBuilder.withQuery(personId);
        SearchHits<TestPerson> searchHits = elasticsearchOperations.search(queryBuilder.build(), TestPerson.class);
        searchHits.forEach(item ->{
            System.out.println(item);
        });
    }
    /***
     * 自定义 match_all 查询
     */
    @Test
    public void test8(){
        // 构建查询条件
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        // 添加基本分词查询
        MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
        queryBuilder.withQuery(matchAllQueryBuilder);
        SearchHits<TestPerson> searchHits = elasticsearchOperations.search(queryBuilder.build(), TestPerson.class);
        searchHits.forEach(item ->{
            System.out.println(item);
        });
    }
    /***
     * 自定义 match_phrase 查询
     */
    @Test
    public void test9(){
        // 构建查询条件
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        // 添加基本分词查询
        MatchPhraseQueryBuilder matchPhraseQueryBuilder = QueryBuilders.matchPhraseQuery("person_name", "小黑子");
        queryBuilder.withQuery(matchPhraseQueryBuilder);
        SearchHits<TestPerson> searchHits = elasticsearchOperations.search(queryBuilder.build(), TestPerson.class);
        searchHits.forEach(item ->{
            System.out.println(item);
        });
    }
    /***
     * 范围查询
     */
    @Test
    public void test10(){
        // 构建查询条件
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        // 添加基本分词查询
        RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("gmt_create");
        rangeQuery.gte("2024-01-31T11:00:00");
        rangeQuery.lt("2024-07-31T11:00:00");
        queryBuilder.withQuery(rangeQuery);
        SearchHits<TestPerson> searchHits = elasticsearchOperations.search(queryBuilder.build(), TestPerson.class);
        searchHits.forEach(item ->{
            System.out.println(item);
        });
    }
    /***
     * 模糊匹配
     */
    @Test
    public void test11(){
        // 构建查询条件
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        // 添加基本分词查询
        FuzzyQueryBuilder fuzzyQueryBuilder = QueryBuilders.fuzzyQuery("person_name", "张三");
        queryBuilder.withQuery(fuzzyQueryBuilder);
        SearchHits<TestPerson> searchHits = elasticsearchOperations.search(queryBuilder.build(), TestPerson.class);
        searchHits.forEach(item ->{
            System.out.println(item);
        });
    }
    /***
     * 布尔查询 必须匹配(must) 过滤(filter) 至少匹配一个(should)
     */
    @Test
    public void test12(){
        // 构建查询条件
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        // 构建布尔查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        //布尔查询下添加must
        List<QueryBuilder> must = boolQueryBuilder.must();
        TermQueryBuilder personId = QueryBuilders.termQuery("person_id", "1");
        must.add(personId);

        //布尔查询下添加filter
        List<QueryBuilder> filter = boolQueryBuilder.filter();
        RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("gmt_create");
        rangeQuery.gte("2024-07-31T10:00:00");
        filter.add(rangeQuery);

       //布尔查询下添加should
        List<QueryBuilder> should = boolQueryBuilder.should();
        TermQueryBuilder shouldTerm = QueryBuilders.termQuery("person_id", "111");
        should.add(shouldTerm);
        //布尔查询下添加must_not
        List<QueryBuilder> queryBuilders = boolQueryBuilder.mustNot();
        TermQueryBuilder mustNotTerm = QueryBuilders.termQuery("person_name", "哈哈哈");
        queryBuilders.add(mustNotTerm);

        //构建布尔查询语法,准备执行
        queryBuilder.withQuery(boolQueryBuilder);
        SearchHits<TestPerson> searchHits = elasticsearchOperations.search(queryBuilder.build(), TestPerson.class);
        searchHits.forEach(item ->{
            System.out.println(item);
        });
    }
    /***
     * 分页
     */
    @Test
    public void test13(){
        // 构建查询条件
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        // 查询全部
        MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
        queryBuilder.withQuery(matchAllQueryBuilder);


        Pageable pageable = PageRequest.of(0, 10, Sort.by("personId").descending());

        queryBuilder.withPageable(pageable);
        SearchHits<TestPerson> searchHits = elasticsearchOperations.search(queryBuilder.build(), TestPerson.class);
        searchHits.forEach(item ->{
            System.out.println(item);
        });
    }
    /***
     * 对查询出来的值进行聚合查询 统计每个唯一值的个数
     */
    @Test
    public void test14(){
        // 构建查询条件
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        //查询数据
        MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("person_name", "张三");
        queryBuilder.withQuery(matchQuery);
        //聚合数据
        TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms("test_aggs").field("gmt_create");
        queryBuilder.addAggregation(termsAggregationBuilder);
        SearchHits<TestPerson> searchHits = elasticsearchOperations.search(queryBuilder.build(), TestPerson.class);
        searchHits.forEach(item ->{
            System.out.println(item);
        });
        Aggregations aggregations = searchHits.getAggregations();
        // 检查 aggregations 是否为 null
        if (aggregations != null) {
            // 第二步:通过聚合名称获取特定的聚合结果
            Terms testAggs = aggregations.get("test_aggs");
            // 检查特定聚合是否存在
            if (testAggs != null) {
                // 第三步:遍历聚合中的桶(buckets)
                for (Terms.Bucket bucket : testAggs.getBuckets()) {
                    // 获取桶的键(在这个例子中是 gmt_create 的值)
                    String keyAsString = bucket.getKeyAsString();
                    // 获取桶中文档的数量
                    long docCount = bucket.getDocCount();
                    // 打印或处理每个桶的结果
                    System.out.println("Key: " + keyAsString + ", DocCount: " + docCount);
                }
            }
        }
    }
    /***
     * 对查询出来的值进行聚合查询 统计每个唯一值的个数  仅仅返回聚合结果
     */
    @Test
    public void test15(){
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        //仅仅返回聚合结果
        queryBuilder.withPageable(PageRequest.of(0,1));
        //查询数据
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("person_name", "张三");
        queryBuilder.withQuery(matchQueryBuilder);
        //聚合
        TermsAggregationBuilder aggregationBuilder = AggregationBuilders.terms("test_aggs").field("gmt_create");
        queryBuilder.addAggregation(aggregationBuilder);
        //获取聚合信息
        SearchHits<TestPerson> search = elasticsearchOperations.search(queryBuilder.build(), TestPerson.class);
        Aggregations aggregations = search.getAggregations();
        if (aggregations != null){
            Terms terms = aggregations.get("test_aggs");
            List<? extends Terms.Bucket> buckets = terms.getBuckets();
            buckets.forEach(item ->{
                System.out.println("key:"+item.getKeyAsString()  +"===="+"doc_count:"+item.getDocCount());
            });
        }

    }
    /***
     * 多个聚合
     */
    @Test
    public void test16(){
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        //仅仅返回聚合结果
        queryBuilder.withPageable(PageRequest.of(0,1));
        TermsAggregationBuilder test_aggs = AggregationBuilders.terms("test_aggs").field("gmt_create");
        queryBuilder.addAggregation(test_aggs);
        AvgAggregationBuilder test_aggs2 = AggregationBuilders.avg("test_aggs2").field("person_id");
        queryBuilder.addAggregation(test_aggs2);
        SearchHits<TestPerson> search = elasticsearchOperations.search(queryBuilder.build(), TestPerson.class);
        Aggregations aggregations = search.getAggregations();
        if (aggregations != null){
            Terms test_aggs1 = aggregations.get("test_aggs");
            if (test_aggs != null){
                test_aggs1.getBuckets().forEach(item ->{
                    System.out.println("key:"+ item.getKeyAsString()+"===="+"doc_count:"+item.getDocCount());
                });
            }
            Avg test2_aggs = aggregations.get("test_aggs2");
            System.out.println( test2_aggs.getValue());
        }
    }
    /***
     * 子聚合 先分组,再计算
     */
    @Test
    public void test17(){
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        queryBuilder.withPageable(PageRequest.of(0,1));
        TermsAggregationBuilder test_aggs = AggregationBuilders.terms("test_aggs").field("gmt_create");
        test_aggs.subAggregation(AggregationBuilders.avg("son_aggs_test").field("person_id"));
        queryBuilder.addAggregation(test_aggs);
        SearchHits<TestPerson> search = elasticsearchOperations.search(queryBuilder.build(), TestPerson.class);
        Aggregations aggregations = search.getAggregations();
        Terms testAgges =  aggregations.get("test_aggs");
        testAgges.getBuckets().forEach(item ->{
            Avg aggregations1 = item.getAggregations().get("son_aggs_test");
            System.out.println("key:"+item.getKeyAsString()+"--doc_count:"+item.getKeyAsString()+"--son_aggs_test"+aggregations1.getValue());
        });
    }
    /**
     * 取聚合最大值
     */
    @Test
    public void test18(){
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        queryBuilder.addAggregation(AggregationBuilders.max("test_agg").field("person_id"));
        SearchHits<TestPerson> search = elasticsearchOperations.search(queryBuilder.build(), TestPerson.class);
        Aggregations aggregations = search.getAggregations();
        Max test_agg = aggregations.get("test_agg");
        System.out.println(test_agg.getValue());
    }
相关推荐
新手小袁_J11 分钟前
JDK11下载安装和配置超详细过程
java·spring cloud·jdk·maven·mybatis·jdk11
呆呆小雅12 分钟前
C#关键字volatile
java·redis·c#
Monly2112 分钟前
Java(若依):修改Tomcat的版本
java·开发语言·tomcat
Ttang2315 分钟前
Tomcat原理(6)——tomcat完整实现
java·tomcat
钱多多_qdd25 分钟前
spring cache源码解析(四)——从@EnableCaching开始来阅读源码
java·spring boot·spring
waicsdn_haha27 分钟前
Java/JDK下载、安装及环境配置超详细教程【Windows10、macOS和Linux图文详解】
java·运维·服务器·开发语言·windows·后端·jdk
Q_192849990638 分钟前
基于Spring Boot的摄影器材租赁回收系统
java·spring boot·后端
Code_流苏40 分钟前
VSCode搭建Java开发环境 2024保姆级安装教程(Java环境搭建+VSCode安装+运行测试+背景图设置)
java·ide·vscode·搭建·java开发环境
禁默1 小时前
深入浅出:AWT的基本组件及其应用
java·开发语言·界面编程
Cachel wood1 小时前
python round四舍五入和decimal库精确四舍五入
java·linux·前端·数据库·vue.js·python·前端框架