Rails 5、thinking sphinx, indexing and searching has meny through relationships

Rails 5, thinking sphinx, indexing and searching has meny through relationships

我有一个 Rails 应用程序,我想在其中使用 Thinking Sphinx 进行搜索。我在以下模型之间有很多关系,Product 有许多 TypeProductType

# Product.rb
has_many :product_types
has_many :types, through: :product_types

# Type.rb
has_many :product_types
has_many :products, through: :product_types

# ProductType.rb
belongs_to :product
belongs_to :type

在我的 ProductsController 索引操作中,我希望能够根据给定的 Variant id 过滤视图中显示的产品。

我的相关索引目前是这样的(注意,我已经很久没有使用 ThinkingSphinx 了):

# product_index.rb
ThinkingSphinx::Index.define :product, :with => :active_record do
  indexes name, :sortable => true
  indexes description
  indexes brand.name, as: :brand, sortable: true

  indexes product_types.type.id, as: :product_types

  has created_at, updated_at
end

# type_index.rb
ThinkingSphinx::Index.define :type, :with => :active_record do
  indexes name, :sortable => true
end

# product_type_index.rb
ThinkingSphinx::Index.define :product_type, :with => :active_record do
  has product_id, type: :integer
  has type_id, type: :integer
end

我目前在 link_to 中传递一个 :product_types id 数组,像这样(如果有更好的方法,请告诉我):

= link_to "Web shop", products_path(product_types: Type.all.map(&:id), brand: Brand.all.map(&:id)), class: "nav-link"

在我的 ProductsController 中,我尝试根据给定的 Type id 过滤结果,如下所示:

product_types = params[:product_types]
@products = Product.search with_all: { product_types: product_types.collect(&:to_i) }

当我 运行 rake ts:rebuild 我得到以下错误:

indexing index 'product_type_core'...
ERROR: index 'product_type_core': No fields in schema - will not index

当我尝试在浏览器中查看视图时,出现以下错误:

index product_core: no such filter attribute 'product_types' 
- SELECT *   FROM `product_core` WHERE `sphinx_deleted` = 0 AND  
`product_types` = 1 AND   `product_types` = 2 AND `product_types` = 3 
LIMIT 0, 20; SHOW META

关于如何为这种情况正确设置索引(和查询)的任何想法?

这里有几个问题需要注意:

首先,您在 rake ts:rebuild 期间看到的错误指出您没有在 ProductType Sphinx 索引中设置任何字段 - 没有 indexes 调用您希望搜索的文本数据在。您实际上是在搜索 ProductType 吗?如果是这样,您希望人们根据什么文本进行匹配?

如果您不是在该模型上进行搜索,则无需为其创建 Sphinx 索引。

其次,您的搜索存在问题 - 您在 product_types 上使用整数进行过滤,这是有道理的。但是,在您的索引中,您已将 product_types 定义为字段(使用 indexes)而不是属性(使用 has)。鉴于它是整数值,并且您可能不希望有人在搜索输入中输入 ID,您几乎肯定希望它成为一个属性 - 因此将 indexes 更改为 has对于产品索引定义中的那一行,以及 运行 ts:rebuild.