![](/img/trans.png)
[英](Elasticsearch) How to get the last element of a nested field of all documents then perform sub-aggregations
[英]ElasticSearch, how to order aggregations by other field?
我有一个问答项目,并且我想在名为Feed的部分中实现Elasticsearch。
本部分是最后一种活动供稿。
这是供稿表:
id | question_id | user_id | action_type | date_added
---------------------------------------------------------------
26 | 29 | 32 | new_answer | 2017-04-22 18:34:56
36 | 38 | 35 | new_answer | 2017-04-24 19:42:40
5 | 52 | 25 | new_question | 2017-04-03 16:28:43
2 | 52 | 20 | new_answer | 2017-05-05 13:22:41
因此,使用Elasticsearch时,我将无法获得按Question_id分组的数据以及按ID DESC排序的数据。
所以我这样做:
{
"size": 0,
"query": {
"match_all": {}
},
"aggs": {
"questions": {
"terms": {
"field": "question.id",
"order": {
"_term": "desc"
}
}
}
}
}
我得到这个结果:
{
"took" : 2,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"failed" : 0
},
"hits" : {
"total" : 41,
"max_score" : 0.0,
"hits" : [ ]
},
"aggregations" : {
"questions" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 10,
"buckets" : [ {
"key" : "64",
"doc_count" : 4
}, {
"key" : "63",
"doc_count" : 5
}, {
"key" : "62",
"doc_count" : 4
}, {
"key" : "61",
"doc_count" : 5
}, {
"key" : "60",
"doc_count" : 1
}, {
"key" : "59",
"doc_count" : 1
}, {
"key" : "58",
"doc_count" : 3
}, {
"key" : "57",
"doc_count" : 3
}, {
"key" : "56",
"doc_count" : 3
}, {
"key" : "55",
"doc_count" : 2
} ]
}
}
}
我该怎么做才能按id
或date_added
排序questions
?
谢谢
您可以让您的文档分成由水桶question_id
和每个桶中的排序id
或date_added
使用排名靠前的子聚集。
这是一个基于您的聚合的示例,并按照id
降序对每个存储桶中的文档进行排序:
{
"size": 0,
"aggs": {
"questions": {
"terms": {
"field": "question_id",
"order": {
"_term": "desc"
}
},
"aggs": {
"question_docs": {
"top_hits": {
"size": 10,
"sort": [
{
"id": {
"order": "desc"
}
}
]
}
}
}
}
}
}
假设您为date_added
的映射指定了date
字段数据类型,那么您也可以在top_hits
聚合中用date_added
代替id
。 如果让Elasticsearch为您确定映射,则日期可能存储为text
(对于Elasticsearch 5.x)或string
(在5.x之前的任何东西)。 我使用带有动态映射的Elasticsearch 5.4为您的问题中的样本数据建立了索引; 它将日期的映射设置为text
(用于全文搜索,使用date_added
访问)和keyword
(用于排序和聚合,使用date_added.keyword
访问)。
您可以使用get mapping API查看索引的映射。 例如,要查看索引<index_name>
的映射,请使用以下命令:
curl -XGET "http://localhost:9200/<index_name>/_mapping"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.