Search code examples
sphinx

Use exact search with OR operator inside Sphinx query


There are different search options possible with sphinx extended syntax.

  • Exact search: "I love to eat" //will match exact phrase
  • OR search: (eat|sleep|dream)

Is it possible to mix them and build queries like that:

"I love to (eat|sleep|dream)"

I know it is possible to simplify it and split OR condition to different exact phrases, like:

"I love to eat" | "I love to sleep" | "I love to dream"

But I plan to use lot of OR groups with lot of options inside, and extending this query will end up with huge one.

So is it possible to use OR syntax inside exact match syntax in Sphinx?


Solution

  • No, its not possible to use 'OR' within the Phrase Operator (the "s around words that enforces adjacent words) - the proper name for what you call 'exact match'.

    Alas there isn't another combined 'strict order' operator and 'near' (ie there isnt a 'just before' operator). So you forced to use both, so something like

    ("I love to" << (eat|sleep|dream)) NEAR/3 ("I love to" NEAR/1 (eat|sleep|dream))
    

    Which is no simpler, and would argue is more complicated and convoluted! The NEAR/3 in the middle is needed to make sure you matching on the same sentance within the document (otherwise there are edge cases with false positives).


    An off the wall idea, if you have a lot of these 'OR' lists, is rather than implement them in the query, use wordforms instead. The drawback is you need to know them in advance (ie compiled into the index) and 'opting out' is more complicated.