Search code examples
ruby-on-railsrubythinking-sphinx

How to iterate over grouped results in ThinkingSphinx?


I'm having trouble figuring out how to loop over the results of a ThinkingSphinx search that has been set to group_by. I currently have the following:

search = Event.search(
  {
    group_by: 'category_id', 
    group_function: :attr
  }
)
search.each_with_groupby_and_count do |event, group, count|
  puts [event, group, count].join(' - ')
end

This, however, only returns one record per category. It seems like the group and count values are correct, but I only get the first Event of each category, which I would have expected to be all the events in the group. Is it possible to get an array of Hashes or similar? Furthermore, if this is possible, would the per_page option be per group?

I would expect each_with_group_and_count to iterate over something like this:

[
   {group: 1, hits: [Event1, Event2], count: 2},
   {group: 2: hits: [Event3], count: 1}
]

Solution

  • I'm afraid Sphinx's grouping functionality doesn't behave in that matter - it only returns one document (in this situation, one event) per group value.

    It may be more appropriate to just sort by category_id instead, and track when it changes as you iterate over it (or use Enumerable#group_by to group all events by category_id) - keep in mind that Sphinx paginates results, so you may want to increase the default page size (with :per_page) depending on how you're using these results.