ElasticSearch高级操作


在这里插入图片描述

想学习架构师构建流程请跳转:Java架构师系统架构设计

1 ElasticSearch高级操作

1.1 bulk批量操作-脚本

在这里插入图片描述

脚本:

测试用的5号文档

POST /person1/_doc/5
{
  "name":"张三5号",
  "age":18,
  "address":"北京海淀区"
}

批量操作文本

#批量操作
#1.删除5号
#新增8号
#更新2号 name为2POST _bulk
{"delete":{"_index":"person1","_id":"5"}}
{"create":{"_index":"person1","_id":"8"}}
{"name":"八号","age":18,"address":"北京"}
{"update":{"_index":"person1","_id":"2"}}
{"doc":{"name":"2号"}}

结果

{
  "took" : 51,
  "errors" : true,
  "items" : [
    {
      "delete" : {
        "_index" : "person1",
        "_type" : "_doc",
        "_id" : "5",
        "_version" : 2,
        "result" : "deleted",
        "_shards" : {
          "total" : 2,
          "successful" : 1,
          "failed" : 0
        },
        "_seq_no" : 6,
        "_primary_term" : 2,
        "status" : 200
      }
    },
    {
      "create" : {
        "_index" : "person1",
        "_type" : "_doc",
        "_id" : "8",
        "_version" : 1,
        "result" : "created",
        "_shards" : {
          "total" : 2,
          "successful" : 1,
          "failed" : 0
        },
        "_seq_no" : 7,
        "_primary_term" : 2,
        "status" : 201
      }
    },
    {
      "update" : {
        "_index" : "person1",
        "_type" : "_doc",
        "_id" : "2",
        "_version" : 2,
        "result" : "updated",
        "_shards" : {
          "total" : 2,
          "successful" : 1,
          "failed" : 0
        },
        "_seq_no" : 10,
        "_primary_term" : 2,
        "status" : 200
      }
    }
  ]
}

1.2 bulk批量操作-JavaAPI

 /**
     *  Bulk 批量操作
     */
    @Test
    public void test2() throws IOException {

        //创建bulkrequest对象,整合所有操作
        BulkRequest bulkRequest =new BulkRequest();

           /*
        # 1. 删除5号记录
        # 2. 添加6号记录
        # 3. 修改3号记录 名称为 “三号”
         */
        //添加对应操作
        //1. 删除5号记录
        DeleteRequest deleteRequest=new DeleteRequest("person1","5");
        bulkRequest.add(deleteRequest);

        //2. 添加6号记录
        Map<String, Object> map=new HashMap<>();
        map.put("name","六号");
        IndexRequest indexRequest=new IndexRequest("person1").id("6").source(map);
        bulkRequest.add(indexRequest);
        //3. 修改3号记录 名称为 “三号”
        Map<String, Object> mapUpdate=new HashMap<>();
        mapUpdate.put("name","三号");
        UpdateRequest updateRequest=new UpdateRequest("person1","3").doc(mapUpdate);

        bulkRequest.add(updateRequest);
        //执行批量操作


        BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(response.status());

    }

1.3 导入数据-分析&创建索引

在这里插入图片描述

PUT goods
{
	"mappings": {
		"properties": {
			"title": {
				"type": "text",
				"analyzer": "ik_smart"
			},
			"price": { 
				"type": "double"
			},
			"createTime": {
				"type": "date"
			},
			"categoryName": {	
				"type": "keyword"
			},
			"brandName": {	
				"type": "keyword"
			},
	
			"spec": {		
				"type": "object"
			},
			"saleNum": {	
				"type": "integer"
			},
			
			"stock": {	
				"type": "integer"
			}
		}
	}
}

1.4 导入数据-代码实现

package com.itheima.elasticsearchdemo2.domain;

import com.alibaba.fastjson.annotation.JSONField;

import java.util.Date;
import java.util.Map;

public class Goods {

   private int id;
   private String title;
   private double price;
   private int stock;
   private int saleNum;
   private Date createTime;
   private String categoryName;
   private String brandName;
   private Map spec;

