Advanced features
Index management
TNTSearch supports dynamic index updates, allowing you to insert new documents, update existing ones, and delete documents without rebuilding the entire index. This is essential for keeping your search index in sync with your application data.
Getting the index handle
After selecting an index, get an indexer instance with getIndex():
$tnt = new TNTSearch;
$tnt->loadConfig($config);
$tnt->selectIndex('articles.index');
$index = $tnt->getIndex();
Inserting documents
Add new documents to an existing index:
$index->insert([
'id' => 13,
'title' => 'Othello',
'article' => 'For she had eyes and chose me.',
]);
The array keys must match the columns used when the index was created. After insertion, the document is immediately searchable:
$results = $tnt->search('Othello');
// [13]
Updating documents
Update an existing document by providing its ID and the new content:
$index->update(11, [
'id' => 11,
'title' => 'Updated Title',
'article' => 'New article content about romeo.',
]);
The update process removes the old document data from the index and inserts the new data. Word counts and document frequencies are adjusted automatically.
If the document ID doesn't exist in the index, update() acts as an insert and the total document count increases.
Deleting documents
Remove a document from the index by its ID:
$index->delete(12);
After deletion, the document will no longer appear in search results. Word counts and document frequencies are decremented accordingly.
Monitoring index state
You can check the total number of indexed documents:
$total = $tnt->totalDocumentsInCollection();
echo "Total documents: $total"; // e.g., 12
This count updates automatically as you insert and delete documents.
Full example
$tnt = new TNTSearch;
$tnt->loadConfig($config);
$tnt->selectIndex('articles.index');
$index = $tnt->getIndex();
// Check initial state
echo $tnt->totalDocumentsInCollection(); // 12
// Delete a document
$index->delete(12);
echo $tnt->totalDocumentsInCollection(); // 11
// Insert a new document
$index->insert([
'id' => 13,
'title' => 'New Article',
'article' => 'Content of the new article.',
]);
echo $tnt->totalDocumentsInCollection(); // 12
// Update an existing document
$index->update(13, [
'id' => 13,
'title' => 'Updated Article',
'article' => 'Updated content of the article.',
]);
echo $tnt->totalDocumentsInCollection(); // 12 (unchanged)
Rebuilding from scratch
If your data has changed significantly, it may be more efficient to rebuild the index entirely rather than performing many individual updates:
$indexer = $tnt->createIndex('articles.index');
$indexer->query('SELECT id, title, article FROM articles;');
$indexer->run();
Creating an index with the same name replaces the existing one.
Tip
For applications with frequent data changes, consider running index updates in a queue or background job to avoid slowing down your main application flow.
