Rails elasticsearch aggregation Rails elasticsearch aggregation elasticsearch elasticsearch

Rails elasticsearch aggregation


I was also struggling with this, but now I found out how to get the aggregation results.

If you're using the elasticsearch-rails with elasticsearch-model gems, when you run an aggregation on a model, you can get the buckets like in this example:

 agg = Model.search(      query: { match: { param: 'value' } },      aggs: {my_aggregation_name: { terms: { field: :my_field} }}  )

In your RoR code:

agg.response["aggregations"]["my_aggregation_name"]["buckets"]

From that, you'll get a result like this:

[{"key"=>"banana",  "doc_count"=>1963,  "score"=>478.30920868573355,  "bg_count"=>2152}, {"key"=>"potato",  "doc_count"=>1212,  "score"=>315.68857496078505,  "bg_count"=>1243}, ...]

Then you can do whatever you want! Hope that helps!