   @JSONField(serialize = false)//在转换JSON时,忽略该字段
   private String specStr;//接收数据库的信息 "{}"


   public int getId() {
       return id;
   }

   public void setId(int id) {
       this.id = id;
   }

   public String getTitle() {
       return title;
   }

   public void setTitle(String title) {
       this.title = title;
   }

   public double getPrice() {
       return price;
   }

   public void setPrice(double price) {
       this.price = price;
   }

   public int getStock() {
       return stock;
   }

   public void setStock(int stock) {
       this.stock = stock;
   }

   public int getSaleNum() {
       return saleNum;
   }

   public void setSaleNum(int saleNum) {
       this.saleNum = saleNum;
   }

   public Date getCreateTime() {
       return createTime;
   }

   public void setCreateTime(Date createTime) {
       this.createTime = createTime;
   }

   public String getCategoryName() {
       return categoryName;
   }

   public void setCategoryName(String categoryName) {
       this.categoryName = categoryName;
   }

   public String getBrandName() {
       return brandName;
   }

   public void setBrandName(String brandName) {
       this.brandName = brandName;
   }

   public Map getSpec() {
       return spec;
   }

   public void setSpec(Map spec) {
       this.spec = spec;
   }

   public String getSpecStr() {
       return specStr;
   }

   public void setSpecStr(String specStr) {
       this.specStr = specStr;
   }


   @Override
   public String toString() {
       return "Goods{" +
               "id=" + id +
               ", title='" + title + '\'' +
               ", price=" + price +
               ", stock=" + stock +
               ", saleNum=" + saleNum +
               ", createTime=" + createTime +
               ", categoryName='" + categoryName + '\'' +
               ", brandName='" + brandName + '\'' +
               ", spec=" + spec +
               ", specStr='" + specStr + '\'' +
               '}';
   }
}

package com.itheima.elasticsearchdemo2.mapper;

import com.itheima.elasticsearchdemo2.domain.Goods;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
@Mapper
public interface GoodsMapper {


    /**
     * 查询所有
     */
    public List<Goods> findAll();

}

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">


<mapper namespace="com.itheima.elasticsearchdemo2.mapper.GoodsMapper">



    <select id="findAll" resultType="goods">
        select
              `id`         ,
              `title`       ,
              `price`       ,
              `stock`       ,
              `saleNum`     ,
              `createTime`  ,
              `categoryName`,
              `brandName`   ,
              `spec`  as specStr

         from goods


    </select>


</mapper>
 /**
     * 从Mysql 批量导入 elasticSearch
     */
    @Test
    public void test3() throws IOException {
        //1.查询所有数据,mysql
        List<Goods> goodsList = goodsMapper.findAll();

        //2.bulk导入
        BulkRequest bulkRequest=new BulkRequest();

        //2.1 循环goodsList,创建IndexRequest添加数据
        for (Goods goods : goodsList) {

            //2.2 设置spec规格信息 Map的数据   specStr:{}
            String specStr = goods.getSpecStr();

            //将json格式字符串转为Map集合
            Map map = JSON.parseObject(specStr, Map.class);

            //设置spec map
            goods.setSpec(map);

            //将goods对象转换为json字符串
            String data = JSON.toJSONString(goods);

            IndexRequest indexRequest=new IndexRequest("goods").source(data,XContentType.JSON);
            bulkRequest.add(indexRequest);

        }


        BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(response.status());

    }

1.5 导入数据-代码实现-详解

转换成JSON的原因:

#spec配置的数据类型是JSON对象,所以当存放字符串的时候报错
			"spec": {		
				"type": "object"
			},

错误信息

在这里插入图片描述

2 ElasticSearch查询

2.1 matchAll-脚本

# 默认情况下,es一次展示10条数据,通过from和size来控制分页
# 查询结果详解

GET goods/_search
{
  "query": {
    "match_all": {}
  },
  "from": 0,
  "size": 100
}

