Elasticsearch通过分组获取第一个项目

时间:2016-07-05 09:16:12

标签: elasticsearch

我遇到问题,找到以下弹性搜索的最佳方法。如果我有如下数据: -

{name: "A", size: "10", "Variant": "Large"},
{name: "B", size: "8", "Variant": "Medium"},
{name: "C", size: "6", "Variant": "Small"},
{name: "D", size: "8", "Variant": "Large"},
{name: "C", size: "4", "Variant": "Small"}

我希望能够返回结果: -

{name: "A", size: "10", "Variant": "Large"},
{name: "B", size: "8", "Variant": "Medium"},
{name: "C", size: "6", "Variant": "Small"}

即。根据变体字段取第一个(TOP 1)。我认为这相当于在SQL中执行CTE和ROW_NUMBER。

谢谢:)

1 个答案:

答案 0 :(得分:1)

可能是这样的事情:

{
  "size": 0,
  "aggs": {
    "variants": {
      "terms": {
        "field": "Variant",
        "order": {
          "max_size": "desc"
        }
      },
      "aggs": {
        "top1": {
          "top_hits": {
            "size": 1,
            "sort": [{"size":{"order": "desc"}}]
          }
        },
        "max_size": {
          "max": {
            "field": "size"
          }
        }
      }
    }
  }
}