Searching
Boolean search
TNTSearch supports boolean search with AND, OR, and NOT operators, as well as grouping with parentheses. This gives your users fine-grained control over search queries.
Basic usage
Use the searchBoolean() method instead of search():
$tnt = new TNTSearch;
$tnt->loadConfig($config);
$tnt->selectIndex('articles.index');
$results = $tnt->searchBoolean('romeo juliet');
Operators
AND (implicit)
Words separated by spaces are combined with AND. All words must appear in the document:
// Documents must contain BOTH "romeo" AND "juliet"
$results = $tnt->searchBoolean('romeo juliet');
OR
Use or between words to match documents containing either term:
// Documents containing "hamlet" OR "macbeth"
$results = $tnt->searchBoolean('hamlet or macbeth');
NOT
Use the tilde ~ prefix to exclude documents containing a term:
// Documents with "juliet" but NOT "romeo"
$results = $tnt->searchBoolean('juliet ~romeo');
// Documents with "hamlet" but NOT "king"
$results = $tnt->searchBoolean('hamlet ~king');
Combining operators
You can combine all operators in a single query:
// Documents with "hamlet" OR "superman"
$results = $tnt->searchBoolean('hamlet or superman');
// Documents with "juliet" but NOT "well"
$results = $tnt->searchBoolean('juliet ~well');
// Documents with "eldred" but NOT "bar"
$results = $tnt->searchBoolean('eldred ~bar');
Return format
The searchBoolean() method returns the same format as regular search:
[
'ids' => [3, 4, 1, 2], // matching document IDs
'hits' => 4, // total number of matches
'execution_time' => '0.234 ms' // execution time
]
Note
Unlike the standard search(), boolean search does not compute BM25 relevance scores. Results are returned based on set operations (intersection, union, difference) rather than ranking.
How it works
Internally, TNTSearch converts your boolean query to postfix notation using the shunting-yard algorithm, then evaluates it as set operations:
- AND (
&) - intersection of document sets - OR (
|) - union of document sets - NOT (
~) - difference (removes documents from the set)
Stemming is applied to all search terms automatically, so boolean queries also benefit from word variation matching.