GET goods

2.2 matchAll获取总记录数查询所有对象-JavaAPI

/**
     * 查询所有
     *  1. matchAll
     *  2. 将查询结果封装为Goods对象,装载到List中
     *  3. 分页。默认显示10条
     */
    @Test
    public void matchAll() throws IOException {

        //2. 构建查询请求对象,指定查询的索引名称
        SearchRequest searchRequest=new SearchRequest("goods");

        //4. 创建查询条件构建器SearchSourceBuilder
        SearchSourceBuilder sourceBuilder=new SearchSourceBuilder();

        //6. 查询条件
        QueryBuilder queryBuilder= QueryBuilders.matchAllQuery();
        //5. 指定查询条件
        sourceBuilder.query(queryBuilder);

        //3. 添加查询条件构建器 SearchSourceBuilder
        searchRequest.source(sourceBuilder);
        // 8 . 添加分页信息  不设置 默认10条
//        sourceBuilder.from(0);
//        sourceBuilder.size(100);
        //1. 查询,获取查询结果

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

        //7. 获取命中对象 SearchHits
        SearchHits hits = searchResponse.getHits();

        //7.1 获取总记录数
      Long total= hits.getTotalHits().value;
        System.out.println("总数:"+total);
        //7.2 获取Hits数据  数组
        SearchHit[] hits1 = hits.getHits();
            //获取json字符串格式的数据
        List<Goods> goodsList = new ArrayList<>();
        for (SearchHit searchHit : hits1) {
            String sourceAsString = searchHit.getSourceAsString();
            //转为java对象
            Goods goods = JSON.parseObject(sourceAsString, Goods.class);
            goodsList.add(goods);
        }

        for (Goods goods : goodsList) {
            System.out.println(goods);
        }

    }

设置条件的疑问点

在这里插入图片描述

2.3 termQuery 词条查询查询具体的词组不副词

term查询和字段类型有关系,首先回顾一下ElasticSearch两个数据类型

ElasticSearch两个数据类型

text:会分词,不支持聚合

keyword:不会分词,将全部内容作为一个词条,支持聚合

term查询:不会对查询条件进行分词。

GET goods/_search
{
  "query": {
    "term": {
      "title": {
        "value": "华为"
      }
    }
  }
}

term查询,查询text类型字段时,只有其中的单词相匹配都会查到,text字段会对数据进行分词

例如:查询title 为“华为”的,title type 为text

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

查询categoryName 字段时,categoryName字段为keyword ,keyword:不会分词,将全部内容作为一个词条,

即完全匹配,才能查询出结果

在这里插入图片描述

GET goods/_search
{
  "query": {
    "term": {
      "categoryName": {
        "value": "华为手机"
      }
    }
  }
}

在这里插入图片描述

2.4 matchQuery 查询条件进行分词or或and进行查询

match查询:

•会对查询条件进行分词。

•然后将分词后的查询条件和词条进行等值匹配

•默认取并集(OR)

# match查询
GET goods/_search
{
  "query": {
    "match": {
      "title": "华为手机"
    }
  },
  "size": 500
}

match 的默认搜索(or 并集)

例如:华为手机,会分词为 “华为”,“手机” 只要出现其中一个词条都会搜索到

match的 and(交集) 搜索

例如:例如:华为手机,会分词为 “华为”,“手机” 但要求“华为”,和“手机”同时出现在词条中

总结:

  • term query会去倒排索引中寻找确切的term,它并不知道分词器的存在。这种查询适合keywordnumericdate
  • match query知道分词器的存在。并且理解是如何被分词的

2.5 模糊查询-脚本

2.5.1 wildcard查询

wildcard查询:会对查询条件进行分词。还可以使用通配符 ?(任意单个字符) 和 * (0个或多个字符)

"*华*"  包含华字的
"华*"   华字后边多个字符
"华?"  华字后边多个字符
"*华"或"?华" 会引发全表(全索引)扫描 注意效率问题
# wildcard 查询。查询条件分词,模糊查询
GET goods/_search
{
  "query": {
    "wildcard": {
      "title": {
        "value": "华*"
      }
    }
  }
}

