How to retrieve the ratings/number of categories with Tire/ElasticSearch?

Tag: elasticsearch , tire Author: bothcn008 Date: 2013-04-19

I am trying to retrieve the nested data from an ElasticSearch query, basically trying to get from a Movie model:

title
ratings
categories

Now, I tried 2 Tire setups, but both only give back movie titles, not the ratings or categories. E.g. the indexes seems to be only:

curl -X POST "http://localhost:9200/movies/_search?pretty=true" -d '
 {
    "query" : { "query_string" : {"query" : "t*"} },
    "facets" : {
      "categories" : { "terms" : {"field" : "categories"} }
    }
  }
'
{
  "took" : 16,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 3,
    "max_score" : 1.0,
    "hits" : [ {
      "_index" : "movies",
      "_type" : "movie",
      "_id" : "13",
      "_score" : 1.0, "_source" : {"description":null,"id":13,"title":"Tiny Plastic Men"}
    }, {
      "_index" : "movies",
      "_type" : "movie",
      "_id" : "32",
      "_score" : 1.0, "_source" : {"description":null,"id":32,"title":"The Extreme Truth"}
    }, {
      "_index" : "movies",
      "_type" : "movie",
      "_id" : "39",
      "_score" : 1.0, "_source" : {"description":null,"id":39,"title":"A Time of Day"}
    } ]
  },
  "facets" : {
    "categories" : {
      "_type" : "terms",
      "missing" : 3,
      "total" : 0,
      "other" : 0,
      "terms" : [ ]
    }
  }

This is my movie model:

class Movie  :categorizations
  belongs_to :user

  has_many :ratings

  mapping do
     indexes :id, type: 'integer'
     indexes :title, boost: 40
     indexes :description, analyzer: 'snowball'
     indexes :categories do
       indexes :id, type: 'integer'
       indexes :name, type: 'string', index: 'not_analyzed'
     end
     indexes :ratings do
       indexes :id, type: 'integer'
       indexes :stars, type: 'integer'
     end
   end

end

The branch for my search experiment is here: https://github.com/mulderp/moviedb/tree/categories

How could I make the facets for a search working e.g. Genres --> Ratings.

Best Answer

You're not actually indexing the categories or ratings: they're in the mapping but tire's default implementation of to_indexed_json just calls the to_json method provided by activerecord.

You need to override that to include the category/rating info, for example

def to_indexed_json
  to_json(:include => [:categories, :ratings])
end