Search code examples
ruby-on-railsruby-on-rails-4elasticsearchtire

re-tire elastic search multi table/index search


I' trying to figure out what would be the best way to do a multi table search with elastic.co.

In particular, I was wondering if I could add more indexes to this search method.

Chapter.rb

def self.search(params)
      fields = [:title, :description, :content ]
      **tables** = [Chapter.index_name, Book.index_name]
      tire.search(**tables**, {load: true,page: params[:page], per_page: 5}) do
        query do
          boolean do
            must { string params[:q], default_operator: "AND" } if params[:q].present?
          end
        end

        highlight *fields, :options => { :tag => '<strong>' }
      end

The above example works without the Tables. How to make it work with the tables ?


Solution

  • If you're adding more indexes then you are moving away from it being a model-centric search. That's probably fine as I guess you'll be handling the search results differently on account of them being from different indexes.

    In which case I think you can do:

    Tire.search([Chapter.index_name, Book.index_name], 
      page: params[:page],
      ... etc ...
    ) do
      query do
        ... etc ...
      end
    end
    

    It does mean that you won't be able to do stuff like load: true because you've moved outside of knowing what model to load the results for.

    From digging around in the code (here) it looks like you might be able to specify multiple indexes even for a model-centric search. Something like:

    tire.search({
      index: [Chapter.index_name, Book.index_name],
      load: true,
      ... etc ...
    

    I haven't tried it though and I'm doubtful as to whether it will work - again because of not being able to load the results into a specific model once multiple indexes are involved.