2.5.2正则查询

\W:匹配包括下划线的任何单词字符,等价于 [A-Z a-z 0-9_]   开头的反斜杠是转义符

+号多次出现

(.)*为任意字符
正则查询取决于正则表达式的效率

GET goods/_search
{
  "query": {
    "regexp": {
      "title": "\\w+(.)*"
    }
  }
}

2.5.3前缀查询

对keyword类型支持比较好

# 前缀查询 对keyword类型支持比较好
GET goods/_search
{
  "query": {
    "prefix": {
      "brandName": {
        "value": "三"
      }
    }
  }
}

2.6 模糊查询-JavaAPI

//模糊查询
WildcardQueryBuilder query = QueryBuilders.wildcardQuery("title", "华*");//华后多个字符
//正则查询
 RegexpQueryBuilder query = QueryBuilders.regexpQuery("title", "\\w+(.)*");
 //前缀查询
 PrefixQueryBuilder query = QueryBuilders.prefixQuery("brandName", "三");

2.7 范围&排序查询

# 范围查询

GET goods/_search
{
  "query": {
    "range": {
      "price": {
        "gte": 2000,
        "lte": 3000
      }
    }
  },
  "sort": [
    {
      "price": {
        "order": "desc"
      }
    }
  ]
}
 //范围查询 以price 价格为条件
RangeQueryBuilder query = QueryBuilders.rangeQuery("price");

//指定下限
query.gte(2000);
//指定上限
query.lte(3000);

sourceBuilder.query(query);

//排序  价格 降序排列
sourceBuilder.sort("price",SortOrder.DESC);

2.8 queryString查询-多个字段取并集查询

queryString 多条件查询

•会对查询条件进行分词。

•然后将分词后的查询条件和词条进行等值匹配

•默认取并集(OR)

•可以指定多个查询字段

query_string:识别query中的连接符(or 、and)

# queryString

GET goods/_search
{
  "query": {
    "query_string": {
      "fields": ["title","categoryName","brandName"], 
      "query": "华为 AND 手机"
    }
  }
}

simple_query_string:不识别query中的连接符(or 、and),查询时会将 “华为”、“and”、“手机”分别进行查询

GET goods/_search
{
  "query": {
    "simple_query_string": {
      "fields": ["title","categoryName","brandName"], 
      "query": "华为 AND 手机"
    }
  }
}

query_string:有default_operator连接符的脚本

GET goods/_search
{
  "query": {
    "query_string": {
      "fields": ["title","brandName","categoryName"],
      "query": "华为手机 "
      , "default_operator": "AND"
    }
  }
}

java代码

QueryStringQueryBuilder query = QueryBuilders.queryStringQuery("华为手机").field("title").field("categoryName")
.field("brandName").defaultOperator(Operator.AND);

simple_query_string:有default_operator连接符的脚本

GET goods/_search
{
  "query": {
    "simple_query_string": {
      "fields": ["title","brandName","categoryName"],
      "query": "华为手机 "
      , "default_operator": "OR"
    }
  }
}

注意:query中的or and 是查询时 匹配条件是否同时出现----or 出现一个即可,and 两个条件同时出现

default_operator的or and 是对结果进行 并集(or)、交集(and)

2.9 布尔查询-脚本

boolQuery:对多个查询条件连接。连接方式:

•must(and):条件必须成立

•must_not(not):条件必须不成立

•should(or):条件可以成立

•filter:条件必须成立,性能比must高。不会计算得分

**得分:**即条件匹配度,匹配度越高,得分越高

