Elasticsearch中的求和查询

Sha*_*ler 3 nosql elasticsearch

我对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
  }
},
...
Run Code Online (Sandbox Code Playgroud)

我想在ES中运行与在SQL中相同的查询,这样我的结果就像(在json中): M05: 7103, M03: 9740

imo*_*tov 6

在elasticsearch中,您可以使用术语stats facet来实现此目的:

{
    "query" : {
        "match_all" : {  }
    },
    "facets" : {
        "lane_routes_stats" : {
            "terms_stats" : {
                "key_field" : "lane",
                "value_field" : "routes",
                "order": "term"
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)