PHP使用redisearch

zhan11400
字数 9103阅读 85

使用前先 composer require ethanhann/redisearch-php

 composer require predis/predis

使用前必须确保已经加载了redis已经redisearch模块,redis必须4.0以上版本才能支持

class Test
{
   private $bookIndex;
    public function __construct()
    {
        $redis = (new PredisAdapter())->connect('192.168.16.130', 6379);
        $this->bookIndex= $bookIndex = new \Ehann\RediSearch\Index($redis,'myIdx');
        $this->bookIndex
            ->addTextField('title',5.0)
            ->addTextField('body')
            ->addNumericField('age');
    }
    //创建索引
    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){
     //   $search="朱*";
        $result = $this->bookIndex->language('chinese')
        //    ->numericFilter('age', 30, 40)
        //    ->limit(0,100)
         //   ->sortBy("age",'desc')
          //  ->tagFilter("title", ['歌','胡'])
            ->search($search);
        return json_encode([
            'list'=>$result->getDocuments(),
            'total'=>$result->getCount()
        ]);
    }
    //新增多条数据
    public function addMany($data){
        $data=[
            ['id'=>1,'title'=>'张学友','body'=>'香港','age'=>56],
            ['id'=>2,'title'=>'黎明','body'=>'香港','age'=>52],
            ['id'=>3,'title'=>'郭富城','body'=>'香港','age'=>50],
            ['id'=>4,'title'=>'勒东','body'=>'内陆','age'=>42],
            ['id'=>5,'title'=>'胡歌','body'=>'内陆','age'=>36],
            ['id'=>6,'title'=>'刘亦菲','body'=>'美国','age'=>35],
            ['id'=>7,'title'=>'吴亦凡','body'=>'加拿大','age'=>30],
            ['id'=>8,'title'=>'杨幂','body'=>'内陆','age'=>30],
            ['id'=>9,'title'=>'古天乐','body'=>'香港','age'=>35],
            ['id'=>10,'title'=>'明道','body'=>'台湾','age'=>39],
        ];
        $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条评论
    暂无评论
发表评论