ElasticSeach--springboot中使用

2023-12-21 00:29:04

目录

一.引入依赖

?二.配置链接信息

?三.索引库测试

1.创建索引库

2.查询索引库

3.删除索引库

四.文档测试

1.添加文档

2.修改文档

3.删除文档

4.查询具体文档

5.批量添加文档

五.查询测试

?1.查询所有

2.根据属性term匹配查询

3.分页查询

4.排序

5.过滤属性

6.bool查询

7.范围查询

8.模糊查询

9.高亮查询

?10.聚合查询

?10.1最大年龄

10.2分组查询


一.引入依赖

    <dependencies>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.8.0</version>
        </dependency>
        <!--es的客户端-->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.8.0</version>
        </dependency>
    </dependencies>

?二.配置链接信息

#自定义elasticsearch连接配置
elasticsearch:
  host: 192.168.81.128
  port: 9200
@Getter
@Setter
@Configuration
@ConfigurationProperties(prefix = "elasticsearch")
public class ElasticSearchConfig {
    private String host;
    private int port;

    @Bean
    public RestHighLevelClient client(){
        return new RestHighLevelClient(RestClient.builder(
                new HttpHost(host, port, "http")
        ));
    }
}

?三.索引库测试

1.创建索引库

    /**
     *  添加索引库
     */
    @Test
    public void AddIndex() throws IOException {
        //创建索引库
        CreateIndexRequest request = new CreateIndexRequest("user");
        //获取响应
        CreateIndexResponse response =
                restHighLevelClient.indices().create(request,RequestOptions.DEFAULT);

        boolean acknowledged = response.isAcknowledged();

        System.out.println("响应状态:"+acknowledged);

    }

2.查询索引库

//查询索引库
    @Test
    public void testGetIndex() throws IOException {
        GetIndexRequest request = new GetIndexRequest("user");

        GetIndexResponse response = restHighLevelClient.indices().get(request, RequestOptions.DEFAULT);

        //
        System.out.println(response.getAliases());
        //获取默认配置
        System.out.println(response.getDefaultSettings());
        //获取索引名称
        System.out.println(Arrays.toString(response.getIndices()));
        //获取映射
        System.out.println(response.getMappings());

    }

3.删除索引库

/**
     * 删除索引库
     */
    @Test
    public void testDeleteIndex() throws IOException {
        //删除索引请求
        DeleteIndexRequest request = new DeleteIndexRequest("user");

        AcknowledgedResponse response = restHighLevelClient.indices().delete(request,RequestOptions.DEFAULT);

        System.out.println(response.isAcknowledged());

        restHighLevelClient.close();

    }

四.文档测试

1.添加文档

/**
     *  添加文档
     */
    @Test
    public void testAddDoucument() throws IOException {

        /**
         * 第一次不存在时是创建,
         *  第二次存在时就是修改,将修改version版本号
         */

        IndexRequest indexRequest = new IndexRequest("user");

        indexRequest.id("122");

        User user = new User();
        user.setId(122);
        user.setName("张三");
        user.setAge(12);
        user.setScore(123);
        //添加数据
        indexRequest.source(JSON.toJSONString(user), XContentType.JSON);
        IndexResponse response = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);

        //获取索引库id
        System.out.println(response.getIndex());
        //获取文档id
        System.out.println(response.getId());
        //获取版本
        System.out.println(response.getVersion());
        //获取结果
        System.out.println(response.getResult());


    }

2.修改文档

/**
     * 修改文档
     */
    @Test
    public void testUpadteDoc() throws IOException {
        UpdateRequest updateRequest = new UpdateRequest("user","122");

        User user = new User();
        user.setId(122);
        user.setName("张三");
        user.setAge(13);
        user.setScore(123);
        updateRequest.doc(JSON.toJSONString(user), XContentType.JSON);

        UpdateResponse res = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);

        System.out.println(res.getId());
        System.out.println(res.getIndex());
        System.out.println(res.getResult());
        System.out.println(res.getVersion());

        restHighLevelClient.close();
    }

3.删除文档

