ruby-on-railssolrsunspotacts-as-treesunspot-rails

How to search a tree with sunspot & solr


I have a model that looks something like this

class Post
  acts_as_tree
end

What I want to do is conduct a search on the contents of an entire thread of posts, but only return the parent post in the results, and paginate these results.

I've read about facets in sunspot/solr, and while this does return the correct results, they cannot be paginated.

Basically, I want to search a set of posts, but group by their parent_id. Is this possible in sunspot/solr?


Solution

  • You basically want to search over a field that is composed of all of a thread's child nodes. You can do this with sunspot's block syntax. If the post is a root node, index all of the node's children (you'll have to implement all_children, which shouldn't be too hard).

    searchable do
      text :posts do
        all_children.map(&:post_body) unless parent
      end
    end
    

    Then search over this "posts" text field. Since you only indexed anything for root nodes, these are the only objects that will be returned in your result set.