繁体   English   中英

Elasticsearch查询聚合

[英]Elasticsearch query aggregation

我在创建带有聚合的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

这是我的弹性数据的代码:

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使用top_hits这样的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
          }
        }
      }
    }
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM