IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> Springboot 中使用elasticsearch -> 正文阅读

[Java知识库]Springboot 中使用elasticsearch

一、创建springboot工程,导入elasticsearch依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.ifun</groupId>
    <artifactId>es-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>es-demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.9.0</version>
            <exclusions>
                <exclusion>
                    <groupId>org.elasticsearch</groupId>
                    <artifactId>elasticsearch</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.9.0</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <scope>test</scope>
            <version>1.18.24</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.9</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

二、编写配置文件,配置elasticsearch的client

package com.ifun.es.demo.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticsearchConfig {

    @Bean
    public RestHighLevelClient restHighLevelClient(){
        return new RestHighLevelClient(RestClient.builder(
                new HttpHost("192.168.225.123", 9200, "http")));
    }

}

使用的时候只需要自动注入RestHighLevelClient就行了

@Autowired
@Qualifier("restHighLevelClient")
private RestHighLevelClient client;

三、索引相关api

1. 创建索引

    @Test
    void createIndex() throws IOException {
        CreateIndexRequest esDemo = new CreateIndexRequest("es_demo");
        CreateIndexResponse response = client.indices().create(esDemo, RequestOptions.DEFAULT);
        log.info("创建成功,索引信息为{}",response.index());
    }

2. 带配置参数的创建索引

    @Test
    void createIndexWithSettings() throws IOException {
        CreateIndexRequest request = new CreateIndexRequest("user");
        // 1. 准备索引的settings
        Settings.Builder settings = Settings.builder();
        settings.put("number_of_shards", 3);
        settings.put("number_of_replicas", 1);

        // 2. 准备关于索引的结构mappings
        XContentBuilder mappings = JsonXContent.contentBuilder()
                .startObject()
                .startObject("properties")
                .startObject("name")
                .field("type", "text")
                .field("analyzer","ik_smart")
                .endObject()
                .startObject("age")
                .field("type", "integer")
                .endObject()
                .startObject("birthday")
                .field("type", "date")
                .field("format", "yyyy-MM-dd")
                .endObject()
                .endObject()
                .endObject();

        // 3. 将settings和mappings封装到Request对象中
        request.settings(settings);
        request.mapping(mappings);

        CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
        log.info("创建成功,索引名称为:{}",response.index());
    }

对应的语句为

PUT /user
     {
        "settings": {
            "number_of_replicas": 1,
            "number_of_shards": 3
        },
        "mappings": {
            "properties": {
                "name":{
                    "type": "text",
                    "analyzer": "ik_smart"
                },
                "age":{
                    "type": "integer"
                },
                "birthday":{
                    "type": "date",
                    "format": "yyyy-MM-dd"
                }
            }
        }
     }

3. 删除索引

    @Test
    void delIndex() throws IOException {
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("user");
        AcknowledgedResponse delete = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
        log.info("删除索引结果:{}",delete.isAcknowledged());
    }

4. 查看索引信息

    @Test
    void getIndex() throws IOException {
        GetIndexRequest getIndexRequest = new GetIndexRequest("user");
        boolean exists = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
        if (exists){
            GetIndexResponse indexResponse = client.indices().get(getIndexRequest, RequestOptions.DEFAULT);
            MappingMetadata user = indexResponse.getMappings().get("user");
            Map<String, Object> mappings = user.getSourceAsMap();
            log.info("\nmappings:{}\nsettings:{}", JSON.toJSONString(mappings),indexResponse.getSettings().get("user"));
        }else{
            log.info("索引不存在");
        }
    }

四、文档相关api

1. 保存文档

    @Test
    void postDocument() throws IOException {
        User user = new User();
        user.setAge(78);
        user.setName("张三");
        user.setBirthday("1976-05-08");
        String json = JSON.toJSONString(user);
        IndexRequest indexRequest = new IndexRequest("user");
//        不传id则使用默认的id
//        indexRequest.id("1");
        indexRequest.source(json, XContentType.JSON);
        IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
        log.info("保存结果:{}",response.toString());
    }

