当前位置:   article > 正文

SpringBoot使用elasticsearch-rest-high-level-client操作ElasticSearch_springboot elasticsearch-rest-high-level-client

springboot elasticsearch-rest-high-level-client

前言

老早之前写过一篇SpringBoot操作ElasticSearch的文章,但是内容过于简单,只是简单交代了下,为了更好的学习ElasticSearch这个搜索引擎,那么在更一篇贴,本文中使用的ElasticSearch为7.4.2,注意哦!那么elasticsearch-rest-high-level-client使用的也是同样的版本!这篇文章可以理解为是SpringBoot整合Elasticsearch的续集,可以先照着上文先把之前的代码准备下!

索引操作

创建索引

    @Test
    void createIndex() throws IOException {
        CreateIndexRequest request = new CreateIndexRequest("user");
        CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
        boolean acknowledged = createIndexResponse.isAcknowledged();
        log.info("索引操作===>"+acknowledged);

    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

查询索引

	@Test
    void selectIndex() throws IOException {
        GetIndexRequest request = new GetIndexRequest("user");
        GetIndexResponse getIndexResponse = client.indices().get(request, RequestOptions.DEFAULT);
        Map<String, List<AliasMetaData>> aliases = getIndexResponse.getAliases();
        Map<String, MappingMetaData> mappings = getIndexResponse.getMappings();
        Map<String, Settings> settings = getIndexResponse.getSettings();
        log.info("aliases===>{}",aliases);
        log.info("mappings===>{}",mappings);
        log.info("settings===>{}",settings);
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

在这里插入图片描述
在这里插入图片描述

这里返回的东西和Kibana操作返回的时一样的,只不过在java中封装成了对象

删除索引

    @Test
    void deleteIndex() throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest("user");
        AcknowledgedResponse acknowledgedResponse = client.indices().delete(request, RequestOptions.DEFAULT);
        log.info("索引操作===>{}",acknowledgedResponse.isAcknowledged());
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

文档操作

新增数据

    @Test
    void insertDoc() throws IOException {
        IndexRequest request = new IndexRequest();
        request.index("user").id("1");
        User user = new User().setName("tao").setAge(18).setSex('男');
        ObjectMapper mapper = new ObjectMapper();
        String userJson = mapper.writeValueAsString(user);
        request.source(userJson, XContentType.JSON);
        IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
        log.info("Result===>{}",indexResponse.getResult());
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

或者

	@Test
    void insertDoc2() throws IOException{
        IndexRequest indexRequest = new IndexRequest("user");
        indexRequest.id("1");
        indexRequest.source("userName", "tao", "age", 18, "sex", "M");
        IndexResponse index = client.index((indexRequest), MallElasticSearchConfig.COMMON_OPTIONS);
        log.info("===>", index.getResult());
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

查询数据

    @Test
    void selectDoc() throws IOException{
        GetRequest request = new GetRequest();
        request.index("user").id("1");
        GetResponse documentFields = client.get(request, RequestOptions.DEFAULT);
        log.info("===>{}",documentFields.getSourceAsString());

    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

删除数据

    @Test
    void deleteDoc() throws IOException{
        DeleteRequest request = new DeleteRequest();
        request.index("user").id("1");
        DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
        log.info("===>{}",response.toString());
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

批量添加数据

    @Test
    void bulkInsertDoc() throws IOException{
        BulkRequest request = new BulkRequest();
        ObjectMapper mapper = new ObjectMapper();
        User user1 = new User().setName("tao").setAge(18).setSex('男');
        User user2 = new User().setName("yyy").setAge(17).setSex('女');
        User user3 = new User().setName("dry").setAge(16).setSex('女');

        request.add(new IndexRequest().index("user").id("1").source(mapper.writeValueAsString(user1),XContentType.JSON));
        request.add(new IndexRequest().index("user").id("2").source(mapper.writeValueAsString(user2),XContentType.JSON));
        request.add(new IndexRequest().index("user").id("3").source(mapper.writeValueAsString(user3),XContentType.JSON ));

        BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
        log.info("Took===>{}",response.getTook());
        log.info("Items===>{}",response.getItems());
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

批量删除数据

    @Test
    void bulkDeleteDoc() throws IOException{
        BulkRequest request = new BulkRequest();

        request.add(new DeleteRequest().index("user").id("1"));
        request.add(new DeleteRequest().index("user").id("2"));
        request.add(new DeleteRequest().index("user").id("3"));

        BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
        log.info("Took===>{}",response.getTook());
        log.info("Items===>{}",response.getItems());
    }

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

高级查询

查询全部

    /**
     * {
     *   "query": {
     *     "match_all": {}
     *   }
     * }
     * @throws IOException
     */
    @Test
    void searchDoc() throws IOException{
        SearchRequest request = new SearchRequest();
        request.indices("user");
        request.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        SearchHits hits = response.getHits();

        log.info("TotalHits===>{}",hits.getTotalHits());
        log.info("Took===>{}",response.getTook());

        hits.forEach(h ->{
            log.info("===>"+h.getSourceAsString());
        });

    }
  • 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

条件查询

    /**
     * {
     *   "query": {
     *     "term": {
     *       "age": {
     *         "value": "18"
     *       }
     *     }
     *   }
     * }
     * @throws IOException
     */
    @Test
    void searchQueryDoc() throws IOException{
        SearchRequest request = new SearchRequest();
        request.indices("user");
        request.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("age",18)));
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        SearchHits hits = response.getHits();

        log.info("TotalHits===>{}",hits.getTotalHits());
        log.info("Took===>{}",response.getTook());

        hits.forEach(h ->{
            log.info("===>"+h.getSourceAsString());
        });

    }
  • 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

分页查询

    /**
     * {
     *   "query": {
     *     "match_all": {}
     *   },
     *   "from": 0,
     *   "size": 2
     * }
     * @throws IOException
     */
    @Test
    void searchPageDoc() throws IOException{
        SearchRequest request = new SearchRequest();
        request.indices("user");
        SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
        builder.from(0);
        builder.size(2);
        request.source(builder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        SearchHits hits = response.getHits();

        log.info("TotalHits===>{}",hits.getTotalHits());
        log.info("Took===>{}",response.getTook());

        hits.forEach(h ->{
            log.info("===>"+h.getSourceAsString());
        });

    }
  • 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

查询排序

    /**
     * {
     *   "query": {
     *     "match_all": {}
     *   },
     *   "sort": [
     *     {
     *       "age": {
     *         "order": "asc"
     *       }
     *     }
     *   ]
     * }
     * @throws IOException
     */
    @Test
    void searchOrderDoc() throws IOException{
        SearchRequest request = new SearchRequest();
        request.indices("user");
        SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
        builder.sort("age", SortOrder.ASC);
        request.source(builder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        SearchHits hits = response.getHits();

        log.info("TotalHits===>{}",hits.getTotalHits());
        log.info("Took===>{}",response.getTook());

        hits.forEach(h ->{
            log.info("===>"+h.getSourceAsString());
        });

    }
  • 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

查询指定字段

    /**
     * {
     *   "query": {
     *     "match_all": {}
     *   },
     *   "sort": [
     *     {
     *       "age": {
     *         "order": "asc"
     *       }
     *     }
     *   ],
     *   "_source": {
     *     "includes": [],
     *     "excludes":["sex"]
     *   }
     * }
     * @throws IOException
     */
    @Test
    void searchSourceDoc() throws IOException{
        SearchRequest request = new SearchRequest();
        request.indices("user");
        SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
        builder.sort("age", SortOrder.ASC);
        String[] excludes = {"sex"};
        String[] includes = {};
        builder.fetchSource(includes, excludes);
        request.source(builder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        SearchHits hits = response.getHits();

        log.info("TotalHits===>{}",hits.getTotalHits());
        log.info("Took===>{}",response.getTook());

        hits.forEach(h ->{
            log.info("===>"+h.getSourceAsString());
        });

    }
  • 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

组合查询

    /**
     * {
     *   "query": {
     *     "bool": {
     *       "must": [
     *         {
     *           "match": {
     *             "age": 18
     *           }
     *         }
     *       ],
     *       "must_not": [
     *         {
     *           "match": {
     *             "sex": "女"
     *           }
     *         }
     *       ]
     *     }
     *   }
     * }
     * @throws IOException
     */
    @Test
    void searchBoolDoc() throws IOException{
        SearchRequest request = new SearchRequest();
        request.indices("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.matchQuery("age", 18));
        boolQueryBuilder.mustNot(QueryBuilders.matchQuery("sex", "女"));

        builder.query(boolQueryBuilder);

        request.source(builder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        SearchHits hits = response.getHits();

        log.info("TotalHits===>{}",hits.getTotalHits());
        log.info("Took===>{}",response.getTook());

        hits.forEach(h ->{
            log.info("===>"+h.getSourceAsString());
        });

    }
  • 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

范围查询

    /**
     * {
     *   "query": {
     *     "range": {
     *       "age": {
     *         "gte": 20,
     *         "lte": 22
     *       }
     *     }
     *   }
     * }
     * @throws IOException
     */
    @Test
    void searchRangeDoc() throws IOException{
        SearchRequest request = new SearchRequest();
        request.indices("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();

        RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("age");
        rangeQuery.gte(20);
        rangeQuery.lte(22);
        builder.query(rangeQuery);

        request.source(builder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        SearchHits hits = response.getHits();

        log.info("TotalHits===>{}",hits.getTotalHits());
        log.info("Took===>{}",response.getTook());

        hits.forEach(h ->{
            log.info("===>"+h.getSourceAsString());
        });

    }
  • 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

模糊查询

    @Test
    void searchFuzzyDoc() throws IOException{
        SearchRequest request = new SearchRequest();
        request.indices("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(QueryBuilders.fuzzyQuery("name", "毛金").fuzziness(Fuzziness.ONE));
        //.fuzziness(Fuzziness.ONE)匹配多少个

        request.source(builder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        SearchHits hits = response.getHits();

        log.info("TotalHits===>{}",hits.getTotalHits());
        log.info("Took===>{}",response.getTook());

        hits.forEach(h ->{
            log.info("===>"+h.getSourceAsString());
        });
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

高亮查询

    /**
     * {
     *   "query": {
     *     "terms": {
     *       "name": [
     *         "金"
     *       ]
     *     }
     *   },
     *   "highlight": {
     *     "fields": {
     *       "name": {
     *         "pre_tags": [
     *           "<font color='red'>"
     *         ],
     *         "post_tags": [
     *           "</font>"
     *         ]
     *       }
     *     }
     *   }
     * }
     * @throws IOException
     */
    @Test
    void searchHighlighterDoc() throws IOException{
        SearchRequest request = new SearchRequest();
        request.indices("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        TermsQueryBuilder termQueryBuilder = QueryBuilders.termsQuery("name", "金");

        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<font color='red'>");
        highlightBuilder.postTags("</font>");
        highlightBuilder.field("name");

        builder.highlighter(highlightBuilder);
        builder.query(termQueryBuilder);


        request.source(builder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        SearchHits hits = response.getHits();

        log.info("TotalHits===>{}",hits.getTotalHits());
        log.info("Took===>{}",response.getTook());

        hits.forEach(h ->{
            log.info("===>"+h);
        });
    }
  • 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

聚合查询

    /**
     * {
     *    "aggs": {
     *     "ageMax": {
     *       "max": {
     *         "field": "age"
     *       }
     *     }
     *   }
     * }
     * @throws IOException
     */
    @Test
    void searchAggregationDoc() throws IOException{
        SearchRequest request = new SearchRequest();
        request.indices("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();

        MaxAggregationBuilder aggregationBuilder = AggregationBuilders.max("maxAge").field("age");

        builder.aggregation(aggregationBuilder);

        request.source(builder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        SearchHits hits = response.getHits();

        log.info("TotalHits===>{}",hits.getTotalHits());
        log.info("Took===>{}",response.getTook());
        log.info("Aggregations===>"+response.getAggregations());
    }

  • 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

聚合查询-分组

    /**
     * {
     *    "aggs": {
     *     "age_group": {
     *       "terms": {
     *         "field": "age"
     *       }
     *     }
     *   }
     * }
     * @throws IOException
     */
    @Test
    void searchAggregationGroupDoc() throws IOException{
        SearchRequest request = new SearchRequest();
        request.indices("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();

        AggregationBuilder aggregationBuilder = AggregationBuilders.terms("ageGroup").field("age");

        builder.aggregation(aggregationBuilder);

        request.source(builder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        SearchHits hits = response.getHits();

        log.info("TotalHits===>{}",hits.getTotalHits());
        log.info("Took===>{}",response.getTook());
        log.info("Aggregations===>"+response.getAggregations());
    }

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

闽ICP备14008679号