Question

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.

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top