title: Elasticsearch, Tire, and Nested queries / associations with ActiveRecord
body: <p>I'm using ElasticSearch with Tire to index and search some ActiveRecord models, and I've been searching for the "right" way to index and search associations. I haven't found what seems like a best practice for this, so I wanted to ask if anyone has an approach that they think works really well.</p>
  
  <p>As an example setup (this is made up but illustrates the problem), let's say we have a book, with chapters. Each book has a title and author, and a bunch of chapters. Each chapter has text. We want to index the book's fields and the chapters' text so you can search for a book by author, or for any book with certain words in it.</p>
  
  <pre><code>class Book &lt; ActiveRecord::Base
    include Tire::Model::Search
    include Tire::Model::Callbacks
  
    has_many :chapters
  
    mapping do
      indexes :title, :analyzer =&gt; 'snowball', :boost =&gt; 100
      indexes :author, :analyzer =&gt; 'snowball'
      indexes :chapters, type: 'object', properties: {
        chapter_text: { type: 'string', analyzer: 'snowball' }
      }
    end
  end
  
  class Chapter &lt; ActiveRecord::Base
    belongs_to :book
  end
  </code></pre>
  
  <p>So then I do the search with:</p>
  
  <pre><code>s = Book.search do
    query { string query_string }
  end
  </code></pre>
  
  <p>That doesn't work, even though it seems like that indexing should do it. If instead I index:</p>
  
  <pre><code>indexes :chapters, :as =&gt; 'chapters.map{|c| c.chapter_text}.join('|'), :analyzer =&gt; 'snowball'
  </code></pre>
  
  <p>That makes the text searchable, but obviously it's not a nice hack and it loses the actual associated object. I've tried variations of the searching, like:</p>
  
  <pre><code>s = Book.search do
    query do
      boolean do
        should { string query_string }
        should { string "chapters.chapter_text:#{query_string}" }
      end
    end
  end
  </code></pre>
  
  <p>With no luck there, either. If anyone has a good, clear example of indexing and searching associated ActiveRecord objects using Tire, it seems like that would be a really good addition to the knowledge base here.</p>
  
  <p>Thanks for any ideas and contributions.</p>