3

我对 Elasticsearch 相当陌生。我正在尝试编写一个按字段分组并计算总和的查询。在 SQL 中,我的查询如下所示: SELECT lane, SUM(routes) FROM lanes GROUP BY lane

我在 ES 中有这样的数据:

{
  "_index": "kpi",
  "_type": "mroutes_by_lane",
  "_id": "TUeWFEhnS9q1Ukb2QdZABg",
  "_score": 1.0,
  "_source": {
    "warehouse_id": 107,
    "date": "2013-04-08",
    "lane": "M05",
    "routes": 4047
  }
},
{
  "_index": "kpi",
  "_type": "mroutes_by_lane",
  "_id": "owVmGW9GT562_2Alfru2DA",
  "_score": 1.0,
  "_source": {
    "warehouse_id": 107,
    "date": "2013-04-08",
    "lane": "M03",
    "routes": 4065
  }
},
{
  "_index": "kpi",
  "_type": "mroutes_by_lane",
  "_id": "JY9xNDxqSsajw76oMC2gxA",
  "_score": 1.0,
  "_source": {
    "warehouse_id": 107,
    "date": "2013-04-08",
    "lane": "M05",
    "routes": 3056
  }
},
{
  "_index": "kpi",
  "_type": "mroutes_by_lane",
  "_id": "owVmGW9GT345_2Alfru2DB",
  "_score": 1.0,
  "_source": {
    "warehouse_id": 107,
    "date": "2013-04-08",
    "lane": "M03",
    "routes": 5675
  }
},
...

我想基本上在 ES 中运行与在 SQL 中相同的查询,这样我的结果将类似于(当然在 json 中):M05: 7103, M03: 9740

4

1 回答 1

6

在 elasticsearch 中,您可以通过使用terms stats facet来实现:

{
    "query" : {
        "match_all" : {  }
    },
    "facets" : {
        "lane_routes_stats" : {
            "terms_stats" : {
                "key_field" : "lane",
                "value_field" : "routes",
                "order": "term"
            }
        }
    }
}
于 2013-04-16T22:14:53.787 回答