ElasticSearch的DSL查询

ElasticSearch的DSL查询

准备工作

创建测试方法,初始化测试结构。

java 复制代码
import org.apache.http.HttpHost;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.util.Map;

public class DemoTest {
    private RestHighLevelClient client;

    /**
     * * 因为下面会重复使用输出语句所以就单独抽出来封装了
     *
     * @param response 查询结果响应体
     */
    public static void handelResponse(SearchResponse response) {
        // 查询的总数
        TotalHits total = response.getHits().getTotalHits();
        System.out.println("total===>" + total);

        SearchHits searchHits = response.getHits();
        // 输出查询结果
        searchHits.forEach(hit -> {
            // 查询时JSON数据,可以使用实体将其转换。
            String json = hit.getSourceAsString();
            System.out.println(json);

            // 高亮返回体
            Map<String, HighlightField> map = hit.getHighlightFields();
            if (map != null) {
                System.out.println("-----------------高亮显示---------------");
                HighlightField highlightField = map.get("name");
                System.out.println("name===>" + highlightField.getName());
                System.out.println("fragments===>" + highlightField.getFragments()[0]);
            }
        });
    }

    @BeforeEach
    void setup() {
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.3.98:9200"))
        );
    }

    @AfterEach
    void teardown() throws IOException {
        this.client.close();
    }
}

DSL查询

普通查询全部

new SearchRequest("hotel")查询索引库名称。

java 复制代码
@Test
void testMatchAll() throws IOException {
    // 指定查询的索引库
    SearchRequest request = new SearchRequest("hotel");

    // 查询全部内容
    request.source().query(QueryBuilders.matchAllQuery());

    // 得到查询返回体,传入返回体到封装的返回体输出
    SearchResponse response = client.search(request, RequestOptions.DEFAULT);
    handelResponse(response);
}

对应控制台。

shell 复制代码
# 查询所有
GET /_search
{
  "query": {
    "match_all": {}
  }
}

match查询-单字段查询

java 复制代码
// match查询-单字段查询
@Test
void testMatch() throws IOException {
    // 指定查询的索引库
    SearchRequest request = new SearchRequest("hotel");

    // 查询内容
    request.source().query(QueryBuilders.matchQuery("all", "如家"));

    // 得到查询返回体,传入返回体到封装的返回体输出
    SearchResponse response = client.search(request, RequestOptions.DEFAULT);
    handelResponse(response);
}

对应控制台。

shell 复制代码
# match,根据单字段查询,推荐使用
GET /hotel/_search
{
  "query": {
    "match": {
      "all": "外滩如家"
    }
  }
}

match查询-多字段查询

java 复制代码
@Test
void testMultiMatchQuery() throws IOException {
    // 指定查询的索引库
    SearchRequest request = new SearchRequest("hotel");

    // 查询内容
    request.source().query(QueryBuilders.multiMatchQuery("如家", "name", "business"));

    // 得到查询返回体,传入返回体到封装的返回体输出
    SearchResponse response = client.search(request, RequestOptions.DEFAULT);
    handelResponse(response);
}

对应控制台。

shell 复制代码
# multi_match 多字段查询,不推荐,性能低
GET /hotel/_search
{
  "query": {
    "multi_match": {
      "query": "外滩如家",
      "fields": ["name","brand","business"]
    }
  }
}

精确查询

java 复制代码
@Test
void termQuery() throws IOException {
    // 指定查询的索引库
    SearchRequest request = new SearchRequest("hotel");

    // 查询内容-精确查找
    request.source().query(QueryBuilders.termQuery("city", "深圳"));

    // 得到查询返回体,传入返回体到封装的返回体输出
    SearchResponse response = client.search(request, RequestOptions.DEFAULT);
    handelResponse(response);
}

对应控制台。

shell 复制代码
# 精确查找-term,不会分词
GET /hotel/_search
{
  "query": {
    "term": {
      "city": {
        "value": "上海"
      }
    }
  }
}

范围查找

