3

I'm fairly new to Elasticsearch. I'm trying to write a query that will group by a field and calculate a sum. In SQL, my query would look like this: SELECT lane, SUM(routes) FROM lanes GROUP BY lane

I have this data that looks like this in 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
  }
},
...

I want to essentially run the same query in ES as I did in SQL, so that my result would be something like (in json of course): M05: 7103, M03: 9740

1 Answer 1

6

In elasticsearch, you can achieve this by using terms stats facet:

{
    "query" : {
        "match_all" : {  }
    },
    "facets" : {
        "lane_routes_stats" : {
            "terms_stats" : {
                "key_field" : "lane",
                "value_field" : "routes",
                "order": "term"
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks imotov. How do I sort the stat results? I'd like to sort by lane field, which is facets.lane_routes_stats.terms.term
All sort options are described in the documentation that I linked in my answer. I have also updated the answer with an example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.