# boolquery
#must和filter配合使用时,max_score(得分)是显示的
#must 默认数组形式
GET goods/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "brandName": {
              "value": "华为"
            }
          }
        }
      ],
      "filter":[ 
        {
        "term": {
          "title": "手机"
        }
       },
       {
         "range":{
          "price": {
            "gte": 2000,
            "lte": 3000
         }
         }
       }
      
      ]
    }
  }
}
#filter 单独使用   filter可以是单个条件,也可多个条件(数组形式)
GET goods/_search
{
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            "brandName": {
              "value": "华为"
            }
          }
        }
      ]
    }
  }
}

2.10 布尔查询-JavaAPI-对多个查询条件连接

布尔查询:boolQuery

  1. 查询品牌名称为:华为
  2. 查询标题包含:手机
  3. 查询价格在:2000-3000

must 、filter为连接方式

term、match为不同的查询方式

       //1.构建boolQuery
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //2.构建各个查询条件
        //2.1 查询品牌名称为:华为
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("brandName", "华为");
        boolQuery.must(termQueryBuilder);
        //2.2. 查询标题包含:手机
        MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("title", "手机");
        boolQuery.filter(matchQuery);

        //2.3 查询价格在:2000-3000
        RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("price");
        rangeQuery.gte(2000);
        rangeQuery.lte(3000);
        boolQuery.filter(rangeQuery);

        sourceBuilder.query(boolQuery);

2.11 聚合查询-脚本

•指标聚合:相当于MySQL的聚合函数。max、min、avg、sum等

•桶聚合:相当于MySQL的 group by 操作。不要对text类型的数据进行分组,会失败。

# 聚合查询

# 指标聚合 聚合函数

GET goods/_search
{
  "query": {
    "match": {
      "title": "手机"
    }
  },
  "aggs": {
    "max_price": {
      "max": {
        "field": "price"
      }
    }
  }
}

# 桶聚合  分组

GET goods/_search
{
  "query": {
    "match": {
      "title": "手机"
    }
  },
  "aggs": {
    "goods_brands": {
      "terms": {
        "field": "brandName",
        "size": 100
      }
    }
  }
}

2.12 聚合查询-JavaAPI

聚合查询:桶聚合,分组查询

  1. 查询title包含手机的数据
  2. 查询品牌列表
/**
     * 聚合查询:桶聚合,分组查询
     * 1. 查询title包含手机的数据
     * 2. 查询品牌列表
     */
@Test
public void testAggQuery() throws IOException {

    SearchRequest searchRequest=new SearchRequest("goods");

    SearchSourceBuilder sourceBuilder=new SearchSourceBuilder();
    //1. 查询title包含手机的数据

    MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("title", "手机");

    sourceBuilder.query(queryBuilder);
    //2. 查询品牌列表  只展示前100条
    AggregationBuilder aggregation=AggregationBuilders.terms("goods_brands").field("brandName").size(100);
    sourceBuilder.aggregation(aggregation);


    searchRequest.source(sourceBuilder);

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

    //7. 获取命中对象 SearchHits
    SearchHits hits = searchResponse.getHits();

    //7.1 获取总记录数
    Long total= hits.getTotalHits().value;
    System.out.println("总数:"+total);

    // aggregations 对象
    Aggregations aggregations = searchResponse.getAggregations();
    //将aggregations 转化为map
    Map<String, Aggregation> aggregationMap = aggregations.asMap();


    //通过key获取goods_brands 对象 使用Aggregation的子类接收  buckets属性在Terms接口中体现

    //        Aggregation goods_brands1 = aggregationMap.get("goods_brands");
    Terms goods_brands =(Terms) aggregationMap.get("goods_brands");

    //获取buckets 数组集合
    List<? extends Terms.Bucket> buckets = goods_brands.getBuckets();

    Map<String,Object>map=new HashMap<>();
    //遍历buckets   key 属性名,doc_count 统计聚合数
    for (Terms.Bucket bucket : buckets) {

        System.out.println(bucket.getKey());
        map.put(bucket.getKeyAsString(),bucket.getDocCount());
    }

    System.out.println(map);

}

2.13 高亮查询-脚本

高亮三要素:

•高亮字段

•前缀

•后缀

默认前后缀 :em

