Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails elasticsearch aggregation

Somehow I can't seem to get a response containing my aggregations...

Using curl it works as expected:

HBZUMB01$ curl -XPOST "http://localhost:9200/contents/_search" -d '{
  "size": 0,
  "aggs": {
    "sport_count": {
      "value_count": {
        "field": "dwid"
      }
    }
  }
}'

I get the response:

{
  "took": 4,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 90,
    "max_score": 0.0,
    "hits": []
  },
  "aggregations": {
    "sport_count": {
      "value": 399
    }
  }
}

However using the code in rails:

query = '{
  "size": 0,
  "aggs": {
    "sport_count": {
      "value_count": {
        "field": "dwid"
      }
    }
  }
}'
@response = Content.search(query).to_json

and rendering it in the browser

respond_to do |format|
  format.html do    
  render text: "#{@response}"   
end

I get an empty response:

[  ]

How can I print my aggregations here which I got with curl?

like image 978
bnassler Avatar asked Jul 27 '14 13:07

bnassler


1 Answers

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!

like image 200
Mauricio Moraes Avatar answered Nov 15 '22 07:11

Mauricio Moraes