0

For Tire (ElasticSearch wrapper gem), how do you query and filter out indexed records that has nil/null value for a certain attribute. For example, if I have this relationship

class Article < ActiveRecord::Base
  belongs_to :topic
end

I have article indexed but I want to avoid pulling back records with topic_id = nil. I tried this code blow but it didn't work.

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
RubyFanatic
  • 2,241
  • 3
  • 22
  • 35

3 Answers3

2

I think you should use exists filter if you want to filter only documents with existing topic_id value.

class Article
  belongs_to :topic

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

Or you can use query string with _exists_:topic_id query.

vhyza
  • 1,030
  • 6
  • 9
1

Please try:

class Article
  belongs_to :topic

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

This should work. existence is required if you want to check if the field exists or not. I guess you just need the null_value check.

Vamsi Krishna
  • 3,742
  • 4
  • 20
  • 45
-3

@articles = Article.where('topic_id is not ?' , nil)

sagar pant
  • 377
  • 1
  • 2
  • 12