Search code examples
searchsphinxthinking-sphinx

How to perform sphinx Multi-queries with Thinking Sphinx


My main aim is to perform Multiple Sphinx queries at once. They can be on different models/tables or some commons ones. The final result should be grouped query-wise.

This seems to be supported in Sphinx with Multi-Queries : http://sphinxsearch.com/docs/2.0.7/multi-queries.html

Using ThinkingSphinx with Rails Application, Is there any way I can use this functionality.?

(FYI my TS version is 2.0.11, However I would like to know if it can be done anyways with version 3.x if not with 2.x)


Solution

  • In Thinking Sphinx v1/v2, it's not particularly elegant, but here's the deal:

    bundle = ThinkingSphinx::BundledSearch.new
    bundle.search 'foo'
    bundle.search 'bar', :classes => [Article]
    bundle.search 'baz', :classes => [User, Article], :with => {:active => true}
    
    # as soon as you call `searches` on the bundle, the group of queries is sent
    # through to Sphinx.
    foo_search, bar_search, baz_search = bundle.searches
    

    With Thinking Sphinx v3, it's a bit different:

    batch      = ThinkingSphinx::BatchedSearch.new
    foo_search = ThinkingSphinx.search 'foo'
    bar_search = Article.search 'bar'
    baz_search = ThinkingSphinx.search 'baz', :classes => [User, Article],
      :with => {:active => true}
    batch.searches += [foo_search, bar_search, baz_search]
    batch.populate
    # Use each of your search results objects now as you normally would.
    # If you use any of them to access results before the batch.populate call,
    # then that will be a separate call to Sphinx.
    

    As an aside from all of this - if you're going to stick with v2 releases for the moment, I'd highly recommend upgrading to Thinking Sphinx v2.1.0, as that's still the old syntax, but uses a connection pool, so even if you're not batching all of these queries together, the socket setup overhead is minimised as much as possible.