0

我在我的rails应用程序中使用轮胎0.4.2与elasticsearch交互(使用mongodb数据库和mongoid与mongdb交互)。我有一个帖子模型,其中嵌入了垃圾邮件文档。

post.rb

include Mongoid::Document
include Mongoid::Timestamps 

..
embeds one :spam, as: :spammable
...

垃圾邮件.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

我想获取所有没有垃圾邮件文档的帖子:这是轮胎查询

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

生成的弹性搜索查询:

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}'

查询结果为我提供了存在垃圾邮件的文档,即使我只搜索缺少垃圾邮件文档的文档。我不知道我在做什么错误。谁能指出我正确的方向?

4

1 回答 1

4

您不能missing仅在对象级别上使用被索引的实际字段。

如果垃圾邮件对象中始终存在一个字段,那么您可以在“spam.always_there”上设置缺少的过滤器,这不是很好,但应该可以工作

 pf.filter(:or, [
    {:missing => { :field => 'spam.needs_approval'}},
    {:term => {'spam.needs_approval' => false}}])

应该选择该字段为假或缺失的文档(如果我没记错,默认情况下 null 和缺失是同一件事,所以要小心)

于 2012-06-05T09:05:00.000 回答