官方学习文档:
https://www.elastic.co/guide/en/elasticsearch/reference/6.8/index.html
1、es 7.X后,统计真实的所有数量,需要加上一个参数,"track_total_hits": true
{
"track_total_hits": true,
"query": {
"match_all": {}
}
}
2、AND、OR、NOT、exists、_missing_等关键字在query_string中的用法;
AND:表示条件与;
OR:表示条件或;
NOT:表示条件非;
_exists_:表示存在,且是存在对应字段;
_missing_:表示不存在或为空,此处为空建议用_exists_取非;
示例,如下DSL含义为:
查询 key_name_1 字段值为 value1,存在key_name_2字段,且key_time范围为time1到time2的所有数据,再按照时间字段key_time2及key_name_2字段进行分组;其中将时间字段key_time2格式化为yyyy-MM-dd HH的格式,"min_doc_count": 1,过滤分组结果大于等一1的数据
{
"size": 0,
"query": {
"query_string": {
"query": "key_name_1:value1 AND _exists_:key_name_2 AND key_time:[\"time1\" TO \"time2\"]"
}
},
"aggs": {
"group_by_time1": {
"date_histogram": {
"field": "key_time2",
"interval": "day",
"time_zone": "Asia/Shanghai",
"format": "yyyy-MM-dd HH",
"min_doc_count": 0
},
"aggs": {
"group_by_key_name_2": {
"terms": {
"field": "key_name_2"
}
}
}
}
}
}
3、having 用法,过滤分组结果
{
"size": 0,
"query": {
"query_string": {
"query": "key_name_1:value1"
}
},
"aggs": {
"group_key_name_2": {
"terms": {
"field": "key_name_2",
"size": 1000
},
"aggs": {
"having": {
"bucket_selector": {
"buckets_path": {
"view_count": "_count"
},
"script": "params.view_count >1"
}
}
}
}
}
}
4、cardinality 关键词,分组去重
{
"aggs": {
"group_by_key_name_1": {
"cardinality": {
"field": "key_name_1",
"size": 100
}
}
}
}
5、order的用法,可用于分组后再按内层结果排序
{
"aggs": {
"group_by_key_name_1": {
"terms": {
"field": "key_name_1",
"size": 100,
"order": {
"dist_key_name_2": "desc"
}
},
"aggs": {
"dist_key_name_2": {
"cardinality": {
"field": "key_name_2"
}
}
}
}
}
}
6、日期date存储为long类型时可以进行格式化
可用的时间间隔表达式有:
year-1y:表示1年;
quarter-1q:表示1季度;
month-1M:表示1个月;
week-1w:表示1星期;
day-1d:表示1天;
hour-1h:表示1小时;
minute-1m:表示1分钟;
second-1s:表示1秒;
用法示例:1.5h可以用分钟表示为90m;
时间格式:yyyy-MM-dd HH:mm:ss 其中大写的HH代表24小时制
用法示例:
{
"aggs": {
"group_by_time": {
"date_histogram": {
"field": "key_time",
"interval": "hour",
"time_zone": "Asia/Shanghai",
"format": "yyyy-MM-dd HH",
"min_doc_count": 0,
"extended_bounds": {
"min": "2020-12-06 00",
"max": "2020-12-06 23"
}
}
}
}
}