Springboot 整合 Elasticsearch(五):使用RestHighLevelClient操作ES ②

📁 前情提要:

Springboot 整合 Elasticsearch(三):使用RestHighLevelClient操作ES ①

目录

[一、Springboot 整合 Elasticsearch](#一、Springboot 整合 Elasticsearch)

[1、RestHighLevelClient API介绍](#1、RestHighLevelClient API介绍)

[1.1、全查询 & 分页 & 排序](#1.1、全查询 & 分页 & 排序)

1.2、单条件查询

1.2.1、termQuery

1.2.2、matchQuery

1.2.3、短语检索

1.3、组合查询

1.4、范围查询

1.5、模糊查询

1.6、分组查询


一、Springboot 整合 Elasticsearch

1、RestHighLevelClient API介绍

目前的测试数据有:

1.1、全查询 & 分页 & 排序

java 复制代码
    @Test
    public void queryAllDoc() {
        try {
            String indexName = "forest";
            SearchRequest request = new SearchRequest();
            request.indices(indexName);

            // 构建查询的请求体
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            sourceBuilder.query(QueryBuilders.matchAllQuery());
            // 设置分页
            sourceBuilder.from(1);
            sourceBuilder.size(3);
            // 设置排序
            sourceBuilder.sort("price",  SortOrder.DESC);

            request.source(sourceBuilder);

            SearchResponse search = esConfig.restHighLevelClient().search(request, RequestOptions.DEFAULT);
            if (200 != search.status().getStatus()) {
                log.error("查询失败");
            }
            System.out.println("--------查询结果-----------");
            SearchHits hits = search.getHits();
            for (SearchHit hit : hits) {
                System.out.println(hit.getSourceAsString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

1.2、单条件查询

1.2.1、termQuery

term属于精确匹配,而且只能查单个词(一个汉字或者一个英文单词),不会对用户输入的内容进行分词;

java 复制代码
    @Test
    public void queryDocByKey() {
        try {
            String indexName = "forest";
            SearchRequest request = new SearchRequest();
            request.indices(indexName);
            // 构建查询的请求体
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            sourceBuilder.query(QueryBuilders.termQuery("price", "300"));
            request.source(sourceBuilder);

            SearchResponse search = esConfig.restHighLevelClient().search(request, RequestOptions.DEFAULT);
            if (200 != search.status().getStatus()) {
                log.error("查询失败");
            }
            System.out.println("--------查询结果-----------");
            SearchHits hits = search.getHits();
            for (SearchHit hit : hits) {
                System.out.println(hit.getSourceAsString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
1.2.2、matchQuery

match进行搜索的时候,会先进行分词拆分,拆完后,再来匹配;例如输入"枫树",match会拆分成"枫","树"两个字,只要包含其中一个字的都会被查出来。

java 复制代码
    @Test
    public void queryDocByKey() {
        try {
            String indexName = "forest";
            SearchRequest request = new SearchRequest();
            request.indices(indexName);
            // 构建查询的请求体
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            sourceBuilder.query(QueryBuilders.matchQuery("title", "枫树"));
            request.source(sourceBuilder);

            SearchResponse search = esConfig.restHighLevelClient().search(request, RequestOptions.DEFAULT);
            if (200 != search.status().getStatus()) {
                log.error("查询失败");
            }
            System.out.println("--------查询结果-----------");
            SearchHits hits = search.getHits();
            for (SearchHit hit : hits) {
                System.out.println(hit.getSourceAsString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
1.2.3、短语检索

要求所有的分词必须同时出现在文档中,同时位置必须紧邻一致

java 复制代码
    @Test
    public void queryDocByPhraseKey() {
        try {
            String indexName = "forest";
            SearchRequest request = new SearchRequest();
            request.indices(indexName);
            // 构建查询的请求体
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            sourceBuilder.query(QueryBuilders.matchPhraseQuery("title", "枫树"));
            request.source(sourceBuilder);

            SearchResponse search = esConfig.restHighLevelClient().search(request, RequestOptions.DEFAULT);
            if (200 != search.status().getStatus()) {
                log.error("查询失败");
            }
            System.out.println("--------查询结果-----------");
            SearchHits hits = search.getHits();
            for (SearchHit hit : hits) {
                System.out.println(hit.getSourceAsString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

1.3、组合查询

  • must:返回的文档必须满足must子句的条件,并且参与计算分值;
  • mustNot:返回的文档必须不满足定义的条件;
  • should:在一个bool查询中,如果没有must或者filter,有一个或者多个should子句,那么只要满足一个就可以返回;
  • filter:返回的文档必须满足filter子句的条件,但是不会像must一样,参与计算分值;
java 复制代码
    @Test
    public void queryByCombinationKey() {
        try {
            // 声明搜索条件对象
            String indexName = "forest";
            SearchRequest request = new SearchRequest();
            request.indices(indexName);
            // 构建查询的请求体
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

            boolQueryBuilder.must(QueryBuilders.matchQuery("price", 1000));
            boolQueryBuilder.should(QueryBuilders.matchQuery("id", 3));
            sourceBuilder.query(boolQueryBuilder);
            request.source(sourceBuilder);
            SearchResponse search = esConfig.restHighLevelClient().search(request, RequestOptions.DEFAULT);

            if (200 != search.status().getStatus()) {
                log.error("查询失败");
            }
            System.out.println("--------查询结果-----------");
            SearchHits hits = search.getHits();
            for (SearchHit hit : hits) {
                System.out.println(hit.getSourceAsString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

**[注]:**当使用should查询时,如果包含了must或者filter查询,那么should的查询语句就不是或者的意思了,而是有或者没有都行的含义。

1.4、范围查询

  • **闭区间查询:**QueryBuilders.rangeQuery("{fieldName}").from({fieldValue1}).to(${fieldValue2});
  • **开区间查询:**QueryBuilders.rangeQuery("{fieldName}").from({fieldValue1}, false).to(${fieldValue2}, false);
  • **大于:**QueryBuilders.rangeQuery("{fieldName}").gt({fieldValue});
  • **大于等于:**QueryBuilders.rangeQuery("{fieldName}").gte({fieldValue});
  • **小于:**QueryBuilders.rangeQuery("{fieldName}").lt({fieldValue});
  • **小于等于:**QueryBuilders.rangeQuery("{fieldName}").lte({fieldValue});
java 复制代码
 @Test
    public void queryByCombinationKey() {
        try {
            // 声明搜索条件对象
            String indexName = "forest";
            SearchRequest request = new SearchRequest();
            request.indices(indexName);
            // 构建查询的请求体
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

            boolQueryBuilder.must(QueryBuilders.rangeQuery("price").from(300).to(500));
            boolQueryBuilder.must(QueryBuilders.rangeQuery("inventory").from(500).to(1000));

            sourceBuilder.query(boolQueryBuilder);
            request.source(sourceBuilder);
            SearchResponse search = esConfig.restHighLevelClient().search(request, RequestOptions.DEFAULT);

            if (200 != search.status().getStatus()) {
                log.error("查询失败");
            }
            System.out.println("--------查询结果-----------");
            SearchHits hits = search.getHits();
            for (SearchHit hit : hits) {
                System.out.println(hit.getSourceAsString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

1.5、模糊查询

java 复制代码
    @Test
    public void queryFuzzyDocByKey() {
        try {
            String indexName = "forest";
            SearchRequest request = new SearchRequest();
            request.indices(indexName);
            // 构建查询的请求体
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            sourceBuilder.query(QueryBuilders.fuzzyQuery("title", "松").fuzziness(Fuzziness.AUTO));
            request.source(sourceBuilder);

            SearchResponse search = esConfig.restHighLevelClient().search(request, RequestOptions.DEFAULT);
            if (200 != search.status().getStatus()) {
                log.error("查询失败");
            }
            System.out.println("--------查询结果-----------");
            SearchHits hits = search.getHits();
            for (SearchHit hit : hits) {
                System.out.println(hit.getSourceAsString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

1.6、分组查询

按价格分组后求每组的条数

java 复制代码
    @Test
    public void queryGroupByKey() {
        try {
            // 声明搜索条件对象
            String indexName = "forest";
            SearchRequest request = new SearchRequest();
            request.indices(indexName);
            // 构建查询的请求体
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

            sourceBuilder.aggregation(AggregationBuilders.terms("price_groupBy").field("price"));

            request.source(sourceBuilder);
            SearchResponse search = esConfig.restHighLevelClient().search(request, RequestOptions.DEFAULT);

            if (200 != search.status().getStatus()) {
                log.error("查询失败");
            }
            List<KeyAndCount> list = new ArrayList<>();
            System.out.println("--------查询结果-----------");
            Terms terms = search.getAggregations().get("price_groupBy");
            List<? extends Terms.Bucket> buckets = terms.getBuckets();
            for (Terms.Bucket bucket : buckets) {
                KeyAndCount keyAndCount = new KeyAndCount();
                keyAndCount.setKey(bucket.getKey().toString());
                keyAndCount.setCount(bucket.getDocCount());
                list.add(keyAndCount);
                System.out.println(keyAndCount);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

相关推荐
刘大辉在路上2 小时前
突发!!!GitLab停止为中国大陆、港澳地区提供服务,60天内需迁移账号否则将被删除
git·后端·gitlab·版本管理·源代码管理
it噩梦2 小时前
es 中 terms set 使用
大数据·elasticsearch
追逐时光者3 小时前
免费、简单、直观的数据库设计工具和 SQL 生成器
后端·mysql
初晴~4 小时前
【Redis分布式锁】高并发场景下秒杀业务的实现思路(集群模式)
java·数据库·redis·分布式·后端·spring·
盖世英雄酱581364 小时前
InnoDB 的页分裂和页合并
数据库·后端
小_太_阳4 小时前
Scala_【2】变量和数据类型
开发语言·后端·scala·intellij-idea
直裾4 小时前
scala借阅图书保存记录(三)
开发语言·后端·scala
黑胡子大叔的小屋5 小时前
基于springboot的海洋知识服务平台的设计与实现
java·spring boot·毕业设计
喝醉酒的小白5 小时前
Elasticsearch 配置文件
大数据·elasticsearch·搜索引擎