2012-04-09 101 views
3

我有下面的代码,我试图用ElasticSearch来查询它。轮胎/ Elasticsearch搜索关联

当我做Book.search(:q =>'Foo')时它正在工作,但当我做Book.search(:author =>'Doctor')时它不起作用。在我的数据库中,我有一个名为“Barz,Foo,Doctor”的条目

我不确定在我的查询中是否应该使用术语或术语,因为我用雪球打破了名称。我尝试了术语,然后出现错误。用术语我没有得到任何结果。

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 

回答

3

你可以这样做

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

我会接受它,因为你有,以及写答案 – 2012-04-09 22:20:55

0

由于@Karmi指出enter link description here

嗨,是的,你的方法似乎是一个。几件事: *除非你想使用Lucene查询语法(boostting,ranges等),最好使用文本查询, *是的,过滤器更有效,然后查询,在你的例子中是active = true非常适合过滤器。尽管如此,请注意查询,过滤器和方面之间的相互作用。 你的词语查询的定义不正确,虽然 - 它应该是:

term :author, params[:author] 
相关问题