安装拓展包
composer require ethanhann/redisearch-php
composer require predis/predis
Redis Modules 是 redis 4.0 引入的一种扩展机制,用户可以通过实现 redis module 提供的 C api 接口为 redis 服务添加定制化功能。
RediSearch是一个高性能的全文搜索引擎,可作为一个Redis Module 运行在Redis上,是由RedisLabs团队开发的。
要事先安装RediSearch模块,这里就不说安装模块过程
class Redisearch
{
/**
* @var Suggestion
*/
private $suggest;
private $bookIndex;
public function __construct($indexName='myIdx')
{
$redis = (new PredisAdapter())->connect('192.168.6.7', 6379,'niuniu');
//定义索引名字
$this->bookIndex = new \Ehann\RediSearch\Index($redis,$indexName);
//也可以这样定义索引名字
// $this->bookIndex->setIndexName($indexName);
//结构
$this->bookIndex
->addTextField('title',5.0) //第二个参数是权重,搜索优先级
->addTextField('body',2.0)
->addNumericField('age',3.0);
$this->suggest= new Suggestion($redis,'MySuggestions');
}
//更新文档内容
public function update($id,$title,$body,$age){
$newDocument = $this->bookIndex->makeDocument($id);
$newDocument->title->setValue($title);
$newDocument->body->setValue($body);
$newDocument->age->setValue($age);
return $this->bookIndex->replace($newDocument);
}
//创建索引
public function create(){
return $this->bookIndex->create();
}
//删除索引
public function drop(){
return $this->bookIndex->drop();
}
//删除数据
public function delete($id){
return $this->bookIndex->delete($id);
}
//新增单条数据
public function add($title,$body,$age){
return $this->bookIndex ->add([
new TextField('title', $title),
new TextField('body', $body),
new NumericField('age', $age),
]);
}
//搜索
public function search($search,$p){
// $search="朱*";
$p=$p<1?1:$p;
//要设置中文语言
$result = $this->bookIndex->language('chinese')
// ->numericFilter('age', 30, 40)
->limit(10*$p,10)
// ->sortBy("age",'desc')
// ->tagFilter("title", ['歌','胡'])
->search($search);
return json_encode([
'list'=>$result->getDocuments(),
'total'=>$result->getCount()
]);
}
//新增多条数据
public function addMany($data){
$documents = [];
foreach ($data as $record) {
// Make a new document with the external record's ID.
$newDocument = $this->bookIndex->makeDocument($record['id']);
$newDocument->title->setValue($record['title']);
$newDocument->body->setValue($record['body']);
$newDocument->age->setValue($record['age']);
$documents[] = $newDocument;
}
$this->bookIndex->addMany($documents);
}