ES查询总结

mac2024-12-06  25

1 按时间聚合

{ "size": 0, "aggs": { "groupDate": { "date_histogram": { "field": "create_date", "interval": "day", "format": "yyyy-MM-dd" } } } }

2 聚合出现

"error": { "root_cause": [ { "type": "illegal_argument_exception", "reason": "Fielddata is disabled on text fields by default. Set fielddata=true on [member_id] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory. Alternatively use a keyword field instead." } ],

解决方案

1 字段加上关键字keyword(推荐),代码如下:

GET /megacorp/employee/_search { "query": { "match": { "last_name": "Smith" } }, "aggs": { "all_members": { "terms": { "field": "member_id.keyword" } } } }

2 在聚合前发送指令开启fielddata,指令如下:

PUT megacorp/_mapping/employee/ { "properties": { "member_id": { "type": "text", "fielddata": true } }

3 统计去重后的数量(分类的数量,key的个数)

GET /cars/transactions/_search { "size" : 0, "aggs" : { "months" : { "date_histogram": { "field": "sold", "interval": "month" }, "aggs": { "distinct_colors" : { "cardinality" : { "field" : "color" } } } } } }

4 多字段分组

{ "size": 0, "query": { "bool": { "filter": [ { "range": { "updated_at": { "gte": "2019-02-10T00:00:00+08:00", "lte": "2020-02-11T23:59:59+08:00" } } } ] } }, "aggs": { "member_id": { "terms": { "field": "member_id.keyword", "size": 100 }, "aggs": { "groupDate": { "date_histogram": { "field": "updated_at", "interval": "day", "format": "yyyy-MM-dd" } } } } } }

5 多字段二次分组

{ "size": 0, "query": { "bool": { "filter": [ { "range": { "updated_at": { "gte": "2019-02-10T00:00:00+08:00", "lte": "2020-02-11T23:59:59+08:00" } } } ] } }, "aggs": { "member_id": { "terms": { "field": "member_id.keyword" }, "aggs": { "groupDate": { "date_histogram": { "field": "updated_at", "interval": "day", "format": "yyyy-MM-dd" } } } } } }

 

最新回复(0)