searching multiple polymorphic items using thinking sphinx

最后都变了- 提交于 2020-01-05 02:35:26

问题


I have an attachments table that has multiple values (via polymorphic assoc). I'd like to be able to search for multiple values (like an AND in SQL) via thinking-sphinx.

For example:

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

My FieldValue model has one field (value), so using the above index definition, I could do something like:

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

But this doesn't technically do what I'm hoping for. The field_values should match the field_ids (similar to a select * from attachments where (field_value.id = 23 and field_value.value like '*5100*) and (field_value.id = 23 and field_value.value = '1')

(i know there are joins missing above :P)

Is it possible to do a search similar to this?


回答1:


Sphinx has no concept of key/value pairs, so you can't ask it to match values and field_ids on given field_values.

If you wanted to search on attachments matching a single value/id pair, a possible way around this would be to search on FieldValue instead, and group by 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

The grouping will ensure you only get one match per Attachment.

However, this is no help matching multiple value/id pairs for an attachment, I'm afraid. I can't think of a way to do that with Sphinx off the top of my head.




回答2:


This can be done in several steps.

  1. You'll need to reference FieldValue's ids in the Attachment index:

    has field_values.id, :as => :field_values_ids

  2. Get the ids for the FieldValue pairs you need:

    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. Search for Attachments that have these pairs:

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

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

  4. Intersect the results:

    r1.to_a & r2.to_a

Caveat: you lose pagination and ordering (See Pat's answer to my question).



来源:https://stackoverflow.com/questions/8824767/searching-multiple-polymorphic-items-using-thinking-sphinx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!