<em>手机</em>
GET goods/_search
{
  "query": {
    "match": {
      "title": "电视"
    }
  },
  "highlight": {
    "fields": {
      "title": {
        "pre_tags": "<font color='red'>",
        "post_tags": "</font>"
      }
    }
  }
}

2.14 高亮查询-JavaAPI

实施步骤:
高亮查询:
1. 设置高亮
高亮字段
前缀
后缀
2. 将高亮了的字段数据,替换原有数据

/**
     *
     * 高亮查询:
     *  1. 设置高亮
     *      * 高亮字段
     *      * 前缀
     *      * 后缀
     *  2. 将高亮了的字段数据,替换原有数据
     */
@Test
public void testHighLightQuery() throws IOException {


    SearchRequest searchRequest = new SearchRequest("goods");

    SearchSourceBuilder sourceBulider = new SearchSourceBuilder();

    // 1. 查询title包含手机的数据
    MatchQueryBuilder query = QueryBuilders.matchQuery("title", "手机");

    sourceBulider.query(query);

    //设置高亮
    HighlightBuilder highlighter = new HighlightBuilder();
    //设置三要素
    highlighter.field("title");
    //设置前后缀标签
    highlighter.preTags("<font color='red'>");
    highlighter.postTags("</font>");

    //加载已经设置好的高亮配置
    sourceBulider.highlighter(highlighter);

    searchRequest.source(sourceBulider);

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


    SearchHits searchHits = searchResponse.getHits();
    //获取记录数
    long value = searchHits.getTotalHits().value;
    System.out.println("总记录数:"+value);

    List<Goods> goodsList = new ArrayList<>();
    SearchHit[] hits = searchHits.getHits();
    for (SearchHit hit : hits) {
        String sourceAsString = hit.getSourceAsString();

        //转为java
        Goods goods = JSON.parseObject(sourceAsString, Goods.class);

        // 获取高亮结果,替换goods中的title
        Map<String, HighlightField> highlightFields = hit.getHighlightFields();
        HighlightField HighlightField = highlightFields.get("title");
        Text[] fragments = HighlightField.fragments();
        //highlight title替换 替换goods中的title
        goods.setTitle(fragments[0].toString());
        goodsList.add(goods);
    }

    for (Goods goods : goodsList) {
        System.out.println(goods);
    }


}

2.15 重建索引&索引别名

#查询别名 默认别名无法查看,默认别名同索引名
GET goods/_alias/
#结果
{
  "goods" : {
    "aliases" : { }
  }
}

1.新建student_index_v1索引

# -------重建索引-----------

# 新建student_index_v1。索引名称必须全部小写

PUT student_index_v1
{
  "mappings": {
    "properties": {
      "birthday":{
        "type": "date"
      }
    }
  }
}
#查看 student_index_v1 结构
GET student_index_v1
#添加数据
PUT student_index_v1/_doc/1
{
  "birthday":"1999-11-11"
}
#查看数据
GET student_index_v1/_search

#添加数据
PUT student_index_v1/_doc/1
{
  "birthday":"1999年11月11日"
}

2.重建索引:将student_index_v1 数据拷贝到 student_index_v2

# 业务变更了,需要改变birthday字段的类型为text

# 1. 创建新的索引 student_index_v2
# 2. 将student_index_v1 数据拷贝到 student_index_v2

# 创建新的索引 student_index_v2
PUT student_index_v2
{
  "mappings": {
    "properties": {
      "birthday":{
        "type": "text"
      }
    }
  }
}
# 将student_index_v1 数据拷贝到 student_index_v2
# _reindex 拷贝数据
POST _reindex
{
  "source": {
    "index": "student_index_v1"
  },
  "dest": {
    "index": "student_index_v2"
  }
}

GET student_index_v2/_search



PUT student_index_v2/_doc/2
{
  "birthday":"1999年11月11日"
}

3.创建索引库别名:

注意:DELETE student_index_v1 这一操作将删除student_index_v1索引库,并不是删除别名

