13.10. Phrase Queries

Phrase Queries are intended for a searching for a phrases.

Phrase Queries are very flexible and allow to search exact phrases as well as sloppy phrases. Exact phrases can also contain gaps or terms in the same places. (It can be generated by Analyser for different purposes. Ex. term can be duplicated to increase term weight or several synonyms can be placed into one position). According to this phrase queries can be constructed only by API now:

$query1 = new ZSearchPhraseQuery();

$query1->addTerm(new ZSearchTerm('word1'));     // Add 'word1' at 0 relative position.
$query1->addTerm(new ZSearchTerm('word2'));     // Add 'word2' at 1 relative position.
$query1->addTerm(new ZSearchTerm('word3'), 3);  // Add 'word3' at 3 relative position.

...

$query2 = new ZSearchPhraseQuery(array('word1', 'word2', 'word3'), array(0,1,3));

...

// Query without a gap.
$query3 = new ZSearchPhraseQuery(array('word1', 'word2', 'word3'));

...

$query4 = new ZSearchPhraseQuery(array('word1', 'word2'), array(0,1), 'annotation');
    

Sloop factor sets the number of other words permitted between words in query phrase. If zero, then this is an exact phrase search. For larger values this works like a WITHIN or NEAR operator.

The slop is in fact an edit-distance, where the units correspond to moves of terms in the query phrase out of position. For example, to switch the order of two words requires two moves (the first move places the words atop one another), so to permit re-orderings of phrases, the slop must be at least two.

More exact matches are scored higher than sloppier matches, thus search results are sorted by exactness. The slop is zero by default, requiring exact matches.

Sloop factor can be assigned after query creation:

// Query without a gap.
$query = new ZSearchPhraseQuery(array('word1', 'word2'));

// Search for 'word1 word2', 'word1 ... word2'
$query->setSlop(1);
$hits1 = $index->find($query);

// Search for 'word1 word2', 'word1 ... word2', 'word1 ... ... word2', 'word2 word1'
$query->setSlop(2);
$hits2 = $index->find($query);