sunspot-solr中的数量统计: facet

在使用solr过后,各种搜索都会变快很多,而solr却不怎么支持统计功能,只找到一个数量的统计,facet,简单的用法相当于:

select count(id) count,category_id value from project_categories group by category_id
# 对应solr查询及使用
search = ProjectCategory.solr_search do
# limit默认是100,也就是说默认返回100条记录,设置成-1则返回所有记录
facet :category_id ,limit:-1
end
search.facet(:category_id).rows.each{|x|puts "category_id:#{x.value} count: #{x.count}"}

search里面可以跟正常solr搜索一样附加很多条件比如:

with :stage , 2
with(:published_at).less_than_or_equal_to Time.parse('2015-1-1')
# 等等……

facet也可以分组数组模式的参数,例如project的索引是这么建的:

integer :category_ids ,:multiple=>true do
categories.map(&:id)
end
# 也就是说每个project会对应多个category_id 也可以这么搜索:
search = ProjectCategory.solr_search do
facet :category_ids ,limit:-1
end
# 跟上面一样的用法
search.facet(:category_ids).rows.each{|x|puts "category_id:#{x.value} count: #{x.count}"}

而如果我只需要返回特定的几种类别数据,比如只要类别1,2,3的数据。
直接在search里面加条件是不行的,因为solr的数据结构不像数据库的sql那样,如果加上with :category_ids ,[1,2,3] 所表达的意思是:先找出包含1或2或3的project,再执行这些project的所有category_ids的group by,得不到想要的结果,可以这么写:

facet :category_ids ,limit:-1 , only: [1,2,3]
# 可以解释为最终只取类别1,2,3的项目数量

更多solr文档参见: https://github.com/sunspot/sunspot/blob/master/README.md

你可能感兴趣的:(sunspot-solr中的数量统计: facet)