# 思考: 现在java代码中操作es,还是使用的实student_index_v1老的索引名称。
# 1. 改代码(不推荐)
# 2. 索引别名(推荐)

# 步骤:
# 0. 先删除student_index_v1
# 1. 给student_index_v2起个别名 student_index_v1



# 先删除student_index_v1
#DELETE student_index_v1 这一操作将删除student_index_v1索引库
#索引库默认的别名与索引库同名,无法删除

# 给student_index_v1起个别名 student_index_v11
POST student_index_v2/_alias/student_index_v11
#测试删除命令
POST /_aliases
{
    "actions": [
        {"remove": {"index": "student_index_v1", "alias": "student_index_v11"}}
    ]
}

# 给student_index_v2起个别名 student_index_v1
POST student_index_v2/_alias/student_index_v1

#查询别名
GET goods/_alias/


GET student_index_v1/_search
GET student_index_v2/_search

3 ES复杂聚合查询

3.1 统计字段总数

    @Override
    public PersonStaticDTO getUserAgg(UserQuery userQuery) {
        SearchQuery query = new NativeSearchQueryBuilder()
            .withQuery(userMapper.getUserQueryBuilder(userQuery))
            //统计这个字段的总数
            .addAggregation(AggregationBuilders.count("userCount").field("accountId"))
            .build();

        AggregatedPage<User> page = elasticsearchTemplate.queryForPage(query, User.class);

        //之后获得这个统计对象 进行赋值
        ValueCount userCount = (ValueCount) page.getAggregation("userCount");

        PersonStaticDTO personStaticDTO = new PersonStaticDTO();
        personStaticDTO.setCount(((Double)userCount.value()).intValue());
        return personStaticDTO;
    }

3.2 枚举分组统计总数

    @Override
    public DeviceRepairCountDTO getRepairAgg(OperatorDeviceRepairQueryDTO operatorDeviceRepairQueryDTO) {
        SearchQuery query = new NativeSearchQueryBuilder()
            .withQuery(RepairQueryUtils.getRepairQueryBuilder(operatorDeviceRepairQueryDTO))
            //通过状态进行分组
            .addAggregation(AggregationBuilders.filter("Pending", QueryBuilders.termQuery("repairStatus", RepairStatus.Pending.ordinal())))
            .addAggregation(AggregationBuilders.filter("Processing", QueryBuilders.termQuery("repairStatus", RepairStatus.Processing.ordinal())))
            .withPageable(PageRequest.of(0, 1))
            .build();


        AggregatedPage<DeviceRepairRecordDoc> page = elasticsearchTemplate.queryForPage(query, DeviceRepairRecordDoc.class);

        //获得分组对象
        InternalFilter repairPending = (InternalFilter) page.getAggregation("Pending");
        InternalFilter repairProcessing = (InternalFilter) page.getAggregation("Processing");
        //接收总数
        DeviceRepairCountDTO deviceRepairCountDTO = new DeviceRepairCountDTO();
        deviceRepairCountDTO.setPendingCount(repairPending.getDocCount());
        deviceRepairCountDTO.setProcessCount(repairProcessing.getDocCount());
        deviceRepairCountDTO.setCount(page.getTotalElements());
        return deviceRepairCountDTO;
    }

3.3 重写分页规则

    @Override
    public Page<ConsumptionBillDTO> getConsumptionListByAccount(Pageable pageable, Long accountId) {
        //重新书写分页顺序条件
        Sort sort = pageable.getSort().and(Sort.by(Sort.Direction.DESC, "createdDate"));
        pageable = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), sort);

        //BoolQueryBuilder查询必须匹配某个字段
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        if (accountId != null) {
            queryBuilder.must(QueryBuilders.termQuery("accountId", accountId));
        }

        SearchQuery query = new NativeSearchQueryBuilder()
            .withQuery(queryBuilder)
            .withPageable(pageable)
            .build();
        //分页查询
        Page<OrderIdxDoc> page = orderIdxRepository.search(query);

        List<OrderIdxDoc> list = page.getContent();
        //list.stream().map  将一个OrderIdxDoc对象之后封装为另一个对象,简化遍历的操作
        List<ConsumptionBillDTO> retList = list.stream().map(orderIdx -> orderMapper.to(orderIdx)).collect(Collectors.toList());

        return new PageImpl(retList, pageable, page.getTotalElements());
    }

