Search by year with Thinking Sphinx

拟墨画扇 提交于 2019-12-13 05:16:54

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/19157235/search-by-year-with-thinking-sphinx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!