java 复制代码
@Test
void testRange() throws IOException {
    // 指定查询的索引库
    SearchRequest request = new SearchRequest("hotel");

    // 查询内容
    request.source().query(QueryBuilders.rangeQuery("price").gte(100).lt(150));

    // 得到查询返回体,传入返回体到封装的返回体输出
    SearchResponse response = client.search(request, RequestOptions.DEFAULT);
    handelResponse(response);
}

对应控制台。

shell 复制代码
# range 范围查询
GET /hotel/_search
{
  "query": {
    "range": {
      "price": {
        "gte": 100,
        "lte": 300
      }
    }
  }
}

布尔查询

java 复制代码
@Test
void testBoolean() throws IOException {
    // 指定查询的索引库
    SearchRequest request = new SearchRequest("hotel");

    // 查询内容
    BoolQueryBuilder query = QueryBuilders.boolQuery();
    query.must(QueryBuilders.termQuery("city", "杭州"));
    query.filter(QueryBuilders.rangeQuery("price").lt(250));

    // 得到查询返回体,传入返回体到封装的返回体输出
    SearchResponse response = client.search(request, RequestOptions.DEFAULT);
    handelResponse(response);
}

对应控制台。

shell 复制代码
# 不等于gt,lt不等于
GET /hotel/_search
{
  "query": {
    "range": {
      "FIELD": {
        "gt": 10,
        "lt": 20
      }
    }
  }
}

排序、分页

java 复制代码
@Test
void testFrom() throws IOException {
    // 页码,每页大小
    int page = 1, size = 5;
    // 指定查询的索引库
    SearchRequest request = new SearchRequest("hotel");

    // 查询内容
    request.source().query(QueryBuilders.matchAllQuery());
    request.source().from((page - 1) * size).size(5);
    request.source().sort("price", SortOrder.ASC);

    // 得到查询返回体,传入返回体到封装的返回体输出
    SearchResponse response = client.search(request, RequestOptions.DEFAULT);
    handelResponse(response);
}

高亮

java 复制代码
@Test
void testHighLighter() throws IOException {
    // 指定查询的索引库
    SearchRequest request = new SearchRequest("hotel");

    // 查询内容
    request.source().query(QueryBuilders.matchQuery("all", "如家"));
    request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));

    // 得到查询返回体,传入返回体到封装的返回体输出
    SearchResponse response = client.search(request, RequestOptions.DEFAULT);
    handelResponse(response);
}

对应控制台。

shell 复制代码
# 搜索结果高亮显示,默认字段必须与高亮字段一致,默认是em标签
GET /hotel/_search
{
  "query": {
    "match": {
      "all": "如家"
    }
  },
  "highlight": {
    "fields": {
      "name": {
        "require_field_match": "false",
        "pre_tags": "<i>",
        "post_tags": "</i>"
      }
    }
  }, 
  "from": 0,
  "size": 20
}
相关推荐
Elastic 中国社区官方博客7 小时前
使用真实 Elasticsearch 进行高级集成测试
大数据·数据库·elasticsearch·搜索引擎·全文检索·jenkins·集成测试
好记性+烂笔头7 小时前
4 Spark Streaming
大数据·ajax·spark
好记性+烂笔头11 小时前
3 Flink 运行架构
大数据·架构·flink
字节侠11 小时前
Flink2支持提交StreamGraph到Flink集群
大数据·flink·streamgraph·flink2·jobgraph
画船听雨眠aa14 小时前
gitlab云服务器配置
服务器·git·elasticsearch·gitlab
好记性+烂笔头14 小时前
4 Hadoop 面试真题
大数据·hadoop·面试
好记性+烂笔头15 小时前
10 Flink CDC
大数据·flink
赵渝强老师17 小时前
【赵渝强老师】Spark RDD的依赖关系和任务阶段
大数据·缓存·spark
小小のBigData17 小时前
【2025年更新】1000个大数据/人工智能毕设选题推荐
大数据·人工智能·课程设计
risc12345618 小时前
【Elasticsearch 】悬挂索引(Dangling Indices)
大数据·elasticsearch·搜索引擎