3.4 去重总数和范围

   /*
    * 获取设备消耗指标
    * */
    public DeviceConsumeMetric getDeviceConsumeMetric(long deviceId, DeviceQuery deviceQuery) {

        //布尔查询
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();

        //匹配 deviceId后面的这个属性值是否和这个字段里面的值匹配  匹配到就过滤
        queryBuilder.must(QueryBuilders.matchQuery("deviceId", deviceId));

        //开始时间,继续放入搜索
        if (deviceQuery.getStartDate() != null) {
            queryBuilder.must(QueryBuilders.rangeQuery("createdDate").gte(deviceQuery.getStartDate()));
        }
        //结束时间
        if (deviceQuery.getEndDate() != null) {
            queryBuilder.must(QueryBuilders.rangeQuery("createdDate").lte(deviceQuery.getEndDate()));
        }

        //本地查询方法
        SearchQuery searchQuery = new NativeSearchQueryBuilder()
            //将上述查询条件加入
            .withQuery(queryBuilder)
            //聚合总数
            .addAggregation(AggregationBuilders.sum("amount").field("amount"))
            .addAggregation(AggregationBuilders.cardinality("person").field("accountId"))
            .build();
        //之后获得分组后的对象
        AggregatedPage<ConsumeRecordDoc> terms = elasticsearchTemplate.queryForPage(searchQuery, ConsumeRecordDoc.class);
        //之后得到Sum类
        Sum sumAmount = (InternalSum) terms.getAggregation("amount");

        //去重
        InternalCardinality terms1 = (InternalCardinality) terms.getAggregation("person");
        DeviceConsumeMetric m = new DeviceConsumeMetric();
        m.setAmount(BigDecimal.valueOf(sumAmount.getValue()));
        m.setUserCount(Math.toIntExact(terms1.getValue()));
        m.setCount(Math.toIntExact(terms.getTotalElements()));
        return m;
    }

3.5 提高阈值防止数据没有全部查到

    public Page<DeviceConsumeInfo> getConsumeUserCountInfo(DeviceQuery deviceQuery, Pageable pageable) {
        int size = pageable.getPageSize() * ((pageable.getPageNumber()) + 1);
        int shard_size = (int) (size * 1.5) + 10;
        SearchQuery query = new NativeSearchQueryBuilder()
            .withQuery(getFilterdDevice(deviceQuery))
            .addAggregation(AggregationBuilders.terms("deviceCount").size(size).shardSize(shard_size).field("deviceId")
                .subAggregation(AggregationBuilders.cardinality("userCount").field("accountId").precisionThreshold(40000))
                .size(Integer.MAX_VALUE)
            )
            .withPageable(pageable).withTrackScores(true)
            .build();
        AggregatedPage<ConsumeRecordDoc> page = elasticsearchTemplate.queryForPage(query, ConsumeRecordDoc.class);
        Terms terms = (Terms) page.getAggregation("deviceCount");
        long total = terms.getBuckets().size();
        List<DeviceConsumeInfo> ret = terms.getBuckets().stream()
            .skip(pageable.getPageSize() * pageable.getPageNumber())
            .limit(pageable.getPageSize())
            .map(x -> {
                DeviceConsumeInfo info = new DeviceConsumeInfo();
                long devId = (long) x.getKeyAsNumber();
                InternalCardinality cardinality = x.getAggregations().get("userCount");
                long userCount = cardinality.getValue();
                info.setUserCount(userCount);
                info.setDeviceId(devId);
                return info;
            })
            .collect(Collectors.toList());
        return new PageImpl(ret, pageable, total);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赵广陆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值