簡體   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