gpt4 book ai didi

elasticsearch - Elasticsearch查询聚合

转载 作者:行者123 更新时间:2023-12-03 00:50:26 25 4
gpt4 key购买 nike

我在创建带有聚合的elastisearch查询时遇到问题。

这是我的数据:

user |rank|comment
-----------------
john |1 |too bad
john |2 |almost
john |3 |well done
james|8 |awesome
james|3 |poor

我对每个用户的最高排名以及相应的评论感兴趣,如下所示:
user |rank|comment
-----------------
john |3 |well done
james|8 |awesome

这是我的 flex 数据的代码:
PUT /myindex/_doc/1
{
"user" : "john",
"rank" : 1,
"comment" : "too bad"
}

PUT /myindex/_doc/2
{
"user" : "john",
"rank" : 2,
"comment" : "almost"
}

PUT /myindex/_doc/3
{
"user" : "john",
"rank" : 3,
"comment" : "well done"
}

PUT /myindex/_doc/4
{
"user" : "james",
"rank" : 8,
"comment": "awesome"
}

PUT /myindex/_doc/5
{
"user" : "james",
"rank" : 3,
"comment": "poor"
}

这是我的汇总查询:
GET  /myindex/_doc/_search
{
"size":0,
"aggs": {
"by": {
"terms": {
"field": "user.keyword"
},
"aggs": {
"maxrank": {
"max": {
"field": "rank"
}
}
}
}
}
}

它给了我这个:
  {
"took": 1,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 5,
"max_score": 0,
"hits": []
},
"aggregations": {
"by": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "john",
"doc_count": 3,
"maxrank": {
"value": 3
}
},
{
"key": "james",
"doc_count": 2,
"maxrank": {
"value": 8
}
}
]
}
}
}

这样看起来不错,但是如何将相应的注释字段放入查询结果中呢?如果我使用的是SQL数据库,则将创建聚合部分作为子查询,并将其连接到基表。如何在Elasticsearch上实现这一目标?

最佳答案

与其在等级上使用最大度量聚合,不如使用top_hits这样的代码:

GET  /myindex/_doc/_search
{
"size":0,
"aggs": {
"by": {
"terms": {
"field": "user.keyword"
},
"aggs": {
"maxrank": {
"top_hits": {
"_source": ["rank", "comment"],
"sort": {"rank": "desc"},
"size": 1
}
}
}
}
}
}

关于elasticsearch - Elasticsearch查询聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54554147/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com