轮胎(弹性搜索)零比较

时间:2012-09-10 17:00:48

标签: ruby-on-rails ruby ruby-on-rails-3 elasticsearch tire

对于Tire(ElasticSearch包装器gem),如何查询和筛选出对于某个属性具有nil / null值的索引记录。例如,如果我有这种关系

class Article < ActiveRecord::Base
  belongs_to :topic
end

我的文章已编入索引,但我想避免使用 topic_id = nil 撤回记录。我尝试了这个代码,但它没有用。

class Article
  belongs_to :topic

  def search(q)
    tire.search do
       ...
         filter :missing, :field => :topic_id, { :existence => false, :null_value => false }
         ...
         ### filter :range, :topic_id => { :gt => 0 } # ==> I tried this as well but didn't work
       ...
    end
  end
end

3 个答案:

答案 0 :(得分:2)

如果您只想过滤具有现有topic_id值的文档,我认为您应该使用exists filter

class Article
  belongs_to :topic

  def search(q)
     tire.search do
       ...
       filter :exists, :field => :topic_id
       ...
    end
  end
end

或者您可以query string使用_exists_:topic_id查询。

答案 1 :(得分:1)

请尝试:

class Article
  belongs_to :topic

  def search(q)
    tire.search do
         ...
         filter :not, :missing => {:field => :topic_id, { :null_value => true } }
         ...
    end
  end
end

这应该有效。如果要检查字段是否存在,则需要存在。我想你只需要进行null_value检查。

答案 2 :(得分:-3)

@articles = Article.where('topic_id不是?',nil)