Implement Real-Time Search and Automatic Index Updating with PHP and Xunsearch
This tutorial explains how to set up Xunsearch with PHP to provide efficient real‑time full‑text search and automatically update the search index, covering environment preparation, server installation, search implementation, and index synchronization steps.
When developing websites or applications, search functionality is essential, and traditional database search can be inefficient for real‑time needs.
1. Environment Preparation
Prepare a PHP environment (version 5.4 or higher) and download the Xunsearch server package.
2. Install Xunsearch
Unzip the downloaded Xunsearch server archive and start the server by running ./xunsearchd .
3. Set Up Index and Search Example
Create a PHP file named search.php , include the Xunsearch library, instantiate an XS object, configure the search object, and execute a query.
require_once '/path/to/sdk/php/lib/XS.php';
$xs = new XS('/path/to/xunsearch/app.ini');
$search = $xs->search;
$search->setFuzzy();
$search->setLimit(10);
$search->setScwsMulti(3);
$search->addWeight('title', 10);
$search->addWeight('content', 5);
$keyword = $_GET['q'];
$result = $search->search($keyword);
foreach ($result as $item) {
echo $item->title . '
';
echo $item->content . '
';
}4. Automatic Index Updating
Create a PHP file named update.php , include the Xunsearch library, instantiate an XS object, obtain a PDO connection to fetch data from a MySQL database, and update the Xunsearch index accordingly.
require_once '/path/to/sdk/php/lib/XS.php';
$xs = new XS('/path/to/xunsearch/app.ini');
$index = $xs->index;
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('SELECT * FROM articles');
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($data as $item) {
$doc = new XSDocument();
$doc->setFields($item);
$index->update($doc);
}
$index->flushIndex();The tutorial demonstrates how to use PHP and Xunsearch to achieve real‑time search and keep the index up‑to‑date, enabling efficient search functionality for web applications.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.