如何使用思维sphinx索引聚合关联字段

时间:2016-03-22 16:09:13

标签: ruby-on-rails thinking-sphinx

所以,我正在试图找出如何在我的sphinx索引中使用聚合字段。 (伯爵和AVG)

我有一个名为business_profile的模型,它与business_feedbacks有一个has_many关联:

class BusinessProfile < ActiveRecord::Base
    has_many :business_feedbacks
    #...
end

尝试为count和avg添加聚合字段:

ThinkingSphinx::Index.define(:business_profile, with: :active_record, delta: ThinkingSphinx::Deltas::DatetimeDelta) do
    # indexes ... fields
    has 'COUNT(business_feedbacks.id)', as: :feedback_count
    has 'AVG(business_feedbacks.recommend)', as: :feedback_recommend
end 

当我尝试重建索引时,我收到此错误(rake ts:rebuild):

ThinkingSphinx::MissingColumnError: column COUNT(business_feedbacks.id) does not exist

如何将这些聚合字段添加到索引中?我希望能够通过feedback_count或feedback_recommend对结果进行排序。

1 个答案:

答案 0 :(得分:1)

因为您没有直接引用列,所以您需要手动指定类型:

has 'COUNT(business_feedbacks.id)',      as: :feedback_count,     type: :integer
has 'AVG(business_feedbacks.recommend)', as: :feedback_recommend, type: :integer

...或者如果推荐列不是整数,则可以相应地更改平均类型。