Bool 查询
例子1:根据2个字段分组,并查询分组后的某个字段的sum总数
类似mysql : Select A,B from 表名 group by A,B
就是在 query 里写的 bool,用于复合的查询,里面的 must ,起到过滤的作用,在 agg 前,先对数据进行筛选。
aggs:用于聚合。
下面是一个微信聊天记录的例子:from_user 发送者, kind 发送的消息类似 seq消息序列号 ,分组的字段如果是字符串要用 keyword类型, 数字就不用
这里第一层 agg1,是对 doc 按照kind 进行分组。
第二层 agg2,接着是对 content 分组。
最里面的 sum_seq 就是先按 kind分组,后按 content 分组 统计的seq累加值。 这里计算sum的字段也可以换成其他字段
GET wechat_letter_alias/_search { "query": { "bool": { "must": [ { "term": { "from_user.keyword": "wmnvpANwAAwBcm0HdLElG-Iv77-teq8Q" } } ] } }, "aggs": { "agg1": { "terms": { "field": "kind.keyword", "size": 10000, "order": { "_key": "asc" } }, "aggs": { "agg2": { "terms": { "field": "content.keyword", "size": 10000, "order": { "_key": "asc" } }, "aggs": { "sum_seq": { "sum": { "field": "seq" } } } } } } }, "from": 0, "size": 0 }
例子2:top_hits 查询里面最大的一条记录的详细信息
GET wechat_letter_alias/_search { "query": { "bool": { "must": [ { "term": { "from_user.keyword": "wmnvpANwAAwBcm0HdLElG-Iv77-teq8Q" } } ] } }, "aggs": { "agg1": { "terms": { "field": "kind.keyword", "size": 10000, "order": { "_key": "asc" } }, "aggs": { "agg2": { "terms": { "field": "content.keyword", "size": 10000, "order": { "_key": "asc" } }, "aggs": { "select_fields": { "top_hits": { "size": 1, "_source": { "includes": [ "id", "from_user", "content" ] } } } } } } } }, "from": 0, "size": 0 }
方法二
另外分组还有一种方法是通过 script 脚本,减少嵌套的层级,可以更改返回的数据,让查询出来的结果和 MySQL 很像:
这里是对 kind和 seq 进行聚合,text类型不支持,必须是keyword类型
GET wechat_letter_alias/_search { "query": { "bool": { "must": [ { "term": { "from_user.keyword": "wmnvpANwAAwBcm0HdLElG-Iv77-teq8Q" } } ] } }, "aggs": { "agg1": { "terms": { "script": { "source": "doc['kind.keyword'].value + '-split-'+doc['seq'].value" } } } }, "from": 0, "size": 0 }
《本文》有 0 条评论