试图计算 Thinking Sphinx 中每个类别的产品数量

Trying to get count of products in each category in Thinking Sphinx

我正在使用 Thinking Sphinx 并希望获得每个类别的产品数量。我的索引文件:

ThinkingSphinx::Index.define :product, :with => :active_record do
  # fields
  indexes title, :sortable => true
  indexes product_category_id

  has created_at, updated_at
end

我尝试使用查询,使用 group_by

Product.search('phone').group_by(&:product_category_id)

但它 returns 我将哈希与所有搜索结果分组,但我只想看到计数,并希望使此查询更轻松。

我也试过查询

Product.search('phone', :select => 'COUNT(product.id) as cr').group_by(&:market_id)

但是returns错误

<ThinkingSphinx::SyntaxError: sphinxql: syntax error, unexpected IDENT, expecting DISTINCT or '*' near 'product.id) as cr FROM `product_core` WHERE MATCH('phone') AND `sphinx_deleted` = 0 LIMIT 0, 20; SHOW META' - SELECT COUNT(product.id) as cr FROM `product_core` WHERE MATCH('phone') AND `sphinx_deleted` = 0 LIMIT 0, 20; SHOW META>

如前所述on GitHub:

Facet 查询是您要用于此的查询: http://pat.github.io/thinking-sphinx/facets.html

它有两个方面 - 首先,您需要将 product_category_id 从字段转换为属性并将其设置为一个方面:

has product_category_id, :facet => true

然后您可以进行 facet 调用以获取您想要的摘要信息:

Product.facets('phone')[:product_category_id]