0
  @search = Sunspot.search(Event, Person, Organization) do
    keywords params[:q]
    order_by(:score)
  end

Based on the search results I'd like to create a list of Models with counts for each model.

  • Events (12)
  • People (5)
  • Organizations (3)

Is there a way to do this type of grouping in Sunspot?

<% @search.each_hit_with_result do |hit, result| -%>
    <%= result.class %> <!- Gives me Model, but repeated -->
<% end %>
Walksalong
  • 191
  • 2
  • 13

1 Answers1

0

There is probably a smarter way, but one possible way is to get array of the classes like this

classes = @search.results.map(&:class) # this will give array of returned classes

then do as suggested in this link

h = Hash.new(0)
classes.each { | v | h.store(v, h[v]+1) }

# h = { 3=>3, 2=>1, 1=>1, 4=>1 }

hope that helps

Community
  • 1
  • 1
Bashar Abdullah
  • 1,545
  • 1
  • 16
  • 27
  • Since Sunspot automatically adds pagination I had to set the per_page to 999999 or you could do a count. – Walksalong Jun 18 '12 at 16:29
  • yes it seems these are the only ways. The count looks cleaner though to me. Btw, just make sure you're not returning huge amount of results or else with time this might slow down a lot. – Bashar Abdullah Jun 19 '12 at 10:02