/**
     *  删除文档
     */
    @Test
    public void testDelteDoc() throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest("user","122");

        DeleteResponse res = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
        System.out.println(res.getId());
        System.out.println(res.getIndex());
        System.out.println(res.getResult());

    }

4.查询具体文档

    /**
     * 查询文档
     */
    @Test
    public void testGetDoc() throws IOException {
        GetRequest getRequest =
                new GetRequest("user","122");

        GetResponse res = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);

        System.out.println(res.getIndex());
        System.out.println(res.getId());
        System.out.println(res.getSource());
        System.out.println(res.getFields());
        System.out.println(res.getSourceAsString()); //返回json串
//        user
//        122
//        {score=123, name=张三, id=122, age=12}
//        {}
//        {"age":12,"id":122,"name":"张三","score":123}

    }

5.批量添加文档

 /**
     * 批量添加文档
     */
    @Test
    public void testBulkAdd() throws IOException {


        User user1 = new User(1,"王五",12,213);
        User user2 = new User(2,"李四",321,213);
        User user3 = new User(3,"赵六",24,213);
        User user4 = new User(4,"zhangsan",41,213);
        User user5 = new User(5,"蔡徐坤",21,213);

        BulkRequest request = new BulkRequest("user");

        IndexRequest request1 = new IndexRequest("user").id(user1.getId().toString());
        request1.source(JSON.toJSONString(user1),XContentType.JSON);

        IndexRequest request2 = new IndexRequest("user").id(user2.getId().toString());
        request2.source(JSON.toJSONString(user2),XContentType.JSON);

        IndexRequest request3 = new IndexRequest("user").id(user3.getId().toString());
        request3.source(JSON.toJSONString(user3),XContentType.JSON);

        IndexRequest request4 = new IndexRequest("user").id(user4.getId().toString());;
        request4.source(JSON.toJSONString(user4),XContentType.JSON);

        IndexRequest request5 = new IndexRequest("user").id(user5.getId().toString());
        request5.source(JSON.toJSONString(user5),XContentType.JSON);

        request.add(request1);
        request.add(request2);
        request.add(request3);
        request.add(request4);
        request.add(request5);

        BulkResponse res = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);

        System.out.println(res.getIngestTook());



        System.out.println(res.getTook());
        System.out.println(res.getIngestTookInMillis());


    }

五.查询测试

?1.查询所有

 /**
     * 查询所有
     */
    @Test
    public void testqueryAll() throws IOException {
        SearchRequest searchRequest = new SearchRequest();
        //指定索引库
        searchRequest.indices("user");

        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //查询所有
        sourceBuilder.query(QueryBuilders.matchAllQuery());
        searchRequest.source(sourceBuilder);

        SearchResponse res = client.search(searchRequest, RequestOptions.DEFAULT);

        //查询匹配
        SearchHits hits = res.getHits();
        System.out.println("took:" + res.getTook());
        System.out.println("是否超时:" + res.isTimedOut());
        System.out.println("TotalHits:" + hits.getTotalHits());
        System.out.println("MaxScore:" + hits.getMaxScore());
        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsString());
        }


    }

2.根据属性term匹配查询

/**
     * 根据term条件查询
     * @throws IOException
     */
    @Test
    public void testTermQuery() throws IOException {

        SearchRequest request = new SearchRequest();
        request.indices("user");
        //构建查询的请求体
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //查询所有对象
        sourceBuilder.query(QueryBuilders.termQuery("name","zhangsan"));
        request.source(sourceBuilder);

        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        //查询匹配
        SearchHits hits = response.getHits();
        System.out.println("took:" + response.getTook());
        System.out.println("是否超时:" + response.isTimedOut());
        System.out.println("TotalHits:" + hits.getTotalHits());
        System.out.println("MaxScore:" + hits.getMaxScore());
        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsString());
        }
    }