2. 通过id查询文档信息

    @Test
    void getDocumentById() throws IOException {
        //GetRequest必须要带上id这个参数
        GetRequest request = new GetRequest("user","1");
        boolean exists = client.exists(request, RequestOptions.DEFAULT);
        if (exists){
            GetResponse response = client.get(request, RequestOptions.DEFAULT);
            log.info("文档内容{}",response.getSourceAsString());
        }
    }

3. 更新文档信息

    @Test
    void updateDocument() throws IOException {
        UpdateRequest request = new UpdateRequest("user", "1");
        User user = new User();
        user.setName("李新化");
        user.setAge(35);
        request.doc(JSONObject.toJSONString(user),XContentType.JSON);
        UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
        log.info("更新结果:{}",response.toString());
    }

4. 删除文档信息

    @Test
    void delDocumentById() throws IOException {
        DeleteRequest request = new DeleteRequest("user","1");
        DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
        log.info("删除结果:{}",response.toString());
    }

5. 文档批量操作

     /**
     POST  /user/_bulk
     {"create":{"_id":"5"}}
     {"name":"王一新","age":24,"birthday":"1969-08-12"}
     {"update":{"_id":"2"}}
     {"doc":{"name":"张新"}}
     {"delete":{"_id":"3"}}
     */
    @Test
    void bulkDocument() throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        User user = new User();
        user.setAge(24);
        user.setName("王一新");
        user.setBirthday("1969-08-12");
        IndexRequest indexRequest = new IndexRequest("user");
        indexRequest.id("5");
        indexRequest.source(JSON.toJSONString(user),XContentType.JSON);
        bulkRequest.add(indexRequest);

        UpdateRequest updateRequest = new UpdateRequest("user", "1");
        User updateUser = new User();
        updateUser.setName("张新");
        updateRequest.doc(JSON.toJSONString(updateUser),XContentType.JSON);
        bulkRequest.add(updateRequest);

        DeleteRequest deleteRequest = new DeleteRequest("user", "3");
        bulkRequest.add(deleteRequest);

        BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        log.info("批量操作结果:{}", JSON.toJSONString(response.getItems()));
    }

五、查询相关api

1. match_all

    /**
     GET /user/_search
     {
        "query": {
            "match_all": {}
         }
     }
     */
    @Test
    void matchAllQuery() throws IOException {
        //1.创建一个查询请求对象
        SearchRequest searchRequest = new SearchRequest("user");
        //2. 创建一个查询语句构建器
        SearchSourceBuilder builder = new SearchSourceBuilder();
        //3. 创建match_all 查询构建器
        MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
        //4. 使用builder构建match_all
        builder.query(matchAllQueryBuilder);
        //5. 将builder添加到查询请求中
        searchRequest.source(builder);
        //6. 发起查询请求
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        //7. 获取命中记录,并遍历查询结果
        SearchHits hits = response.getHits();
        log.info("\n查询结果:");
        for (SearchHit hit : hits) {
            log.info("\n{}", hit.getSourceAsString());
        }
    }

