新手问题 Sunspot 多 model 附带条件搜索实现

xiaoTao · 2012年07月26日 · 最后由 doitian 回复于 2012年09月18日 · 2498 次阅读

我有这样一个需求:利用 sunspot 对两个 model 进行检索,并附带其中一个 model 的属性的条件,如其中一个 model 是 Topic,另一个是 Attachment,我要检索包含关键字的 Topic 和 Attachment,并且 Attachment 的 a_type = ‘Topic',下面是我的写法:

 Sunspot.search(Attachment, Topic) do |query|
      query.fulltext params[:search]
      query.with(:a_type, 'Topic') 
end

这样能够检索出含有关键字的 Attachment 而对于 Topic 也给附加了 a_type = 'Topic'条件,因此查出的结果明显不对,请问这个正确的做法应该是怎样呢?谢谢 @huacnlee@lgn21st@poshboytl

为啥没有高手回复呢,我最近也遇到类似的问题,对多个 model 进行查询的问题

  • 如果所有 Attachment 都有 a_type, 就搜索 a_type 为 nil 或者为 'Topic'

    # cannot be: query.with(:a_type, [nil, 'Topic'])
    query.any_of do |query|
        query.with(:a_type, nil)
        query.with(:a_type, 'Topic')
    end
    
    
  • 如果 Attachment 的 a_type 可能为空,就需要加上 class_name 作为条件,虽然 sunspot 内部已经 index 了 class_name, 但是我们没办法在 DSL 里用,所以定义的时候自己加下

    string(:class_name) { self.class.name }
    

    然后用 boolean 查询

    query.any_of do |query|
        query.all_of do |query|
          query.with(:class_name, 'Attachment')
          query.with(:a_type, 'Topic')
        end
        query.with(:class_name, 'Topic')
    end
    

没反应 重复提交了

没反应 重复提交了

没反应 重复提交了

需要 登录 后方可回复, 如果你还没有账号请 注册新账号