当前位置:   article > 正文

分布式搜索引擎ES-RestClient查询文档快速入门

分布式搜索引擎ES-RestClient查询文档快速入门

RestClient查询文档快速入门

1.1、match_all

package cn.mannor.hotel;

import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
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.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.IOException;

import static cn.mannor.hotel.constants.HotelConstants.MAPPING_TEMPLATE;

public class HotelSearchTest {

    private RestHighLevelClient restHighLevelClient; // 高级REST客户端,用于与Elasticsearch进行交互

    @Test
    void testMatchAll() throws IOException {
        //1.准备Request
        SearchRequest hotelRequest = new SearchRequest("hotel");
        //2.准备DSL
        hotelRequest.source().query(QueryBuilders.matchAllQuery());
        //3.发送请求
        SearchResponse response = restHighLevelClient.search(hotelRequest, RequestOptions.DEFAULT);
        System.out.println(response);
    }


    /**
     * 初始化测试环境,创建并配置RestHighLevelClient实例。
     */
    @BeforeEach
    void setUp() {
        this.restHighLevelClient = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.12.131:9200") // 设置Elasticsearch的地址和端口
        ));
    }

    /**
     * 测试结束后清理资源,关闭RestHighLevelClient实例。
     *
     * @throws IOException 如果关闭客户端时发生IO错误
     */
    @AfterEach
    void tearDown() throws IOException {
        this.restHighLevelClient.close(); // 关闭高级REST客户端,释放资源
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57

注:下面的内容我只会放置测试方法

完整获取:

    @Test
    void testMatchAll() throws IOException {
        //1.准备Request
        SearchRequest hotelRequest = new SearchRequest("hotel");
        //2.准备DSL
        hotelRequest.source().query(QueryBuilders.matchAllQuery());
        //3.发送请求
        SearchResponse response = restHighLevelClient.search(hotelRequest, RequestOptions.DEFAULT);
        //4.解析响应
        SearchHits searchHits = response.getHits();
        //4.1获取总条数
        long total = searchHits.getTotalHits().value;
        //4.2文档数组
        SearchHit[] hits = searchHits.getHits();
        //4.3遍历
        for (SearchHit hit : hits) {
            //获取文档source
            String json = hit.getSourceAsString();
            //反序列化
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
            System.out.println("hoteldoc:" + hotelDoc);
        }
        System.out.println(response);
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

image-20240323104622141

其中,核心API包含所有方法:

  1. hotelRequest.source()
    
    • 1

image-20240323133454901

  1. QueryBuilders
    
    • 1

image-20240323133223401

1.2、全文检索查询

// 单字段查询
QueryBuilders.matchQuery("name", "上海");
// 多字段查询 
QueryBuilders.multiMatchQuery("如家", "name", "business");
  • 1
  • 2
  • 3
  • 4

1.3、精确查询

// 词条查询
QueryBuilders.termQuery("city", "杭州"); 
// 范围查询
QueryBuilders.rangeQuery("price").gte(100).lte(150);
  • 1
  • 2
  • 3
  • 4

例如:

    @Test
    void testMatch() throws IOException {
        //1.准备Request
        SearchRequest hotelRequest = new SearchRequest("hotel");
        //2.准备DSL
        //2.1词条查询
        hotelRequest.source().query(QueryBuilders.termQuery("hotelName", "酒店"));
        //2.2范围查询
       // hotelRequest.source().query(QueryBuilders.rangeQuery("price").lt(300).gt(1000));
        //3.发送请求
        SearchResponse response = restHighLevelClient.search(hotelRequest, RequestOptions.DEFAULT);
        //4.解析响应(方法抽出来了)
        handelResponse(response);
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

1.4、复合查询-boolean query

// 创建布尔查询
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
// 添加must条件
boolQuery.must(QueryBuilders.termQuery("city", "杭州")); 
// 添加filter条件
boolQuery.filter(QueryBuilders.rangeQuery("price").lte(250));
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

例:

@Test
void testBooleQuery() throws IOException {
    //1.准备Request
    SearchRequest hotelRequest = new SearchRequest("hotel");
    //2.准备DSL
    BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    // 添加must条件
    boolQueryBuilder.must(QueryBuilders.matchQuery("city", "上海"));
    // 添加filter条件
    boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").lt(250));
    hotelRequest.source().query(boolQueryBuilder);
    //3.发送请求
    SearchResponse response = restHighLevelClient.search(hotelRequest, RequestOptions.DEFAULT);
    //4.解析响应(方法抽出来了)
    handelResponse(response);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

基于上述几种查询,只需要记住核心API:QueryBuilders

1.5、排序和分页

@Test
void testPageAndSort() throws IOException {
    //页码,每页大小
    int page = 1, size = 5;
    //1.准备Request
    SearchRequest hotelRequest = new SearchRequest("hotel");
    //2.准备DSL
    hotelRequest.source().query(QueryBuilders.matchAllQuery());
    //分页from ,size  排序sort
    hotelRequest.source().from((page-1)*size).size(5).sort("price", SortOrder.DESC);
    //3.发送请求
    SearchResponse response = restHighLevelClient.search(hotelRequest, RequestOptions.DEFAULT);
    //4.解析响应
    handelResponse(response);

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

image-20240323140751109

1.6、高亮(解析查询高亮结果)

@Test
void testHighlight() throws IOException {
    //1.准备Request
    SearchRequest hotelRequest = new SearchRequest("hotel");
    //2.准备DSL
    hotelRequest.source().query(QueryBuilders.matchQuery("name", "酒店"));
    //分页from ,size  排序sort
    hotelRequest.source().highlighter(new HighlightBuilder()
            .field("name")
            .requireFieldMatch(false));
    //3.发送请求
    SearchResponse response = restHighLevelClient.search(hotelRequest, RequestOptions.DEFAULT);

    
    //高亮解析
    //4.解析响应
    SearchHits searchHits = response.getHits();
    //4.1获取总条数
    long total = searchHits.getTotalHits().value;
    System.out.println("查询到的数据总条数为:" + total);
    //4.2文档数组
    SearchHit[] hits = searchHits.getHits();
    //4.3遍历
    for (SearchHit hit : hits) {
        //获取文档source
        String json = hit.getSourceAsString();
        //反序列化
        HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
        //获取高亮结果
        Map<String, HighlightField> highlightFields = hit.getHighlightFields();
        if (!CollectionUtils.isEmpty(highlightFields)) {
            // 根据字段名获取高亮结果
            HighlightField highlightField = highlightFields.get("name");
            if (highlightField != null) {
                //获取高亮值
                String name = highlightField.getFragments()[0].string();
                //覆盖非高亮结果
                hotelDoc.setName(name);
            }
        }
        System.out.println("hoteldoc:" + hotelDoc);
    }
    System.out.println(response);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44

查询结果:
image-20240323142809826

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/301918
推荐阅读
相关标签
  

闽ICP备14008679号