Search code examples
elasticsearchgroup-byelasticsearch-aggregationelastic4s

Elasticsearch aggregation group by using elastic4s


I want to query total sum of sales grouped by product name in Elasticsearch

How do I do that using elastic4s?

client.execute {
      search ("sales"/ "sales_type")
        .query {rangeQuery("date") gte "01-01-2018"   lte "31-12-2018" }
          .aggs { termsAgg("s1","product_name")}
             .aggs  (sumAgg("sums","total_sum"))
}

currently my code just sums up all in given date range, not grouping by product name


Solution

  • You've probably found an answer by now anyway, but here's my 2p worth for anyone else who comes across this.... you probably want to use a sub-aggregation on product_name rather than a second aggregation on the whole dataset.

    Something like this (untested code, but based on a working part of one of my projects):

    .query {rangeQuery("date") gte "01-01-2018"   lte "31-12-2018" }
      .aggs { termsAgg("s1","product_name").subAggregations(
                 sumAgg("sums","total_sum")
              )
            }
    

    The results come back as a bunch of nested Map[String,Any] which take a bit of sorting through, but some logging/print statements and a bit of trial and error sorted it out for me.

    Reference is here: https://github.com/guardian/archivehunter/blob/47372d55d458cfe31e5d9809910cc5d9a4bbb9bf/app/controllers/SearchController.scala#L203, in that case I am processing it down for rendering in a browser frontend with ChartJS.

    Apologies for brevity, but I'm on the hop at the moment and haven't got long to post :)