我试图对elasticsearch聚合的结果桶进行排序。我有一大套文件:
"mappings": {
"properties": {
"price": {
"type": "double"
},
"product_name": {
"type": "text"
},
"product_id": {
"type": "keyword"
},
"timestamp": {
"type": "date"
}
}
}我目前正在做的是使用composite和top_hits聚合为每个top_hits获得最新的销售:
{
"query": {
"bool": {
"filter": [
{
"range": {
"timestamp": {
"gte": "2019-10-25T00:00:00Z",
"lte": "2019-10-26T00:00:00Z"
}
}
}
]
}
},
"aggs": {
"distinct_products": {
"composite": {
"sources": [
{
"distinct_ids": {
"terms": {
"field": "product_id"
}
}
}
],
"size": 10000
},
"aggs": {
"last_timestamp": {
"top_hits": {
"sort": {
"timestamp": {
"order": "desc"
}
},
"size": 1
}
}
}
}
}
}现在,我想按任意字段对产生的桶进行排序。如果我想按price进行排序,可以在this question中使用解决方案,方法是添加一个从每个桶中提取product_price字段的max聚合,并在最后添加一个bucket_sort聚合,以对max的结果进行排序。
{
"query": {
"bool": {
"filter": [
{
"range": {
"timestamp": {
"gte": "2019-10-25T00:00:00Z",
"lte": "2019-10-26T00:00:00Z"
}
}
}
]
}
},
"aggs": {
"distinct_products": {
"composite": {
"sources": [
{
"distinct_ids": {
"terms": {
"field": "product_id"
}
}
}
],
"size": 10000
},
"aggs": {
"last_timestamp": {
"top_hits": {
"sort": {
"timestamp": {
"order": "desc"
}
},
"size": 1,
"_source": {
"excludes": []
}
}
},
"latest_sell": {
"max": {
"field": "product_price"
}
},
"latest_sell_secondary": {
"max": {
"field": "timestamp"
}
},
"sort_sells": {
"bucket_sort": {
"sort": {
"latest_sell": {
"order": "desc"
},
"latest_sell_secondary": {
"order": "desc"
}
},
"from": 0,
"size": 10000
}
}
}
}
}
}如果我想按product_name而不是product_price按字母顺序排序,则不能使用max聚合,因为它只适用于数字字段。
last_timestamp 存储桶(每个只有一个文档)如何按照文本字段排序?
我使用的elasticsearch版本是7.2.0。
发布于 2019-10-26 10:51:26
从医生那里
每个桶可以根据其_key、_count或其子聚合进行排序。
而不是产品Id,您可以在术语、聚合和键排序方面使用product_name.keyword
"order": { "_key" : "asc" }https://stackoverflow.com/questions/58557040
复制相似问题