3
votes

I have the following code and i'm trying to use ElasticSearch to query it.

It is working when i do Book.search(:q=>'Foo') but it doesn't work when i do Book.search(:author=>'Doctor'). In my database I have a entry with a name like "Barz, Foo, Doctor"

I'm not sure if I should use terms or term, in my query, because i'm breaking the name using snowball. I tried with terms and then I get an error. With term I get no results.

class Author < ActiveRecord::Base
    has_many :books
end

class Book < ActiveRecord::Base
  belongs_to :author
  include Tire::Model::Search
  include Tire::Model::Callbacks
  mapping do
    indexes :title,
    indexes :description
    indexes :author,type: 'object', properties: {
         name: { type: 'multi_field',
                 fields: { name:  { type: 'string', analyzer: 'snowball' },
                           exact: { type: 'string', index: 'not_analyzed' } 
                  } 
          } }
  end

  def to_indexed_json
   to_json(:include=>{:author=>{:only=>[:name]}} )
  end

  def self.search(params = {})
    tire.search(load:true) do
      query do
       boolean do
        should { string params[:q] } if params[:q].present?
        should { term params[:author] } if params[:author].present?
       end
      end
      filter :term, :active=>true
    end
  end
end
2

2 Answers

3
votes

You can do like this

should { terms :author, [params[:author]]} if params[:author].present?

OR

should { term :author, params[:author]} if params[:author].present?

OR

should { string "author:#{params[:author]}"} if params[:author].present?
0
votes

As @Karmi stated enter link description here

Hi, yeah, your approach seems one. Couple of things: * unless you want to use Lucene query syntax (boosting, ranges, etc), it's maybe best to use the text query, * yes, filters are more performant then queries, an the active=true in your example is a good fit for filters. Beware of the interplay between queries, filters and facets, though. Your definition of the term query is incorrect, though -- it should be:

term :author, params[:author]