redisearch php,php 使用redisearch

安装拓展包

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);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值