I am using tire-0.4.2 to interact with elasticsearch in my rails application (uses mongodb database and mongoid for interacting with mongdb). I have a post model which has a spam document embedded in it.
post.rb
include Mongoid::Document
include Mongoid::Timestamps
..
embeds one :spam, as: :spammable
...
spam.rb
include Mongoid::Document
include Mongoid::Timestamps
embedded_in :spammable, polymorphic: true
field :needs_approval, type: Boolean, default: false
field :is_spam, type: Time
has_and_belongs_to_many :request_spam_by, :class_name => "User"
field :request_spam, type: Boolean, default: false
I want to get all the posts which have no spam document: Here is the tire query
Post.tire.search(:load => :true, page: self.page, per_page: Post::PER_PAGE) do |pf|
pf.query{ |query| query.string self.search_text } unless search_text.blank?
pf.filter(:missing, :field => 'spam')
pf.filter(:term, :college_id => self.college.id)
pf.filter(:term, :user_id => self.user.id)
pf.filter(:missing, :field => 'spam' )
pf.filter(:terms, :user_type => self.user_type) unless self.user_type.blank?
pf.filter(:range, :created_at => {:gte => self.from_time}) unless self.from_time.blank?
pf.filter(:range, :created_at => {:lte => self.to_time}) unless self.to_time.blank?
pf.sort{|s| s.by :updated_at, self.sort_order}
end
generated elasticsearch query:
curl -X GET "http://localhost:9200/development_posts/post/_search? from=0&load=true&page=1&per_page=10&size=10&pretty=true" -d '{"sort":[{"updated_at":"desc"}],"filter":{"and":[{"missing":{"field":"spam"}},{"term":{"college_id":"4fb424a5addf32296f00013a"}},{"missing":{"field":"spam"}},{"range":{"created_at":{"gte":"2012-06-05T00:00:00+05:30"}}},{"range":{"created_at":{"lte":"2012-06-05T23:59:59+05:30"}}}]},"size":10,"from":0}'
The results of the query gives me the documents in which spam exists even though I am searching only for documents which have spam document missing. I don’t know what is the mistake I am doing. Can anybody point me in the right direction?
You can’t use the
missingon an object level only actual fields that get indexed.If there is a field that is always present in a spam object then you could set the missing filter on “spam.always_there” which isn’t quite as nice but should work
Should select documents where that field is either false or missing (if I remember correctly by default null and missing are the same thing so watch out there)