• Elasticsearch学习


    1、官网下载,安装方式多样,这里选择docker

    docker pull docker.elastic.co/elasticsearch/elasticsearch:7.14.0

     2、创建普通用户以便于使用Elasticsearch

    1. # root用户可以使用docker,普通用户无法使用,是因为没有权限。
    2. # 查看当前用户
    3. whoami
    4. # 创建新用户
    5. adduser username
    6. # 设置用户密码
    7. passwd username
    8. # 创建一个新的docker组
    9. groupadd docker
    10. # 添加新用户到docker组
    11. usermod -a -G docker username
    12. # 更新docker组
    13. newgrp docker
    14. # 修改docker.sock权限为root用户docker组
    15. chown root:docker /var/run/docker.sock
    16. # 切换到新用户
    17. su username

    3、创建Elasticsearch容器

    1. docker run
    2. --name elasticsearch # 容器名称
    3. -p 9200:9200 # 映射端口 接受http协议
    4. -p 9300:9300 # 接受TCP协议
    5. -e "discovery.type=single-node" # 单节点式
    6. -e ES_JAVA_OPTS="-Xms84m -Xmx512m" # 内存大小
    7. -v /home/docker/elasticsearch/data:/usr/share/elasticsearch/data # 挂载目录
    8. -v /home/docker/elasticsearch/logs:/usr/share/elasticsearch/logs
    9. -v /home/docker/elasticsearch/plugins:/usr/share/elasticsearch/plugins
    10. -d
    11. elasticsearch:8.7.0

    4、Kibana安装,安装方式多样,这里也选择docker

    1. # 拉取镜像
    2. docker pull kibana:7.14.0
    3. # 挂载数据卷,创建容器
    4. docker run -d
    5. --name kibana
    6. -p 5601:5601
    7. -v /home/es/kibana/kibana.yml:/usr/share/kibana/config/kibana.yml
    8. 58dffcbc8caa

    5、拷贝容器内的文件

    docker cp <containerId>:/path/to/file /path/on/host

    6、索引操作

    1. # 查询全部索引
    2. GET /_cat/indices?v
    3. # 创建索引
    4. PUT /indexName
    5. # 创建一个索引并使用json格式传参,设置主分片为1副本分片数量为零
    6. PUT /indexName
    7. {
    8. "settings": {
    9. "number_of_shards": 1
    10. , "number_of_replicas": 0
    11. }
    12. }
    13. # 删除一个索引
    14. DELETE /indexName
    15. # 删除所有索引
    16. DELETE /*

    7、映射操作

            字符串类型:keyword、text

            整数类型:integer、long

            小数类型:float、double

            布尔类型:boolean

            日期类型:date

    1. # 创建索引时创建映射
    2. PUT /indexName
    3. {
    4. "settings": {
    5. "number_of_shards": 1
    6. , "number_of_replicas": 0
    7. }
    8. , "mappings": {
    9. "properties": {
    10. "id":{
    11. "type": "integer"
    12. },
    13. "title":{
    14. "type": "keyword"
    15. },
    16. "price":{
    17. "type": "double"
    18. },
    19. "update_time":{
    20. "type": "date"
    21. },
    22. "describe":{
    23. "type": "text"
    24. }
    25. }
    26. }
    27. }
    28. # 查看索引的映射
    29. GET /indexName/_mapping

    8、文档操作

    1. # 根据映射向索引中创建一条文档,自动指定id
    2. POST /indexName/_doc
    3. {
    4. "title":"电冰箱",
    5. "price":2.99,
    6. "update_time":"2023-03-25",
    7. "describe":"很好用"
    8. }
    9. # 手动指定id
    10. POST /indexName/_doc/id
    11. {
    12. "title":"电冰箱",
    13. "price":2.99,
    14. "update_time":"2023-03-25",
    15. "describe":"很好用"
    16. }
    17. # 根据文档id查询文档
    18. GET /indexName/_doc/id
    19. # 根据id删除文档
    20. DELETE /indexName/_doc/id
    21. # 根据id更新文档,先删除再更新,覆盖式更新
    22. PUT /indexName/_doc/id
    23. {
    24. "title":"电视机"
    25. }
    26. # 根据id更新文档,只覆盖更新部分
    27. POST /indexName/_doc/id/_update
    28. {
    29. "doc" : {
    30. "title":"电视据"
    31. }
    32. }
    33. # 批量操作文档,指定id同时插入两条数据
    34. POST /indexName/_doc/_bulk
    35. {"index":{"_id":7}}
    36. {"title":"瓜子","price":3.99,"update_time":"2022-04-23","describe":"好吃"}
    37. {"index":{"_id":8}}
    38. {"title":"饮料","price":4.99,"update_time":"2020-04-22","describe":"好喝"}
    39. # 批量操作文档,指定id插入更新删除
    40. POST /indexName/_doc/_bulk
    41. {"index":{"_id":9}}
    42. {"title":"矿泉水","price":8.99,"update_time":"1921-09-23","describe":"矿泉水也好喝"}
    43. {"update":{"_id":9}}
    44. {"doc":{"describe":"矿泉水好喝是好喝,就是太贵啦"}}
    45. {"delete":{"_id":1}}

    9、高级文档查询

    1. # 查询索引中的所有文档
    2. GET /indexName/_doc/_search # 或使用GET /indexName/_search
    3. {
    4. "query":{
    5. "match_all":{}
    6. }
    7. }
    8. # 根据索引中的关键词查询
    9. # keyword类型、Integer类型、double类型、date类型、boolean类型、float类型、long类型不分词
    10. # text类型,es会使用分词器进行分词,中文单字查询英文单个单词(空格)查询
    11. GET /indexName/_doc/_search
    12. {
    13. "query":{
    14. "term":{ # term代表关键词查询
    15. "price":3.99
    16. }
    17. }
    18. }
    19. # 范围查询
    20. GET /indexName/_doc/_search
    21. {
    22. "query":{
    23. "range":{ # range代表范围查询
    24. "price":{
    25. "gte":2, # gte大于等于、gt大于
    26. "lte":3 # lte小于等于、lt小于
    27. }
    28. }
    29. }
    30. }
    31. # 前缀查询,查询指定前缀的内容
    32. GET /indexName/_doc/_search
    33. {
    34. "query":{
    35. "prefix":{ # prefix代表前缀查询
    36. "title":"瓜"
    37. }
    38. }
    39. }
    40. # 通配符查询,"?"代表任意一个字符,"*"代表任意多个字符
    41. GET /indexName/_doc/_search
    42. {
    43. "query":{
    44. "wildcard":{ # wildcard代表通配符查询
    45. "title":"?泉*"
    46. }
    47. }
    48. }
    49. # 多id查询
    50. GET /indexName/_doc/_search
    51. {
    52. "query":{
    53. "ids":{
    54. "values":["7","8","9"]
    55. }
    56. }
    57. }
    58. # 模糊查询。搜索关键词长度为2不允许出现模糊、关键词长度为3-5允许一次模糊、关键词长度大于五允许两次模糊
    59. GET /indexName/_doc/_search
    60. {
    61. "query":{
    62. "fuzzy":{
    63. "title":"矿石水" # 文档中为矿泉水
    64. }
    65. }
    66. }
    67. # 布尔查询。关键字must等价于&&、should等价于||、must_not相当于!
    68. GET /indexName/_doc/_search
    69. {
    70. "query":{
    71. "bool":{
    72. "must":[{
    73. "ids":{
    74. "values":[7,8,9]
    75. }
    76. }]
    77. }
    78. }
    79. }
    80. # 多字段查找某个值,只能在同一类型(字符串或数字)的字段中查找,如果给出的字段类型不同会报错
    81. # 如果查找的类型为字符串,会进行分词分别查找
    82. GET /indexName/_doc/_search
    83. {
    84. "query": {
    85. "multi_match": {
    86. "query": "饮料",
    87. "fields": ["title","describe"]
    88. }
    89. }
    90. }
    91. # 默认字段查询,默认字段分词就分词查询,默认字段不分词就不分词查询
    92. GET /indexName/_doc/_search
    93. {
    94. "query":{
    95. "query_string":{
    96. "default_field":"describe",
    97. "query":"好喝"
    98. }
    99. }
    100. }

    10、文档查询其他操作

    1. # 高亮查询结果
    2. GET /indexName/_doc/_search
    3. {
    4. "query":{
    5. "query_string":{
    6. "default_field":"describe",
    7. "query":"好喝"
    8. }
    9. },
    10. "highlight":{ # 高亮关键词
    11. "fields":{
    12. "*":{}
    13. }
    14. }
    15. }
    16. # 控制显示文档条数
    17. GET /indexName/_doc/_search
    18. {
    19. "query":{
    20. "match_all":{}
    21. },
    22. "size":3 # 文档条数关键词
    23. }
    24. # 选择查询的起始位置,从零开始
    25. GET /indexName/_doc/_search
    26. {
    27. "query":{
    28. "match_all":{}
    29. },
    30. "from":0
    31. }
    32. # 对查询结果进行排序
    33. GET /indexName/_doc/_search
    34. {
    35. "query":{
    36. "match_all":{}
    37. },
    38. "sort":{ # 排序关键词
    39. "price":{
    40. "order":"desc" # 选择降序
    41. }
    42. }
    43. }
    44. # 查询指定字段
    45. GET /indexName/_doc/_search
    46. {
    47. "query":{
    48. "match_all":{}
    49. },
    50. "_source":["title","describe"] # 指定需要查询的字段
    51. }

    11、ES索引规则:倒排索引

            ES存储区:索引区、元数据区

            倒排索引:把文档存在元数据区,将文档中不同类别和分词的数据分别与文档id绑定存在索引区,查询时,根据索引区数据找到对应元数据区的文档。

    12、ES默认标准分词器

            结构:字符过滤器(进行预处理例如过滤html标签)、分词器、Token过滤器(加工分好的词)

            内置分词器:

                    ①标准分词器Standard:英文按单词切分,中文按字切分,过滤符号,并小写处理

                    ②简单分词器Simple:英文按单词切分中文按空格切分,过滤符号,小写处理

                    ③停用词过滤分词器Stop:小写处理,停用this、a、an等词的过滤

                    ④Whitespace:按空格切分,不过滤符号,不小写处理

                    ⑤Keyword:不分词

    1. # standard
    2. POST /_analyze
    3. {
    4. "analyzer": "standard"
    5. , "text": ["i am a good boy"]
    6. }
    7. # simple
    8. POST /_analyze
    9. {
    10. "analyzer": "simple"
    11. , "text": ["i am a good boy,这里是中文"]
    12. }
    13. # whitespace
    14. POST /_analyze
    15. {
    16. "analyzer": "whitespace"
    17. , "text": ["I am a good boy,这里是中文"]
    18. }
    19. # 创建映射时手动指定字段的分词器,只能指定可以分词的类型
    20. PUT /user
    21. {
    22. "settings": {
    23. "number_of_shards": 1
    24. , "number_of_replicas": 0
    25. },
    26. "mappings": {
    27. "properties": {
    28. "title":{
    29. "type": "text"
    30. , "analyzer": "standard"
    31. }
    32. }
    33. }
    34. }

     13、中文分词器IK

    1. # 分词器版本与ES版本一致
    2. # 下载分词器https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v7.14.0/elasticsearch-analysis-ik-7.14.0.zip
    3. # 解压至es容器中plugins目录
    4. # 粗粒度分词器
    5. POST /_analyze
    6. {
    7. "analyzer": "ik_smart"
    8. ,"text": ["这里是中文"]
    9. }
    10. # 细粒度分词器
    11. POST /_analyze
    12. {
    13. "analyzer": "ik_max_word"
    14. ,"text": ["这里是中文"]
    15. }

    14、扩展词:将非关键词的词加入词典

            停用词:将关键词移除词典

    1. # IK设置扩展词典和停用词典
    2. # 在ik/config/IKAnalyzer.cfg.xml文件中设置停用词典文件和扩展词典文件
    3. # 两个文件与IKAnalyzer.cfg.xml放在同一目录中,文件中每一行设置一个关键词

    15、过滤查询

    1. # 必须包裹在布尔查询内,与布尔查询连用,有filter关键字省略query关键字
    2. # 先执行filter再执行布尔
    3. GET /product/_doc/_search
    4. {
    5. "query":{
    6. "bool":{
    7. "must":[{
    8. "range":{
    9. "price":{
    10. "lte":10
    11. ,"gte":0
    12. }
    13. }
    14. }],
    15. "filter":{
    16. "wildcard":{
    17. "describe":"*喝*"
    18. }
    19. }
    20. }
    21. }
    22. }

    16、ES整合SpringBoot

    1. # 依赖
    2. <dependency>
    3. <groupId>org.springframework.boot</groupId>
    4. <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
    5. </dependency>
    6. # 配置
    7. @Configuration
    8. public class ESConfig extends AbstractElasticsearchConfiguration {
    9. @Value("${url}")
    10. String url;
    11. @Override
    12. @Bean
    13. public RestHighLevelClient elasticsearchClient() {
    14. final ClientConfiguration clientConfiguration = ClientConfiguration.builder().connectedTo(url).build();
    15. return RestClients.create(clientConfiguration).rest();
    16. }
    17. }

    17、两种操作ES方式:

            ElasticserachOperations        面向对象

            RestHighLevelClient        restful风格、封装了ES细节

    18、ElasticserachOperations方式

    1. //实体类创建索引
    2. @Document(indexName = "product",createIndex = true) //索引名,是否创建索引
    3. public class Product {
    4. @Id //将id与文档_id进行映射
    5. private Integer id;
    6. @Field(type = FieldType.Keyword) //主要是指定字段类型
    7. private String title;
    8. @Field(type = FieldType.Double)
    9. private Double price;
    10. @Field(type = FieldType.Text)
    11. private String describe;
    12. }
    13. //创建索引并插入文档对象
    14. @SpringBootTest //测试类注解该加还得加,不然无法注入
    15. public class Test {
    16. @Autowired
    17. ElasticsearchOperations elasticsearchOperations;
    18. @org.junit.jupiter.api.Test
    19. public void create(){
    20. Product product = new Product();
    21. product.setId(1);
    22. product.setTitle("上周青花瓷");
    23. product.setPrice(3.99);
    24. product.setDescribe("的确是上周的青花瓷,还带着烟火香");
    25. elasticsearchOperations.save(product); //文档对象存入es,id不存在添加,id存在更新
    26. }
    27. }
    28. //根据id查询文档对象
    29. @org.junit.jupiter.api.Test
    30. public void get(){
    31. Product product = elasticsearchOperations.get("1",Product.class);
    32. System.out.println(product.toString());
    33. }
    34. //删除全部文档
    35. @org.junit.jupiter.api.Test
    36. public void deleteAll(){
    37. elasticsearchOperations.delete(Query.findAll(), Product.class);
    38. }
    39. //查询全部文档
    40. @org.junit.jupiter.api.Test
    41. public void find() throws JsonProcessingException {
    42. SearchHits<Product> searchHits = elasticsearchOperations.search(Query.findAll(), Product.class);
    43. for (SearchHit<Product> s :searchHits){
    44. System.out.println(new ObjectMapper().writeValueAsString(s.getContent()));
    45. }
    46. }

    19、RestHighLevelClient方式

    创建索引

    1. //使用Query DSL语法,创建索引
    2. @Test
    3. public void creat() throws IOException {
    4. CreateIndexRequest createIndexRequest = new CreateIndexRequest("product"); //创建索引名
    5. createIndexRequest.settings("{\n" + //设置分片
    6. " \"number_of_shards\": 1\n" +
    7. " , \"number_of_replicas\": 0\n" +
    8. " }",XContentType.JSON);
    9. createIndexRequest.mapping("{\n" + //设置映射
    10. " \"properties\": {\n" +
    11. " \"id\":{\n" +
    12. " \"type\": \"integer\" \n" +
    13. " },\n" +
    14. " \"title\":{\n" +
    15. " \"type\": \"keyword\"\n" +
    16. " },\n" +
    17. " \"price\":{\n" +
    18. " \"type\": \"double\"\n" +
    19. " },\n" +
    20. " \"update_time\":{\n" +
    21. " \"type\": \"date\"\n" +
    22. " },\n" +
    23. " \"describe\":{\n" +
    24. " \"type\": \"text\"\n" +
    25. " , \"analyzer\": \"ik_max_word\"\n" +
    26. " }\n" +
    27. " }}", XContentType.JSON);
    28. CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
    29. restHighLevelClient.close();
    30. }

    删除索引

    1. @Test
    2. public void delet() throws IOException {
    3. DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("product");
    4. restHighLevelClient.indices().delete(deleteIndexRequest,RequestOptions.DEFAULT);
    5. restHighLevelClient.close();
    6. }

    向指定索引中增加数据

    1. @Test
    2. public void add() throws IOException {
    3. IndexRequest indexRequest = new IndexRequest("product"); //指定索引
    4. indexRequest.id("1"); //指定id、可以不指定自动分配
    5. indexRequest.source("{\n" + //指定数据
    6. " \"title\":\"电冰箱\",\n" +
    7. " \"price\":2.99,\n" +
    8. " \"update_time\":\"2023-03-25\",\n" +
    9. " \"describe\":\"很好用\"\n" +
    10. "}",XContentType.JSON);
    11. restHighLevelClient.index(indexRequest,RequestOptions.DEFAULT);
    12. restHighLevelClient.close();
    13. }

    更新文档

    1. @Test
    2. public void update() throws IOException {
    3. UpdateRequest updateRequest = new UpdateRequest("product","1");
    4. updateRequest.doc("{\n" +
    5. " \"title\":\"电视据\"\n" +
    6. " }",XContentType.JSON);
    7. restHighLevelClient.update(updateRequest,RequestOptions.DEFAULT);
    8. restHighLevelClient.close();
    9. }

    删除文档

    1. @Test
    2. public void dele() throws IOException {
    3. DeleteRequest deleteRequest = new DeleteRequest("product");
    4. deleteRequest.id("1");
    5. restHighLevelClient.delete(deleteRequest,RequestOptions.DEFAULT);
    6. restHighLevelClient.close();
    7. }

    基于id查询文档

    1. @Test
    2. public void gett() throws IOException {
    3. GetRequest getRequest = new GetRequest("product");
    4. getRequest.id("1");
    5. GetResponse getResponse = restHighLevelClient.get(getRequest,RequestOptions.DEFAULT);
    6. String s = getResponse.toString();
    7. System.out.println(s);
    8. restHighLevelClient.close();
    9. }

    查询所有

    1. @Test
    2. public void getAll() throws IOException {
    3. SearchRequest searchRequest = new SearchRequest("product");
    4. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    5. searchSourceBuilder.query(QueryBuilders.matchAllQuery());
    6. searchRequest.source(searchSourceBuilder);
    7. //searchResponse结果就是kibana中查询返回结果
    8. SearchResponse searchResponse = restHighLevelClient.search(searchRequest,RequestOptions.DEFAULT);
    9. String s = searchResponse.toString();
    10. System.out.println(s);
    11. }

    按条件查询

    1. @Test
    2. public void quer() throws IOException {
    3. SearchRequest searchRequest = new SearchRequest("product");
    4. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    5. searchSourceBuilder.query(QueryBuilders.termQuery("describe","好用"));
    6. searchRequest.source(searchSourceBuilder);
    7. SearchResponse searchResponse = restHighLevelClient.search(searchRequest,RequestOptions.DEFAULT);
    8. String s = searchResponse.toString();
    9. System.out.println(s);
    10. }

    分页查询,指定从第二条开始查询,总计查询一条

    1. @Test
    2. public void sort() throws IOException {
    3. SearchRequest searchRequest = new SearchRequest("product");
    4. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    5. searchSourceBuilder.query(QueryBuilders.matchAllQuery()).from(1).size(1);
    6. searchRequest.source(searchSourceBuilder);
    7. SearchResponse s = restHighLevelClient.search(searchRequest,RequestOptions.DEFAULT);
    8. System.out.println(s.toString());
    9. }

    降序查询

    1. @Test
    2. public void sort() throws IOException {
    3. SearchRequest searchRequest = new SearchRequest("product");
    4. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    5. searchSourceBuilder.query(QueryBuilders.matchAllQuery()).from(0).size(10).sort("price",SortOrder.DESC);
    6. searchRequest.source(searchSourceBuilder);
    7. SearchResponse s = restHighLevelClient.search(searchRequest,RequestOptions.DEFAULT);
    8. System.out.println(s.toString());
    9. }

    返回指定的字段,排除describe,接受title、price

    1. @Test
    2. public void sort() throws IOException {
    3. SearchRequest searchRequest = new SearchRequest("product");
    4. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    5. searchSourceBuilder.query(QueryBuilders.matchAllQuery()).from(0).size(10).sort("price",SortOrder.DESC).fetchSource(new String[]{"price","title"},new String[]{"describe"});
    6. searchRequest.source(searchSourceBuilder);
    7. SearchResponse s = restHighLevelClient.search(searchRequest,RequestOptions.DEFAULT);
    8. System.out.println(s.toString());
    9. }

    使用HighLightBuilder对查询结果进行高亮显示

    1. @Test
    2. public void quer() throws IOException {
    3. SearchRequest searchRequest = new SearchRequest("product");
    4. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    5. HighlightBuilder highlightBuilder = new HighlightBuilder();
    6. highlightBuilder.requireFieldMatch(false).field("describe").field("title");
    7. searchSourceBuilder.query(QueryBuilders.termQuery("describe","好喝")).highlighter(highlightBuilder);
    8. searchRequest.source(searchSourceBuilder);
    9. SearchResponse searchResponse = restHighLevelClient.search(searchRequest,RequestOptions.DEFAULT);
    10. String s = searchResponse.toString();
    11. System.out.println(s);
    12. }

    过滤查询

    1. @Test
    2. public void fget() throws IOException {
    3. SearchRequest searchRequest = new SearchRequest("product");
    4. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    5. searchSourceBuilder.query(QueryBuilders.matchAllQuery()).postFilter(QueryBuilders.termQuery("describe","好喝"));
    6. searchRequest.source(searchSourceBuilder);
    7. SearchResponse s =restHighLevelClient.search(searchRequest,RequestOptions.DEFAULT);
    8. System.out.println(s);
    9. }

    ES对象存取

    1. //作为对象存入
    2. @Test
    3. public void las() throws IOException {
    4. Product product = new Product();
    5. product.setId(4);
    6. product.setTitle("黑鱼片");
    7. product.setPrice(28.0);
    8. product.setDescribe("很好吃");
    9. product.setUpdate_time(new Date());
    10. IndexRequest indexRequest = new IndexRequest("product");
    11. indexRequest.id(String.valueOf(product.getId())).source(new ObjectMapper().writeValueAsString(product),XContentType.JSON);
    12. IndexResponse s = restHighLevelClient.index(indexRequest,RequestOptions.DEFAULT);
    13. System.out.println(s.isFragment());
    14. }
    15. //取出存为对象
    16. @Test
    17. public void lget() throws IOException, JSONException {
    18. SearchRequest searchRequest = new SearchRequest("product");
    19. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    20. searchSourceBuilder.query(QueryBuilders.matchAllQuery());
    21. searchRequest.source(searchSourceBuilder);
    22. SearchResponse s = restHighLevelClient.search(searchRequest,RequestOptions.DEFAULT);
    23. org.elasticsearch.search.SearchHit[] searchHits = s.getHits().getHits();
    24. List<Product> list = new ArrayList<>();
    25. for (org.elasticsearch.search.SearchHit a :searchHits){
    26. Product product = new ObjectMapper().readValue(a.getSourceAsString(),Product.class);
    27. list.add(product);
    28. }
    29. for (int i =0;i<list.size();i++){
    30. System.out.println(list.get(i));}
    31. }

    20、聚合查询

    Query DSL

    1. //查某一个字段,
    2. GET /product/_search
    3. {
    4. "query":{
    5. "match_all": {}
    6. },
    7. "aggs":{
    8. "dd_all":{ //这里是聚合查询名,可以随便定义
    9. "terms": {
    10. "field": "price", //查询价格
    11. "size": 10
    12. }
    13. }
    14. }
    15. }
    16. //查询最大值
    17. GET /product/_search
    18. {
    19. "query": {
    20. "match_all": {}
    21. },
    22. "aggs": {
    23. "dd_max":{
    24. "max": {
    25. "field": "price" //查询价格最大值
    26. }
    27. }
    28. }
    29. }
    30. //查询最小值
    31. GET /product/_search
    32. {
    33. "query": {
    34. "match_all": {}
    35. },
    36. "aggs": {
    37. "dd_min":{
    38. "min": {
    39. "field": "price" //这里查询价格最小值
    40. }
    41. }
    42. }
    43. }
    44. //查询平均值
    45. GET /product/_search
    46. {
    47. "query": {
    48. "match_all": {}
    49. },
    50. "aggs": {
    51. "dd_average":{
    52. "avg": {
    53. "field": "price" //这里查询价格平均值
    54. }
    55. }
    56. }
    57. }

    RestHighLevelClient

    1. //查询字段所有
    2. @Test
    3. public void agg() throws IOException {
    4. SearchRequest searchRequest = new SearchRequest("product");
    5. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    6. searchSourceBuilder.query(QueryBuilders.matchAllQuery()).aggregation(AggregationBuilders.terms("price_all").field("price"));
    7. searchRequest.source(searchSourceBuilder);
    8. SearchResponse s = restHighLevelClient.search(searchRequest,RequestOptions.DEFAULT);
    9. System.out.println(s);
    10. }
    11. //查询字段最大值
    12. @Test
    13. public void aggm() throws IOException {
    14. SearchRequest searchRequest = new SearchRequest("product");
    15. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    16. searchSourceBuilder.query(QueryBuilders.matchAllQuery()).aggregation(AggregationBuilders.max("max_all").field("price"));
    17. searchRequest.source(searchSourceBuilder);
    18. SearchResponse s = restHighLevelClient.search(searchRequest,RequestOptions.DEFAULT);
    19. System.out.println(s);
    20. }
    21. //

     21、集群搭建

    配置文件

    1. # 集群名称
    2. cluster.name: es_cluster
    3. # 节点名称
    4. node.name: node_1
    5. # 开启远程访问
    6. network.host: 0.0.0.0
    7. # 使用发布地址进行集群间通信
    8. network.publish_host: IP
    9. # http通信端口
    10. http.port: 9201
    11. # tcp通信端口
    12. transport.tcp.port: 9301
    13. # 指定节点的tcp通信
    14. discovery.seed_hosts: ["IP:9301","IP:9302","IP:9303"]
    15. # 集群初始化节点
    16. cluster.initial_master_nodes: ["node_1","node_2","node_3"]
    17. # 集群最少可用节点
    18. gateway.recover_after_nodes: 2
    19. # 开启跨域
    20. http.cors.enabled: true
    21. # 跨域请求前缀
    22. http.cors.allow-origin: "*"

    kibana配置到es集群

    1. server.host: "0"
    2. server.shutdownTimeout: "5s"
    3. elasticsearch.hosts: [ "http://IP:9201","http://IP:9202","http://IP:9203" ]
    4. monitoring.ui.container.elasticsearch.enabled: true

  • 相关阅读:
    JS: 运算符
    一文读懂机智云物联网APP开发
    计算机毕业设计Java创新学分认证系统(源码+系统+mysql数据库+lw文档)
    百度面试——AI算法岗
    ESP8266-Arduino网络编程实例-Web页面WiFi配置管理
    【Mysql】子查询
    Android开发之——Jetpack Compose入门(01)
    为什么 Spring和IDEA 都不推荐使用 @Autowired 注解
    ENVI_常用扩展工具名
    TensorFlow模型训练常见案例
  • 原文地址:https://blog.csdn.net/nlhkfcdxb/article/details/131666574