Elasticsearch, Tire, and Nested fields with ActiveRecord

Tag: activerecord , elasticsearch , tire Author: zjy558899 Date: 2013-01-02

Please read this answer to a similar question I have below Elasticsearch, Tire, and Nested queries/associations with ActiveRecord

Lets say I added the following field the the Book model provided in the question above:

field :account_tags, type: Array # [{:account_id => 1, :tags => ["tag1", "tag2"], :acccount_id => 2, :tags => ["tag3", "tag4"] }]

I now would like to set up an index to seach these account_ids or tags.

How would I do so?

Best Answer

I have solved this problem and was straight forward. My mapping looks like

mapping do 
  indexes :account_tags do
    indexes :account_id, :index => "not_analyzed"
    indexes :tags, :type => 'string', :analyzer => 'keyword'

My to_indexed_json looks like

def to_indexed_json
    account_tags: account_tags

Now I can search via

@query = "account_id:#{account_id}"
@tags = tags

Book.tire.search :load => true do |search|
  search.query do |query|
    query.string @query

  search.filter :terms, :tags => @tags

This is a bare boned solution that I used to prototype a system.