[英](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.