【发布时间】:2020-11-14 14:56:33
【问题描述】:
我面临以下基于其子文档的聚合值选择和排序父文档的问题。聚合(例如 sum)本身取决于查询字符串,即哪些子文档与聚合相关。
示例:给定文档 basket A 和 basket B,对于每个 basket document,我希望对其 fruit 的 number 字段求和如果name 字段与我的查询匹配,则为孩子,例如apples.
PUT /baskets/_doc/0
{
"name": "basket A",
"fruit": [
{
"name": "apples",
"number": 2
},
{
"name": "oranges",
"number": 3
}
]
}
PUT /baskets/_doc/1
{
"name": "basket B",
"fruit": [
{
"name": "apples",
"number": 3
},
{
"name": "apples",
"number": 3
}
]
}
映射:
PUT /baskets
{
"mappings": {
"properties": {
"name": { "type": "text" },
"fruit": {
"type": "nested",
"properties": {
"name": { "type": "text" },
"number": { "type": "long" }
}
}
}
}
}
- 用例 1:哪个篮子有(严格)超过 5 个苹果?预计只有 篮子 B
- 用例 2:按苹果数量对篮子进行排序。预计 篮 B 共有 6 个苹果,然后 篮 A 共有 2 个苹果。
如何使用 Elasticsearch (7.8.0) 查询 DSL 来实现这一点?
到目前为止,我已经尝试使用nested queries and aggregations,但没有成功。
谢谢!
编辑:添加映射
编辑:更新了数字以更好地反映问题
*编辑:为 用例 2 添加了可能的答案(请参阅@joe 的答案的 cmets):
GET /profiles/_search
{
"aggs": {
"aggs_baskets": {
"terms": {
"field": "name",
"order": {"nest > fruit_filter > fruit_sum": "desc"}
},
"aggs": {
"nest":{
"nested":{
"path": "fruit"
},
"aggs":{
"fruit_filter":{
"filter": {
"term": {"fruit.name": "apple"}
},
"aggs":{
"fruit_sum":{
"sum": {"field": "fruit.number"}
}
}
}
}
}
}
}
}
}
【问题讨论】:
-
发布您的映射(或生成的映射),您绝对可以使用嵌套查询来做到这一点。
标签: elasticsearch