【问题标题】:searching multiple polymorphic items using thinking sphinx使用思维狮身人面像搜索多个多态项
【发布时间】:2012-01-11 18:38:08
【问题描述】:

我有一个包含多个值的附件表(通过多态关联)。我希望能够通过thinking-sphinx 搜索多个值(如SQL 中的AND)。

例如:

class FieldValue < ActiveRecord::Base
  belongs_to :customized, :polymorphic => true
end

class Attachment < ActiveRecord::Base
  has_many  :field_values, :as => :customized, :dependent => :destroy

  define_index do
    has field_values.field_id, :as => :field_ids, :type => :multi

    indexes field_values.value, :as => :field_values, :type => :multi

    set_property :enable_star   => 1
    set_property :min_infix_len => 3
  end
end

我的 FieldValue 模型有一个字段(值),因此使用上面的索引定义,我可以执行以下操作:

Attachment.search :conditions => { :field_values => ["*5100*", "1"] }, :with => { :field_ids => [23, 24] }

但这在技术上并没有达到我的期望。 field_values 应该与 field_ids 匹配(类似于 select * from attachments where (field_value.id = 23 and field_value.value like '*5100*) and (field_value.id = 23 and field_value.value = '1')

(我知道上面缺少连接:P)

是否可以进行类似的搜索?

【问题讨论】:

    标签: ruby-on-rails-3 thinking-sphinx polymorphic-associations


    【解决方案1】:

    Sphinx 没有键/值对的概念,因此您不能要求它匹配给定 field_values 上的值和 field_id。

    如果您想搜索匹配单个值/id 对的附件,解决此问题的一种可能方法是搜索 FieldValue,并按 customized_id 分组:

    class FieldValue < ActiveRecord::Base
      define_index do
        indexes value
        has field_id, customized_id
      end
    end
    
    FieldValue.search :conditions => {:value => '1'}, :with => {:field_id => 23},
      :group_by => 'customized_id', :group_function => :attr
    

    分组将确保每个附件只能获得一个匹配项。

    但是,恐怕这对为附件匹配多个值/ID 对没有帮助。我想不出什么办法可以让 Sphinx 脱离我的头顶。

    【讨论】:

    • 我曾经使用 FieldValue 上的索引来进行搜索,但看起来我最终得到的结果有点“黑客”,所以希望有一个“官方”的方式来做。我基本上是在尝试复制类似:```define_index 做索引:value_one 索引:value_two 索引:value_three end ``` 但由于关联是多态的,value_[one..three] 被定义为键/值(如你上面提到的)。我可以使用标准的 Attachment.search 来解决这个问题,然后单独调用 FieldValue.search 并合并结果,但这是我要避免的黑客攻击:P
    • 对不起,尝试编辑了很多次但忘记了你不能真正格式化 cmets :P
    • 能否分别得到结果并相交?看到这个问题:stackoverflow.com/questions/30305981/…
    【解决方案2】:

    这可以通过几个步骤来完成。

    1. 您需要在附件索引中引用 FieldValue 的 ID:

      has field_values.id, :as =&gt; :field_values_ids

    2. 获取您需要的 FieldValue 对的 id:

      v1 = FieldValue.search_for_ids(conditions: { value: "*5100*" }, with: { field_id: 23 })

      v2 = FieldValue.search_for_ids(conditions: { value: "1" }, with: { field_id: 24 })

    3. 搜索具有这些对的附件:

      r1 = Attachment.search(with: { field_values_ids: v1 })

      r2 = Attachment.search(with: { field_values_ids: v2 })

    4. 相交结果:

      r1.to_a &amp; r2.to_a

    警告:您失去了分页和排序(请参阅Pat's answer我的问题)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-22
      • 1970-01-01
      相关资源
      最近更新 更多