首先,请注意,我必须将您对该
headline字段的映射更改为
string,因为在示例文档中,标题为,
string而不是
object。
因此,类似以下查询的查询将检索您期望的结果:
curl -XPOST "$ELASTICSEARCH_ENDPOINT/news/_search" -d '{ "size": 0, "query": { "filtered": { "filter": { "term": { "user": "John"<--- filter for user=John } } } }, "aggs": { "sources": { "terms": { "field": "source" <--- aggregate by source }, "aggs": { "latest": { "top_hits": { "size": 1, <--- only take the first... "_source": [<--- only the date and headline "headline", "timestamp" ], "sort": { "timestamp": "desc" <--- ...and only the latest hit } } } } } }}'这将产生如下内容:
{ ... "aggregations" : { "sources" : { "doc_count_error_upper_bound" : 0, "sum_other_doc_count" : 0, "buckets" : [ { "key" : "CNN", "doc_count" : 2, "latest" : { "hits" : { "total" : 2, "max_score" : null, "hits" : [ { "_index" : "news", "_type" : "news", "_id" : "AU7Sh3VDGDddn2ZNuDVl", "_score" : null, "_source":{ "headline": "More great news", "timestamp": "2015-07-28T00:08:23.000" }, "sort" : [ 1438042103000 ] } ] } } }, { "key" : "ESPN", "doc_count" : 2, "latest" : { "hits" : { "total" : 2, "max_score" : null, "hits" : [ { "_index" : "news", "_type" : "news", "_id" : "AU7Sh3VDGDddn2ZNuDVn", "_score" : null, "_source":{ "headline": "More sports news", "timestamp": "2015-07-28T00:10:35.000" }, "sort" : [ 1438042235000 ] } ] } } } ] } }}


