开始使用,以 YII2 为例:
composer 安装: composer require hightman/xunsearch 安装说明
生成配置文件,可根据文档自己手写一份,配置文件简单清晰。我的配置:
user_id
name
1
张三
2
李四
3
王五
...
...
project.name = user
project.default_charset = utf-8
server.index = 8383
server.search = 8384
[user_id]
type = id
[name]
index = self
tokenizer = default
这里只使用了用户id和名称
创建索引
namespace console\helper;
use Yii;
class UserXunSearch
{
/**
* 创建文档
* createDoc
*/
public static function createDoc()
{
try {
$userData = []; //数据自己查一下
/**
* @var $xunSearch \hightman\xunsearch\ConnectionYII2,
*/
$xunSearch = Yii::$app->xunsearch;
$db = $xunSearch->getDatabase('user');
$db->charset = 'UTF-8';
$db->createDoc();
foreach ($userData as $user){
//添加文档 http://www.xunsearch.com/doc/php/guide/index.add
$db->add([
'user_id' => $user['user_id'],
'name' => $user['name'],
]);
}
return true;
}catch (\Exception $e){
Yii::error($e->getMessage());
return false;
}
}
/**
* 搜索内容
* search
* @param $keyword
* @return bool|\XSDocument[]
*/
public static function search($keyword)
{
try {
/**
* @var $xunSearch \hightman\xunsearch\Connection
*/
$xunSearch = Yii::$app->xunsearch;
$db = $xunSearch->getDatabase('user');
return $db->xs->getSearch()
->setQuery('name:'.$keyword) // 构建搜索语句 http://www.xunsearch.com/doc/php/guide/search.query
->search();
}catch (\Exception $e){
Yii::error($e->getMessage());
return false;
}
}
}
插件很友善了提供了AR操作,小中型项目确实是不错的选择。