如何在弹性搜索中将bucket关键字排序为整数



我有一个按bucket键排序的问题。

如何按整数对bucket密钥进行排序?

这是我的疑问。

{
"aggregations": {
"by_time": {
"terms": {
"script": {
"source": "Instant.ofEpochMilli(doc['statdate'].date.millis).atZone(ZoneId.of(params.tz)).hour",
"lang": "painless",
"params": {
"tz": "Asia/Seoul"
}
},
"size": 10,
"min_doc_count": 0,
"shard_min_doc_count": 0,
"show_term_doc_count_error": false,
"order": {
"_key": "asc"
}
}
}
}

以及结果。

{
"aggregations": {
"sterms#by_time": {
"buckets": [
{
"key": "11",
"doc_count": 1
},
{
"key": "19",
"doc_count": 1
},
{
"key": "22",
"doc_count": 1
}
},
{
"key": "7",
"doc_count": 1
},
{
"key": "9",
"doc_count": 7
}
]
}
}

但我不想要这样的结果。

我认为这个键类型是字符串。

如何按整数键排序?

您需要使用作为父管道的bucket排序聚合对其父多存储桶的存储桶进行排序的聚合聚合。零个或多个排序字段可以与一起指定相应的排序顺序。每个bucket可以根据其_key、_count或其子聚合。

试试这个搜索查询:

{
"aggregations": {
"by_time": {
"terms": {
"script": {
"source": "Instant.ofEpochMilli(doc['statdate'].date.millis).atZone(ZoneId.of(params.tz)).hour",
"lang": "painless",
"params": {
"tz": "Asia/Seoul"
}
},
"size": 20,            <-- note this
"min_doc_count": 0,
"shard_min_doc_count": 0,
"show_term_doc_count_error": false,
"order": {
"_key": "asc"
}
},
"aggs": {
"bucket_truncate": {
"bucket_sort": {            <-- note this
"sort": [
{
"_key": {
"order": "asc"
}
}
],
"size": 20         <-- note this  
}
}
}
}
}
}

添加一个具有索引数据、搜索查询和搜索结果的工作示例

指数数据:

{
"id":"1",
"title":"a"
}
{
"id":"3",
"title":"c"
}
{
"id":"2",
"title":"b"
}
{
"id":"2",
"title":"c"
}

搜索查询:

{
"size": 0,
"aggs": {
"unique_id": {
"terms": {
"field": "id.keyword"
},
"aggs": {
"bucket_truncate": {
"bucket_sort": {
"sort": [
{
"_key": {
"order": "asc"
}
}
]
}
}
}
}
}
}

搜索结果:

"aggregations": {
"unique_id": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "1",
"doc_count": 1
},
{
"key": "2",
"doc_count": 2
},
{
"key": "3",
"doc_count": 1
}
]
}
}

最新更新