To import data from a MySQL database using Xunsearch, you need to use the Xunsearch PHP extension and the relevant APIs. Below is a simple example of code – assume you have already installed Xunsearch and configured the indexing and database connection.
<?php
// 引入 Xunsearch 扩展
require_once '/path/to/xunsearch/sdk/php/lib/XS.php';
// 创建 XS 对象
$xs = new XS('demo');
// 获取 XS 的搜索对象
$search = $xs->search;
// 连接 MySQL 数据库
$mysqli = new mysqli("localhost", "username", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli->connect_error;
exit();
}
// 查询数据
$result = $mysqli->query("SELECT id, title, content FROM table");
if ($result) {
// 开始导入数据到 Xunsearch
while ($row = $result->fetch_assoc()) {
$doc = new XSDocument;
$doc->setField('id', $row['id']);
$doc->setField('title', $row['title']);
$doc->setField('content', $row['content']);
$search->index->add($doc);
}
// 提交更改
$search->index->flushIndex();
} else {
echo "Failed to fetch data from MySQL";
}
// 关闭数据库连接
$mysqli->close();
// 输出导入完成信息
echo "Import data into Xunsearch complete";In this example, we first install the Xunsearch PHP extension and create an Xunsearch object. Then, we connect to a MySQL database, query the data to be imported, and add each record to the Xunsearch index one by one. Finally, we commit the changes and close the database connection.
Please note that this is just a simple example; in real-world scenarios, you may need to implement additional error handling and performance optimizations based on your specific requirements.