好的想法是十分钱一打,真正无价的是能够实现这些想法的人。

复杂嵌套查询,复杂聚合

Elasticsearch | 作者 zhengbufang | 发布于2021年06月12日 | 阅读数:1425

三个字段人员ID 时间  数量 
10001,'2021-06-01',1
10001,'2021-06-01',2 
10002,'2021-06-01',1 
10002,'2021-06-01',3
我要通过时间筛选出数量为1的记录人  且这个人没有数量2的记录(这个不受查询条件时间管控 只要这个有数量为2的就不统计该人)
这个ES语句该怎么写 
 
有一种方案  就是根据条件查询符合数量为1 的人员ID   再根据人员ID去查有没有对应数量为2的记录  如果有就在代码里面过滤
 
有想过先根据条件按人员分组  然后再分组里面过滤   但是再分组里面过滤的话  这个数量为2的记录就局限再查询条件里面了,
因为分组是通过查询条件后
 
现在卡再就是过滤数量为2的条件是不受查询条件控制的  然后又要通过这个去过滤掉根据查询条件得到数量为1的人员
 
Elasticsearch 版本6.8
 
现在想问有没有那种解决方案 
已邀请:

thewind

赞同来自: zhengbufang meowCoder123

WX20210615-144727@2x.png

 

thewind

赞同来自: meowCoder123

一、创建测试索引
 
# (1) 创建测试索引
PUT test/
{
"mappings": {
"properties": {
"id": {
"type": "keyword"
},
"date": {
"type": "date"
},
"count": {
"type": "long"
}
}
}
}


# (2) 写入测试文档
POST _bulk
{ "index" : { "_index" : "test" } }
{ "id": "10001", "date": "2021-06-01", "count": 1}
{ "index" : { "_index" : "test" } }
{ "id": "10001", "date": "2021-06-02", "count": 3}
{ "index" : { "_index" : "test" } }
{ "id": "10001", "date": "2021-06-03", "count": 2}
{ "index" : { "_index" : "test" } }
{ "id": "10002", "date": "2021-06-01", "count": 1}
{ "index" : { "_index" : "test" } }
{ "id": "10002", "date": "2021-06-02", "count": 3}
{ "index" : { "_index" : "test" } }
{ "id": "10002", "date": "2021-06-03", "count": 3}
{ "index" : { "_index" : "test" } }
{ "id": "10003", "date": "2021-06-01", "count": 1}


二、查询语句
管道聚合 bucket_selector
 
# (3) 查询语句
# a21 用于过滤条件: 时间范围过滤 和 count为1
# a22 用于过滤条件: count为2
# 最终使用 bucket_selector 管道聚合,得到结果
GET test/_search
{
"size": 0,
"aggs": {
"a1": {
"terms": {
"field": "id",
"size": 10
},
"aggs": {
"a21": {
"filter": {
"bool": {
"must": [
{
"range": {
"date": {
"gte": "2021-05-30",
"lte": "2021-06-31"
}
}
},
{
"term": {
"count": 1
}
}
]
}
},
"aggs": {
"a31": {
"sum": {
"field": "count"
}
}
}
},
"a22": {
"filter": {
"bool": {
"must": [
{
"term": {
"count": 2
}
}
]
}
},
"aggs": {
"a32": {
"sum": {
"field": "count"
}
}
}
},
"a4": {
"bucket_selector": {
"buckets_path": {
"count1": "a21>a31",
"count2": "a22>a32"
},
"script": "params.count1 > 0 && params.count2 < 1"
}
}
}
}
}
}

要回复问题请先登录注册