3.分页查询

 /**
     * 分页查询
     */
    @Test
    public void testPageQuery() throws IOException {

        SearchRequest request = new SearchRequest();
        request.indices("user");
        //构建查询的请求体
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //查询所有对象
        sourceBuilder.query(QueryBuilders.matchAllQuery());
        //第一页
        sourceBuilder.from(0);
        //三条记录
        sourceBuilder.size(11);

       
        request.source(sourceBuilder);
        //添加分页信息


        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        //查询匹配
        SearchHits hits = response.getHits();
        System.out.println("took:" + response.getTook());
        System.out.println("是否超时:" + response.isTimedOut());
        System.out.println("TotalHits:" + hits.getTotalHits());
        System.out.println("MaxScore:" + hits.getMaxScore());
        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsString());
        }
    }

4.排序

 //年龄排序 倒序,从大到小
        sourceBuilder.sort("age", SortOrder.DESC);

5.过滤属性

//查询过滤字段
        String[] excludes = {"age"};
        //过滤掉age属性
        String[] includes = {};
        sourceBuilder.fetchSource(includes,excludes);

6.bool查询

 //创建搜索对象
        SearchRequest request = new SearchRequest();
        request.indices("user");
        //构建查询的请求体
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //必须包含
        boolQuery.must(QueryBuilders.matchQuery("age",18));
        //一定不包含
        boolQuery.mustNot(QueryBuilders.matchQuery("name","lisi"));
        //可能包含
        boolQuery.should(QueryBuilders.matchQuery("name","zhangsan"));
        //查询所有对象
        sourceBuilder.query(boolQuery);
        
        request.source(sourceBuilder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

7.范围查询

 //创建搜索对象
        SearchRequest request = new SearchRequest();
        request.indices("user");
        //构建查询的请求体
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //范围查询
        RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("age");
        //大于等于
        rangeQuery.gte("19");
        //小于等于
        rangeQuery.lte("40");
        //查询所有对象
        sourceBuilder.query(rangeQuery);
 
        request.source(sourceBuilder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

8.模糊查询

//创建搜索对象
        SearchRequest request = new SearchRequest();
        request.indices("user");
        //构建查询的请求体
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //模糊查询
        FuzzyQueryBuilder fuzzyQuery = QueryBuilders.fuzzyQuery("name", "zhangsan");
        fuzzyQuery.fuzziness(Fuzziness.ONE);
 
        sourceBuilder.query(fuzzyQuery);
 
        request.source(sourceBuilder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

9.高亮查询


        //高亮查询
        SearchRequest request = new SearchRequest("user");
        //创建查询请求体构建器
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //构建查询方式,高亮查询
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "zhangsan");
        //设置查询方式
        sourceBuilder.query(termQueryBuilder);
        //构建高亮字段
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        //设置标签前缀
        highlightBuilder.preTags("<font color='red'");
        //设置标签后缀
        highlightBuilder.postTags("</font>");
        //设置高亮字段
        highlightBuilder.field("name");
        //设置高亮构建对象
        sourceBuilder.highlighter(highlightBuilder);
        //设置请求体
        request.source(sourceBuilder);
        //客户端发送请求,获取响应对象
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        // 打印响应结果
        SearchHits hits = response.getHits();
        System.out.println("took::"+response.getTook());
        System.out.println("time_out::"+response.isTimedOut());
        System.out.println("total::"+hits.getTotalHits());
        System.out.println("max_s core::"+hits.getMaxScore());
        System.out.println("hits::::>>");
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            System.out.println(sourceAsString);
            //打印高亮结果
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            System.out.println(highlightFields);
            System.out.println("<<::::");
        }

?10.聚合查询

?10.1最大年龄

 SearchRequest request = new SearchRequest().indices("user");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.aggregation(AggregationBuilders.max("maxAge").field("age"));
        //设置请求体
        request.source(sourceBuilder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        //打印响应结果
        SearchHits hits = response.getHits();
        System.out.println("hits = " + hits);
        System.out.println(response);

10.2分组查询

//创建搜索对象
         SearchRequest request = new SearchRequest().indices("user");
         SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
         searchSourceBuilder.aggregation(AggregationBuilders.terms("age_groupby").field("age"));
 
         //设置请求体
         request.source(searchSourceBuilder);
         SearchResponse response = client.search(request, RequestOptions.DEFAULT);
         System.out.println(response.getHits());
         System.out.println(response);

文章来源:https://blog.csdn.net/jjhnb123/article/details/135118999
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。