質問

I have Category model with many Topics. Each Topic has many Posts. Posts have fields 'rating' (float), and 'created_at' (DateTime).

I am using Thinking Sphinx for searching different fields in Category and I'm trying to add little more complicated search option.

I would like to find Categories with rating for example below 4.5 for Posts from this year only. Other example would be finding Categories with rating above 6.7 for Posts from year 2009 etc.

So far I created indexing like this:

indexes posts(:rating), as: :rating, type: :decimal
has 'SUM(rating)', as: :total_rating, type: :float

And can get Categories with Posts ratings by using:

Category.search(with: { total_rating: 0..4.5 })

But I don't know if it's possible to restrict Posts used for 'total_rating' by given year.

Any help would be appreciated.

役に立ちましたか?

解決

I'm not sure if there's an elegant way to do this, I'm afraid. The only option I can think of is something like this in your index definition:

(2008..Date.today.year).each do |year|
  has "SUM(CASE WHEN YEAR(posts.created_at) = #{year} THEN rating ELSE 0 END",
    as: "total_rating_for_#{year}".to_sym, type: :float
end
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top