Top Hits Aggregation
需求: 对每个用户发表的博客进行分组
造数据
PUT /blogs/_doc/2 { "title":"learn words", "content":"learning elasticsearch", "userInfo":{ "userId":2, "username":"jack" } } PUT /blogs/_doc/3 { "title":"learn hello", "content":"learning hello", "userInfo":{ "userId":3, "username":"jim" } } PUT /blogs/_doc/4 { "title":"learn lucy", "content":"learning chinese", "userInfo":{ "userId":5, "username":"lucy" } } PUT /blogs/_doc/5 { "title":"learn two", "content":"learning english", "userInfo":{ "userId":5, "username":"two" } } PUT /blogs/_doc/6 { "title":"learn six", "content":"learning six", "userInfo":{ "userId":5, "username":"six" } }
#对每个用户发表的博客进行分组,取前5篇的标题
GET /blogs/_search { "size":0, "aggs":{ "group_by_userName":{ "terms":{ "field":"userInfo.username.keyword" }, "aggs":{ "top_blog":{ "top_hits":{ "_source":{ "includes":"title" }, "size":5 } } } } } }
结果
{ "took" : 789, "timed_out" : false, "_shards" : { "total" : 1, "successful" : 1, "skipped" : 0, "failed" : 0 }, "hits" : { "total" : { "value" : 6, "relation" : "eq" }, "max_score" : null, "hits" : [ ] }, "aggregations" : { "group_by_userName" : { "doc_count_error_upper_bound" : 0, "sum_other_doc_count" : 0, "buckets" : [ { "key" : "jack", "doc_count" : 1, "top_blog" : { "hits" : { "total" : { "value" : 1, "relation" : "eq" }, "max_score" : 1.0, "hits" : [ { "_index" : "blogs", "_type" : "_doc", "_id" : "2", "_score" : 1.0, "_source" : { "title" : "learn words" } } ] } } }, { "key" : "jim", "doc_count" : 1, "top_blog" : { "hits" : { "total" : { "value" : 1, "relation" : "eq" }, "max_score" : 1.0, "hits" : [ { "_index" : "blogs", "_type" : "_doc", "_id" : "3", "_score" : 1.0, "_source" : { "title" : "learn hello" } } ] } } }, { "key" : "lucy", "doc_count" : 1, "top_blog" : { "hits" : { "total" : { "value" : 1, "relation" : "eq" }, "max_score" : 1.0, "hits" : [ { "_index" : "blogs", "_type" : "_doc", "_id" : "4", "_score" : 1.0, "_source" : { "title" : "learn lucy" } } ] } } }, { "key" : "six", "doc_count" : 1, "top_blog" : { "hits" : { "total" : { "value" : 1, "relation" : "eq" }, "max_score" : 1.0, "hits" : [ { "_index" : "blogs", "_type" : "_doc", "_id" : "6", "_score" : 1.0, "_source" : { "title" : "learn six" } } ] } } }, { "key" : "two", "doc_count" : 1, "top_blog" : { "hits" : { "total" : { "value" : 1, "relation" : "eq" }, "max_score" : 1.0, "hits" : [ { "_index" : "blogs", "_type" : "_doc", "_id" : "5", "_score" : 1.0, "_source" : { "title" : "learn two" } } ] } } }, { "key" : "夏明", "doc_count" : 1, "top_blog" : { "hits" : { "total" : { "value" : 1, "relation" : "eq" }, "max_score" : 1.0, "hits" : [ { "_index" : "blogs", "_type" : "_doc", "_id" : "1", "_score" : 1.0, "_source" : { "title" : "盛夏的果实" } } ] } } } ] } } }
立志如山 静心求实
浙公网安备 33010602011771号