How to query Sphinx for an exact matching phrase?

Kevin Lee picture Kevin Lee · Mar 24, 2011 · Viewed 15.9k times · Source

It seems that Sphinx is searching the documents word by word. I don't know how to search the documents for an exact phrase. I tried SPH_MATCH_ALL, SPH_MATCH_PHRASE but all search the documents word by word. I'm using it in my PHP application.

How do I query Sphinx to match an exact string?

Here's my code:

$sphinx = new SphinxClient();
$mode = SPH_MATCH_PHRASE;
$sphinx->setServer('127.0.0.1', 9312);
$sphinx->setLimits(0,1);
$sphinx->setMaxQueryTime(5000);
$sphinx->setMatchMode($mode);
$sphinx->setFieldWeights(array('name' => 100));
$sphinx->setArrayResult(true);

$result = $sphinx->query('Lorem ipsum dolor sit amet, consectetur adipiscing elit.');
print_r($result);

The return result is this:

Array (
    [error] =>
    [warning] =>
    [status] => 0
    [fields] => Array (
        [0] => name
        [1] => company
        [2] => image
        [3] => price
    )
    [attrs] => Array ()
    [total] => 0
    [total_found] => 0
    [time] => 0.000
    [words] => Array (
        [lorem] => Array (
            [docs] => 0
            [hits] => 0
        )
        [ipsum] => Array (
            [docs] => 0
            [hits] => 0
        )
        [dolor] => Array (
            [docs] => 0
            [hits] => 0
        )
        [sit] => Array (
            [docs] => 0
            [hits] => 0
        )
        [amet] => Array (
            [docs] => 0
            [hits] => 0
        )
        [consectetur] => Array (
            [docs] => 0
            [hits] => 0
        )
        [adipiscing] => Array (
            [docs] => 0
            [hits] => 0
        )
        [elit] => Array (
            [docs] => 0
            [hits] => 0
        )
    )
)

As you can see, Sphinx is searching the documents word by word...

Answer

Iaroslav Vorozhko picture Iaroslav Vorozhko · Nov 15, 2011

The best way is to use SPH_MATCH_EXTENDED2 syntax and take your query in double quotes.

$sphinx->SetMatchMode(SPH_MATCH_EXTENDED2);
$sphinx->Query('"Lorem ipsum dolor"'); 

Extended syntax