0


RestClient操作索引库

1.1.引入JavaRestClient依赖

因为SpringBoot默认默认ES版本是7.6.2,所以需要覆盖默认的版本。

    <properties>
        <elasticsearch.version>7.12.1</elasticsearch.version>
    </properties>
<!-- https://mvnrepository.com/artifact/org.elasticsearch.client/elasticsearch-rest-high-level-client -->
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.15.2</version>
</dependency>

1.2.初始化RestHighLevelClient

@Bean
    public RestHighLevelClient client(){
        return new RestHighLevelClient(RestClient.builder(HttpHost.create("http://ip地址:9200")));
    }

1.3. 注入

private RestHighLevelClient client;

2.1.RestClient****操作索引库

2.1.1.创建索引库

@Test
    void createHotelIndex() throws IOException {
        //创建request对象
        CreateIndexRequest request = new CreateIndexRequest("索引库名称");
        //MAPPING_TEMPLATE为静态变量,内容是创建索引库的DSL语句
        request.source(MAPPING_TEMPLATE, XContentType.JSON);
        //发起请求
        client.indices().create(request, RequestOptions.DEFAULT);
    }

2.1.2.删除索引库

@Test
    void deleteHotelIndex() throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest("索引库名称");
        client.indices().delete(request, RequestOptions.DEFAULT);
    }

2.1.3.判断索引库是否存在

@Test
    void existsHotelIndex() throws IOException {
        GetIndexRequest request = new GetIndexRequest("索引库名称");
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
    }

2.2.RestClient操作文档

2.2.1.创建文档

@Test
    void testAddDocument() throws IOException {
        IndexRequest request = new IndexRequest("索引库名称").id(文档id);
        request.source("新增文档内容",XContentType.JSON);
        client.index(request,RequestOptions.DEFAULT);
    }

2.2.2.查询文档

@Test
    void GetDocument() throws IOException {
        GetRequest request = new GetRequest("索引库名称").id("文档id");
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        String source = response.getSourceAsString();
        System.out.println(source);
    }

2.2.3.更新文档

@Test
    void UpdateDocument() throws IOException {
        UpdateRequest request = new UpdateRequest("索引库名称","文档id");
        //  字段,value,字段,value .......
        request.doc("name","lonely");
        client.update(request,RequestOptions.DEFAULT);
    }

2.2.4.删除文档

@Test
    void DeleteDocument() throws IOException {
        DeleteRequest request = new DeleteRequest("索引库名称","文档id");
        client.delete(request,RequestOptions.DEFAULT);
    }

2.2.5.批量导入文档

@Test
    void testBulkRequests() throws IOException {
        List<Hotel> hotels = hotelService.list();
        BulkRequest request = new BulkRequest();
        for (Hotel hotel : hotels) {
            HotelDoc hotelDoc = new HotelDoc(hotel);
            request.add(new IndexRequest("索引库名称").id(hotelDoc.getId().toString()).source(JSON.toJSONString(hotelDoc),XContentType.JSON));
        }
        client.bulk(request,RequestOptions.DEFAULT);
    }

3.1.DSL查询分类

   注:handleResponse()为处理响应结果函数
//处理响应结果
    private void handleResponse(SearchResponse response) {
        SearchHit[] hits = response.getHits().getHits();
        long value = response.getHits().getTotalHits().value;
        System.out.println(value);
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
            System.out.println(hotelDoc);
        }
    }

3.1.1.match_all查询

@Test
    void testMatchAll() throws IOException {
        SearchRequest request = new SearchRequest("hotel");
        request.source().query(QueryBuilders.matchAllQuery());
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        handleResponse(response);
    }

 

3.1.2.match查询

@Test
    void testMatch() throws IOException {
        SearchRequest request = new SearchRequest("索引库名称");
        request.source().query(QueryBuilders.matchQuery("字段", value"));
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        handleResponse(response);
    }

3.1.3.term查询(词条查询)

@Test
    void testTerm() throws IOException {
        SearchRequest request = new SearchRequest("索引库名称");
        request.source().query(QueryBuilders.termQuery("字段", value));
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        handleResponse(response);
    }

3.1.4.range查询

@Test
    void testRange() throws IOException {
        SearchRequest request = new SearchRequest("索引库名称");
        //这里以字段price为例范围是[200,300]
        request.source().query(QueryBuilders.rangeQuery("price").gte("200").lte("300"));
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        handleResponse(response);
    }

3.1.5.复合查询

@Test
    void testBool() throws IOException {
        SearchRequest request = new SearchRequest("索引库名称");
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        /*
           查询条件:城市是上海
           价格小于等于100
           距离经纬度30km内的地方
        */

        boolQuery.must(QueryBuilders.termQuery("city", "上海"));
        boolQuery.mustNot(QueryBuilders.rangeQuery("price").lte("100"));
        boolQuery.filter(QueryBuilders.geoDistanceQuery("location").distance("30km").point(31.21, 121.5));
        request.source().query(boolQuery);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        handleResponse(response);
    }

3.1.6.排序分页

@Test
    void testSort() throws IOException {
        int page = 10;
        int size = 5;
        SearchRequest request = new SearchRequest("hotel");
        request.source().query(QueryBuilders.matchAllQuery());
        request.source().from((page - 1) * size).size(2);
        //按照价格降序
        request.source().sort("price", SortOrder.DESC);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        handleResponse(response);
    }

3.1.7.高亮

高亮:对特定内容加上特定标签,有前端进行解析。

 @Test
    void testHighlighter() throws IOException {
        SearchRequest request = new SearchRequest("索引库名称");
        request.source().query(QueryBuilders.matchQuery("字段", value));
        //对查询字段为name的value进行高亮处理
        //es对高亮内容默认是加<em></em>标签
        request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false).tagsSchema("styled").preTags("<strong>").postTags("</strong>"));
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        //将响应解析为指定类
        SearchHit[] hits = response.getHits().getHits();
        for (SearchHit hit : hits) {
            HotelDoc hotelDoc = JSON.parseObject(hit.getSourceAsString(), HotelDoc.class);
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (!highlightFields.isEmpty()) {
                HighlightField highlightField = highlightFields.get("name");
                String name = highlightField.getFragments()[0].toString();
                hotelDoc.setName(name);
            }
            System.out.println(hotelDoc);
        }
    }

前端页面对JSON进行解析,会对strong标签进行高亮处理。


4.1.DSL实现聚合

4.1.1. Bucket聚合

解析代码:


本文转载自: https://blog.csdn.net/qq_57173833/article/details/127466330
版权归原作者 lonely_only_lonely 所有, 如有侵权,请联系我们删除。

“RestClient操作索引库”的评论:

还没有评论