2. match

    /**
     GET /user/_search
     {
        "query": {
            "match": {
                "name": "张三"
            }
        }
     }
     */
    @Test
    void matchQuery() throws IOException {
        SearchRequest searchRequest = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("name","张三");
        builder.query(matchQueryBuilder);
        searchRequest.source(builder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        for (SearchHit hit : hits) {
            log.info("{}",hit.getSourceAsString());
        }
    }

3. term

    /**
     GET /user/_search
     {
       "query": {
         "term": {
            "age": {
              "value":"57"
            }
          }
       }
     }
     */

    @Test
    void termQuery() throws IOException {
        SearchRequest searchRequest = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        TermQueryBuilder termQueryBuilder = new TermQueryBuilder("age",78);
        builder.query(termQueryBuilder);
        searchRequest.source(builder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        for (SearchHit hit : hits) {
            log.info("{}",hit.getSourceAsString());
        }
    }

4. prefix

    /**
     GET /user/_search
     {
        "query": {
            "prefix": {
                "name": {
                    "value": "张"
                }
            }
        }
     }
     */
    @Test
    void prefixQuery() throws IOException {
        SearchRequest searchRequest = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        PrefixQueryBuilder prefixQueryBuilder = new PrefixQueryBuilder("name","张");
        builder.query(prefixQueryBuilder);
        searchRequest.source(builder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        for (SearchHit hit : response.getHits()) {
            log.info("{}",hit.getSourceAsString());
        }
    }

5. match_phrase

    /**
    GET /user/_search
    {
        "query": {
            "match_phrase": {
                "name": "张三"
            }
        }
    }
    */
    @Test
    void matchPhraseQuery() throws IOException {
        SearchRequest searchRequest = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        MatchPhraseQueryBuilder matchPhraseQueryBuilder = new MatchPhraseQueryBuilder("name","张三");
        builder.query(matchPhraseQueryBuilder);
        searchRequest.source(builder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        for (SearchHit hit : response.getHits()) {
            log.info("{}",hit.getSourceAsString());
        }
    }

6. multi_match

    /**
    GET /user/_search
    {
        "query": {
        "multi_match": {
            "query": "张三",
                    "fields": ["name","description"]
            }
        }
    }*/
    @Test
    void multiMatchQuery() throws IOException {
        SearchRequest searchRequest = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        MultiMatchQueryBuilder multiMatchQueryBuilder = new MultiMatchQueryBuilder("张三","name","description");
        builder.query(multiMatchQueryBuilder);
        searchRequest.source(builder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        for (SearchHit hit : response.getHits()) {
            log.info("{}",hit.getSourceAsString());
        }
    }

7. terms

    /**
    GET /user/_search
    {
        "query": {
         "terms": {
            "name": [
                "张三",
                "李四",
                "王五"
            ]
         }
      }
    }*/
    @Test
    void termsQuery() throws IOException {
        SearchRequest searchRequest = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        TermsQueryBuilder termsQueryBuilder = new TermsQueryBuilder("name","张三","五","李四");
        builder.query(termsQueryBuilder);
        searchRequest.source(builder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        for (SearchHit hit : response.getHits()) {
            log.info("{}",hit.getSourceAsString());
        }
    }

8. range

    /**
    GET /user/_search
    {
        "query": {
          "range": {
            "age": {
                "gte": 20,
                "lte": 60
            }
          }
        }
    }*/
    @Test
    void rangeQuery() throws IOException {
        SearchRequest searchRequest = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        RangeQueryBuilder rangeQueryBuilder = new RangeQueryBuilder("age");
        rangeQueryBuilder.from("20",true);
        rangeQueryBuilder.to("60",true);
        builder.query(rangeQueryBuilder);
        searchRequest.source(builder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        for (SearchHit hit : response.getHits()) {
            log.info("{}",hit.getSourceAsString());
        }
    }

9. ids

    /**
    GET /user/_search
    {
        "query": {
          "ids": {
            "values": [
                    "1",
                    "2",
                    "3",
                    "4",
                    "5"
            ]
          }
        }
    }*/
    @Test
    void idsQuery() throws IOException {
        SearchRequest searchRequest = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        IdsQueryBuilder idsQueryBuilder = new IdsQueryBuilder();
        idsQueryBuilder.addIds("1","2","3","4","5");
        builder.query(idsQueryBuilder);
        searchRequest.source(builder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        for (SearchHit hit : response.getHits()) {
            log.info("{}",hit.getSourceAsString());
        }
    }

10. query_string

    /**
    GET /user/_search
    {
        "query": {
         "query_string": {
            "default_field": "name",
             "query": "张三 OR 李四"
         }
       }
    }*/
    @Test
    void stringQuery() throws IOException {
        SearchRequest searchRequest = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        QueryStringQueryBuilder queryStringQueryBuilder = new QueryStringQueryBuilder("张三 OR 李四");
        queryStringQueryBuilder.defaultField("name");
        builder.query(queryStringQueryBuilder);
        searchRequest.source(builder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        for (SearchHit hit : response.getHits()) {
            log.info("{}",hit.getSourceAsString());
        }
    }

11. exists

    /**
    GET /user/_search
    {
        "query": {
        "exists": {
            "field": "description"
        }
        }
    }*/
    @Test
    void existsQuery() throws IOException {
        SearchRequest searchRequest = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        ExistsQueryBuilder existsQueryBuilder = new ExistsQueryBuilder("description");
        builder.query(existsQueryBuilder);
        searchRequest.source(builder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        for (SearchHit hit : response.getHits()) {
            log.info("{}",hit.getSourceAsString());
        }
    }

12. 对结果进行排序

    /**
    GET /user/_search
    {
        "query": {
        "range": {
            "age": {
                "gte": 20,
                "lte": 60
            }
        }
        },
        "sort": [
                {
                    "age": {
                        "order": "desc"
                     }
                }
         ]
    }*/
    @Test
    void sortResultQuery() throws IOException {
        SearchRequest searchRequest = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        RangeQueryBuilder rangeQueryBuilder = new RangeQueryBuilder("age");
        rangeQueryBuilder.from("20",true);
        rangeQueryBuilder.to("60",true);
        builder.query(rangeQueryBuilder);
        searchRequest.source(builder);
        //按照age大小倒序
        builder.sort("age", SortOrder.DESC);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        for (SearchHit hit : response.getHits()) {
            log.info("{}",hit.getSourceAsString());
        }
    }

13. 分页查询

    /**
    GET /user/_search
    {
        "query": {
          "range": {
            "age": {
                "gte": 20,
                "lte": 60
             }
          }
        },
        "from": 0,
        "size": 10
    }*/
    @Test
    void sizeResultQuery() throws IOException {
        SearchRequest searchRequest = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        RangeQueryBuilder rangeQueryBuilder = new RangeQueryBuilder("age");
        rangeQueryBuilder.from("20",true);
        rangeQueryBuilder.to("60",true);
        builder.query(rangeQueryBuilder);
        searchRequest.source(builder);
        //从0索引开始,返回10个数据
        builder.from(0);
        builder.size(10);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        for (SearchHit hit : response.getHits()) {
            log.info("{}",hit.getSourceAsString());
        }
    }

14. bool must

    /**
    GET /user/_search
    {
        "query": {
        "bool": {
            "must": [
                {
                "match": {
                    "name": "张三"
                    }
                },
               {
                 "range": {
                   "age": {
                      "gte": 70
                    }
                  }
               }
            ]
          }
        }
    }*/

    @Test
    void boolMustQuery() throws IOException {
        SearchRequest searchRequest = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        //must中可以是多个,所以可以写多个must
        boolQueryBuilder.must(QueryBuilders.matchQuery("name","张三"));
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("age");
        rangeQueryBuilder.from(70,true);
        boolQueryBuilder.must(rangeQueryBuilder);
        builder.query(boolQueryBuilder);
        searchRequest.source(builder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        for (SearchHit hit : response.getHits()) {
            log.info("{}",hit.getSourceAsString());
        }
    }

15. bool must_not


    /**
    GET /user/_search
    {
        "query": {
        "bool": {
            "must_not": [
                {
                  "match": {
                     "name": "张三"
                    }
                },{
                   "exists": {
                     "field": "description"
                    }
                }
            ]
        }
      }
    }*/
    @Test
    void boolMustNotQuery() throws IOException {
        SearchRequest searchRequest = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        //must_not中可以是多个,所以可以写多个mustNot
        boolQueryBuilder.mustNot(QueryBuilders.existsQuery("description"));
        boolQueryBuilder.mustNot(QueryBuilders.matchQuery("name","张三"));
        builder.query(boolQueryBuilder);
        searchRequest.source(builder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        for (SearchHit hit : response.getHits()) {
            log.info("{}",hit.getSourceAsString());
        }
    }

16. bool should

    /**
    GET /user/_search
    {
        "query": {
        "bool": {
            "should": [
            {
                "match": {
                "name": "张三"
            }
            },
            {
                "exists": {
                "field": "description"
            }
            }
           ]
        }
      }
    }*/
    @Test
    void boolShouldQuery() throws IOException {
        SearchRequest searchRequest = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        //should中可以是多个,所以可以写多个should
        boolQueryBuilder.should(QueryBuilders.matchQuery("name","张三"));
        boolQueryBuilder.should(QueryBuilders.existsQuery("description"));
        builder.query(boolQueryBuilder);
        searchRequest.source(builder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        for (SearchHit hit : response.getHits()) {
            log.info("{}",hit.getSourceAsString());
        }
    }

17. bool filter

    /**
    GET /user/_search
    {
        "query": {
        "bool": {
            "filter": [
            {
                "match": {
                "name": "张三"
               }
             }
            ]
         }
       }
    }*/
    @Test
    void boolFilterQuery() throws IOException {
        SearchRequest searchRequest = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        //filter中可以是多个,所以可以写多个filter
        boolQueryBuilder.filter(QueryBuilders.matchQuery("name","张三"));
        builder.query(boolQueryBuilder);
        searchRequest.source(builder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        for (SearchHit hit : response.getHits()) {
            log.info("{}",hit.getSourceAsString());
        }
    }

18. bool 条件组合查询

    /**
    GET /user/_search
    {
        "query": {
        "bool": {
            "should": [
            {
                "match": {
                "name": "张三"
            }
            }
            ],
            "must_not": [
            {
                "exists": {
                "field": "description"
            }
            }
            ],
            "must": [
            {
                "range": {
                "age": {
                    "gt": 10,
                            "lt": 70
                }
            }
            }
            ]
        }
     }
    }*/
    /**
     * bool条件组合查询
     */
    @Test
    void boolCombineQuery() throws IOException {
        SearchRequest searchRequest = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        //should mustNo must
        boolQueryBuilder.should(QueryBuilders.matchQuery("name","张三"));
        boolQueryBuilder.mustNot(QueryBuilders.existsQuery("description"));
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("age");
        rangeQueryBuilder.from(10);
        rangeQueryBuilder.to(70);
        boolQueryBuilder.must(rangeQueryBuilder);
        builder.query(boolQueryBuilder);
        searchRequest.source(builder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        for (SearchHit hit : response.getHits()) {
            log.info("{}",hit.getSourceAsString());
        }
    }

19. bool 嵌套查询

    /**
    GET /user/_search
    {
        "query": {
        "bool": {
            "must": [
               {
                "bool": {
                  "should": [
                   {
                    "match": {
                    "name": "张三"
                   }
                  },
                  {
                    "range": {
                    "age": {
                        "gt": 10,
                        "lt": 70
                    }
                   }
                  }
               ]
              }
             }
          ]
         }
      }
    }*/
    /**
     * bool 嵌套查询
     */
    @Test
    void boolNestQuery() throws IOException {
        SearchRequest searchRequest = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        //must中嵌套should
        BoolQueryBuilder innerBoolQueryBuilder = new BoolQueryBuilder();
        innerBoolQueryBuilder.should(QueryBuilders.matchQuery("name","张三"));
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("age");
        rangeQueryBuilder.from(10);
        rangeQueryBuilder.to(70);
        innerBoolQueryBuilder.should(rangeQueryBuilder);
        boolQueryBuilder.must(innerBoolQueryBuilder);
        builder.query(boolQueryBuilder);
        searchRequest.source(builder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        for (SearchHit hit : response.getHits()) {
            log.info("{}",hit.getSourceAsString());
        }
    }

20. fuzzy 模糊查询

    /**
    GET /user/_search
    {
        "query": {
        "fuzzy": {
            "name": {
                "value": "张思",
                "fuzziness": 1
            }
            }
        }
    }*/
    @Test
    void fuzzyQuery() throws IOException {
        SearchRequest searchRequest = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        FuzzyQueryBuilder fuzzyQueryBuilder = new FuzzyQueryBuilder("name","张思");
        //fuzziness 表示查的词中可以有几个不同的字
        fuzzyQueryBuilder.fuzziness(Fuzziness.ONE);
        builder.query(fuzzyQueryBuilder);
        searchRequest.source(builder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        for (SearchHit hit : response.getHits()) {
            log.info("{}",hit.getSourceAsString());
        }
    }

21. nested 嵌套查询


    /**
     *  nested 嵌套属性查询
     */
    @Test
    void createNestedDoc() throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        Random random = new Random();
        String[] firstName = new String[]{"张","王","李","赵","成","陈","艾","方","费","车"};
        String[] lastName = new String[]{"小饭","芳芳","烦","西放","东方","阿","不","发","加姐","信息"};
        String[] birthDay = new String[]{"1990-01-12","1995-04-01","1999-01-11","1993-12-12","2000-01-15","2022-01-10","2021-01-12","2000-01-05","2001-05-10","2004-05-15"};
        String[] color = new String[]{"red","yellow","pink"};
        for (int i=0;i<10;i++){
            User user = new User();
            user.setAge(random.nextInt(100)+1);
            user.setName(firstName[random.nextInt(10)]+lastName[random.nextInt(10)]);
            user.setBirthday(birthDay[random.nextInt(10)]);
            Dog dog = new Dog();
            dog.setColor(color[random.nextInt(3)]);
            dog.setWeight(random.nextFloat());
            user.setDog(dog);
            IndexRequest indexRequest = new IndexRequest("user");
            String id = ""+(i+1);
            indexRequest.id(id);
            indexRequest.source(JSON.toJSONString(user),XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        log.info("批量操作结果:{}", JSON.toJSONString(response.getItems()));
    }

    /**
    GET /user/_search
    {
        "query": {
        "nested": {
            "path": "dog",
             "query": {
                "match": {
                    "dog.color": "red"
                }
            }
          }
        }
    }*/

    @Test
    void nestedQuery() throws IOException {
        SearchRequest searchRequest = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        NestedQueryBuilder nestedQueryBuilder = new NestedQueryBuilder("dog",QueryBuilders.matchQuery("dog.color","red"), ScoreMode.None);
        builder.query(nestedQueryBuilder);
        searchRequest.source(builder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        for (SearchHit hit : response.getHits()) {
            log.info("{}",hit.getSourceAsString());
        }
    }

六、聚合操作相关api

1. avg

    /**
    GET /user/_search
    {
        "size": 0,
            "aggs": {
        "age-avg-aggs": {
            "avg": {
                "field": "age"
            }
        }
    }
    }*/

    @Test
    void avgAggsQuery() throws IOException {
        SearchRequest searchRequest = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        AvgAggregationBuilder avg = AggregationBuilders.avg("age-avg-aggs").field("age");
        builder.aggregation(avg);
        searchRequest.source(builder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        ParsedAvg parsedAvg = response.getAggregations().get("age-avg-aggs");
        double avgValue = parsedAvg.getValue();
        log.info("平均值:{}",avgValue);

    }

2. sum

    /**
    GET /user/_search
    {
        "size": 0,
            "aggs": {
        "age-sum-aggs": {
            "sum": {
                "field": "age"
            }
        }
    }
    }*/
    @Test
    void sumAggsQuery() throws IOException {
        SearchRequest searchRequest = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.aggregation(AggregationBuilders.sum("age-sum-aggs").field("age"));
        searchRequest.source(builder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        ParsedSum parsedSum = response.getAggregations().get("age-sum-aggs");
        double sumValue = parsedSum.getValue();
        log.info("总和:{}",sumValue);
    }

3.? min

    /**
    GET /user/_search
    {
        "size": 0,
            "aggs": {
        "age-min-aggs": {
            "min": {
                "field": "age"
            }
        }
    }
    }*/

    @Test
    void minAgeQuery() throws IOException {
        SearchRequest searchRequest = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.aggregation(AggregationBuilders.min("age-min-aggs").field("age"));
        searchRequest.source(builder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        ParsedMin parsedMin = response.getAggregations().get("age-min-aggs");
        double minValue = parsedMin.getValue();
        log.info("最小:{}",minValue);
    }

4.? max

    /**
    GET /user/_search
    {
        "size": 0,
            "aggs": {
        "age-max-aggs": {
            "max": {
                "field": "age"
            }
        }
    }
    }*/
    @Test
    void maxAgeQuery() throws IOException {
        SearchRequest searchRequest = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.aggregation(AggregationBuilders.max("age-max-aggs").field("age"));
        searchRequest.source(builder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        ParsedMax parsedMax = response.getAggregations().get("age-max-aggs");
        double maxValue = parsedMax.getValue();
        log.info("最大:{}",maxValue);
    }

5.? stats

    /**
    GET /user/_search
    {
        "size": 0,
            "aggs": {
        "age-stats-aggs": {
            "stats": {
                "field": "age"
            }
        }
    }
    }*/

    @Test
    void statsAgeQuery() throws IOException {
        SearchRequest searchRequest = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.aggregation(AggregationBuilders.stats("age-stats-aggs").field("age"));
        searchRequest.source(builder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        ParsedStats parsedStats = response.getAggregations().get("age-stats-aggs");
        double avg = parsedStats.getAvg();
        double max = parsedStats.getMax();
        double min = parsedStats.getMin();
        double sum = parsedStats.getSum();
        long count = parsedStats.getCount();
        log.info("avg:{},max:{},min:{},sum:{},count:{}",avg,max,min,sum,count);
    }

6. extended_stats

    /**
    GET /user/_search
    {
        "size": 0,
            "aggs": {
        "age-extended-stats-aggs": {
            "extended_stats": {
                "field": "age"
            }
        }
    }
    }*/
    @Test
    void extendedStatsAgeQuery() throws IOException {
        SearchRequest searchRequest = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.aggregation(AggregationBuilders.extendedStats("age-extended-stats-aggs").field("age"));
        searchRequest.source(builder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        ParsedExtendedStats parsedStats = response.getAggregations().get("age-extended-stats-aggs");
        double avg = parsedStats.getAvg();
        double max = parsedStats.getMax();
        double min = parsedStats.getMin();
        double sum = parsedStats.getSum();
        long count = parsedStats.getCount();
        double stdDeviation = parsedStats.getStdDeviation();
        double stdDeviationPopulation = parsedStats.getStdDeviationPopulation();
        double stdDeviationSampling = parsedStats.getStdDeviationSampling();
        double sumOfSquares = parsedStats.getSumOfSquares();
        log.info("avg:{},max:{},min:{},sum:{},count:{},\ndeviation:{},population:{},sampling:{},squares:{}",
                avg,max,min,sum,count,stdDeviation,stdDeviationPopulation,stdDeviationSampling,sumOfSquares);
    }

7. filter?

    /**
    GET /user/_search
    {
        "size": 0,
            "aggs": {
        "filter-aggs": {
            "filter": {
                "match":{
                    "name":"不"
                }
            }
        }
    }
    }*/
    @Test
    void filterAggsQuery() throws IOException {
        SearchRequest searchRequest = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name", "不");
        builder.aggregation(AggregationBuilders.filter("filter-aggs",matchQueryBuilder));
        searchRequest.source(builder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        ParsedFilter parsedFilter = response.getAggregations().get("filter-aggs");
        long docCount = parsedFilter.getDocCount();
        log.info("doc-count:{}",docCount);
    }

8. filters

    /**
    GET /user/_search
    {
        "size": 0,
        "aggs": {
        "filters-aggs": {
            "filters": {
                "filters": {
                    "dog-yellow": {
                        "nested": {
                            "path": "dog",
                            "query": {
                                "match": {
                                    "dog.color": "yellow"
                                }
                            }
                        }
                    },
                    "dog-red": {
                        "nested": {
                            "path": "dog",
                             "query": {
                                "match": {
                                    "dog.color": "red"
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    }*/

    @Test
    void filtersAggsQuery() throws IOException {
        SearchRequest searchRequest = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        NestedQueryBuilder redBuilder = QueryBuilders.nestedQuery("dog", QueryBuilders.matchQuery("dog.color", "red"), ScoreMode.None);
        FiltersAggregator.KeyedFilter keyedRedFilter = new FiltersAggregator.KeyedFilter("dog-red",redBuilder);
        NestedQueryBuilder yellowBuilder = QueryBuilders.nestedQuery("dog", QueryBuilders.matchQuery("dog.color", "yellow"), ScoreMode.None);
        FiltersAggregator.KeyedFilter keyedYellowFilter = new FiltersAggregator.KeyedFilter("dog-yellow",yellowBuilder);
        builder.aggregation(AggregationBuilders.filters("filters-aggs",keyedRedFilter,keyedYellowFilter));
        searchRequest.source(builder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        ParsedFilters parsedFilters = response.getAggregations().get("filters-aggs");
        ParsedFilters.ParsedBucket dogRedBucket = parsedFilters.getBucketByKey("dog-red");
        ParsedFilters.ParsedBucket dogYellowBucket = parsedFilters.getBucketByKey("dog-yellow");
        log.info("yellow:{},doc-count:{}",dogYellowBucket.getKeyAsString(),dogYellowBucket.getDocCount());
        log.info("red:{},doc-count:{}",dogRedBucket.getKeyAsString(),dogRedBucket.getDocCount());
    }

9. terms

    /**
    GET /user/_search
    {
        "size": 0,
            "aggs": {
        "terms-aggs": {
            "terms": {
                "field": "birthday"
            }
        }
    }
    }*/

    @Test
    void termsAggsQuery() throws IOException {
        SearchRequest searchRequest = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.aggregation(AggregationBuilders.terms("terms-aggs").field("birthday"));
        searchRequest.source(builder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        ParsedLongTerms parsedLongTerms = response.getAggregations().get("terms-aggs");
        for (Terms.Bucket bucket : parsedLongTerms.getBuckets()) {
            String keyAsString = bucket.getKeyAsString();
            long docCount = bucket.getDocCount();
            log.info("{}:{}",keyAsString,docCount);
        }
    }

10.? range

    /**
    GET /user/_search
    {
        "size": 0,
        "aggs": {
        "range-aggs": {
            "range": {
                "field": "age",
                        "ranges": [
                {
                    "from": 0,
                        "to": 20
                },
                {
                    "from": 20,
                        "to": 60
                },
                {
                    "from": 60,
                        "to": 100
                }
        ]
            }
        }
    }
    }*/
    @Test
    void rangeAggsQuery() throws IOException {
        SearchRequest searchRequest = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.aggregation(AggregationBuilders.range("range-aggs").field("age")
                .addRange(0,20).addRange(20,60).addRange(60,100));
        searchRequest.source(builder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        ParsedRange parsedRange = response.getAggregations().get("range-aggs");
        for (Range.Bucket bucket : parsedRange.getBuckets()) {
            String keyAsString = bucket.getKeyAsString();
            long docCount = bucket.getDocCount();
            log.info("{}:{}",keyAsString,docCount);
        }
    }

11. date_range

    /**
    GET /user/_search
    {
        "size": 0,
         "aggs": {
        "date-rang-aggs": {
            "date_range": {
                "field": "birthday",
                "ranges": [
                {
                    "from": "1992-01-01",
                        "to": "1994-01-01"
                },
                {
                    "from": "1994-01-01",
                        "to": "1999-01-01"
                },
                {
                    "from": "1999-01-01",
                        "to": "2022-01-01"
                }
                ]
            }
        }
    }
    }*/
    @Test
    void dateRangeAggsQuery() throws IOException {
        SearchRequest searchRequest = new SearchRequest("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.aggregation(AggregationBuilders.dateRange("date-range-aggs").field("birthday")
        .addRange("1992-01-01","1994-01-01").addRange("1994-01-01","1999-01-01").addRange("1999-01-01","2022-01-01"));
        searchRequest.source(builder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        ParsedDateRange parsedDateRange = response.getAggregations().get("date-range-aggs");
        for (Range.Bucket bucket : parsedDateRange.getBuckets()) {
            String keyAsString = bucket.getKeyAsString();
            long docCount = bucket.getDocCount();
            log.info("{}:{}",keyAsString,docCount);
        }
    }

七、总结

Elasticsearch 在springboot中的相关操作就介绍这么多了,应该都够用了,哈哈哈

  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2022-09-15 01:51:23  更:2022-09-15 01:52:57 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/23 13:14:34-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码