当前位置:首页 > PHP > 正文内容

php elasticsearch基础使用

高老师6年前 (2019-11-15)PHP1502

elasticsearch的操作都是基于http协议的,已经有现成的php类库,composer安装即可。

{
    "require": {
        "elasticsearch/elasticsearch": "^6.7"
    }
}

(1).先封装一个简单的操作

class Es
{
    /**
     * Es_Hosts
     * @var array
     */
    private $hosts = ['127.0.0.1:9200'];

    /**
     * Es_hander
     * @var null
     */
    private $hander = null;

    /**
     * Es constructor.
     */
    public function __construct()
    {
        $this->hander = \Elasticsearch\ClientBuilder::create()->setHosts($this->hosts)->build();
    }

    /**
     * 索引一个文档(相当于mysql新增)
     * @param array $data 索引的数据
     * @return array
     */
    public function add($data)
    {
        $inputData = [
            'index' => 'hq', //索引,相当于Mysql的数据库
            'type' => 'hq_member', //索引,相当于Mysql的表
            'body' => $data //添加的文档,相当于Mysql的记录
        ];
        return $this->hander->index($inputData);
    }

    /**
     * 批量索引文档(相当于mysql批量新增)
     * @param array $allData 批量索引的数据
     * @return array
     */
    public function addAll($allData)
    {
        $inputData = [];
        foreach ($allData as $data)
        {
            $inputData['body'][] = [
                'index' => [
                    '_index' => 'hq', //索引,相当于Mysql的数据库
                    '_type' => 'hq_member', //索引,相当于Mysql的表
                ]
            ];
            $inputData['body'][] = $data;
        }
        return $this->hander->bulk($inputData);
    }

    /**
     * 获取一个文档(相当于mysql查询记录)
     * @param string $id 文档id
     * @return array|bool
     */
    public function get($id)
    {
        $inputData = [
            'index' => 'hq', //索引,相当于Mysql的数据库
            'type' => 'hq_member', //索引,相当于Mysql的表
            'id' => $id //文档的id
        ];
        try
        {
            $result = $this->hander->get($inputData);
        }
        catch (\Elasticsearch\Common\Exceptions\Missing404Exception $exception)
        {
            //不存在的文档竟然抛出异常,有点2
            return false;
        }

        return $result;
    }

    /**
     * 搜索一个文档(相当于mysql搜索记录)
     * @param string $word 搜索词
     * @return array
     */
    public function search($word)
    {
        $inputData = [
            'index' => 'hq', //索引,相当于Mysql的数据库
            'type' => 'hq_member', //索引,相当于Mysql的表
        ];
        $inputData['body']['query']['match']['desc'] = $word;
        return $this->hander->search($inputData);
    }

    /**
     * 删除一个文档(相当于mysql删除记录)
     * @param string $id 文档id
     * @return array
     */
    public function delete($id)
    {
        $inputData = [
            'index' => 'hq', //索引,相当于Mysql的数据库
            'type' => 'hq_member', //索引,相当于Mysql的表
            'id' => $id, //文档id
        ];
        return $this->hander->delete($inputData);
    }

    /**
     * 创建索引名称(相当于mysql创建库)
     * @param string $indexName 索引名
     * @return array
     */
    public function createIndex($indexName)
    {
        return $this->hander->indices()->create([
            'index' => $indexName
        ]);
    }

    /**
     * 删除索引名称(相当于mysql删库)
     * @param string $indexName 索引名
     * @return array
     */
    public function deleteIndex($indexName)
    {
        return $this->hander->indices()->delete([
            'index' => $indexName
        ]);
    }
}

(2).索引一个文档记录(相当于mysql的insert)

$oneData = ['name' => '张清喜', 'age' => 21, 'desc' => '江西的小伙子'];
$ret = $es->add($oneData);

返回内容:

{
["_index"]=>
string(2) "hq"
["_type"]=>
string(9) "hq_member"
["_id"]=>
string(20) "HIuebG4B8k6m0qLHMJmc"
["_version"]=>
int(1)
["result"]=>
string(7) "created"
["_shards"]=>
array(3) {
["total"]=>
int(2)
["successful"]=>
int(1)
["failed"]=>
int(0)
}
["_seq_no"]=>
int(3)
["_primary_term"]=>
int(1)
}

(3).获取一个文档记录,传入的是文档id

$oneData = $es->get('GYuebG4B8k6m0qLHL5nR');
var_dump($oneData);

返回内容:

{
["_index"]=>
string(2) "hq"
["_type"]=>
string(9) "hq_member"
["_id"]=>
string(20) "GYuebG4B8k6m0qLHL5nR"
["_version"]=>
int(1)
["_seq_no"]=>
int(0)
["_primary_term"]=>
int(1)
["found"]=>
bool(true)
["_source"]=>
array(3) {
["name"]=>
string(9) "高久峰"
["age"]=>
int(21)
["desc"]=>
string(24) "陕西安康的小伙子"
}

(4).搜索文档

$word = '江西';
$ret = $es->search($word);
var_dump($ret);

返回内容:

  {
  ["took"]=>
  int(2)
  ["timed_out"]=>
  bool(false)
  ["_shards"]=>
  array(4) {
    ["total"]=>
    int(1)
    ["successful"]=>
    int(1)
    ["skipped"]=>
    int(0)
    ["failed"]=>
    int(0)
  }
  ["hits"]=>
  array(3) {
    ["total"]=>
    array(2) {
      ["value"]=>
      int(2)
      ["relation"]=>
      string(2) "eq"
    }
    ["max_score"]=>
    float(2.6002216)
    ["hits"]=>
    array(2) {
      [0]=>
      array(5) {
        ["_index"]=>
        string(2) "hq"
        ["_type"]=>
        string(9) "hq_member"
        ["_id"]=>
        string(20) "HYunbG4B8k6m0qLHMpmu"
        ["_score"]=>
        float(2.6002216)
        ["_source"]=>
        array(3) {
          ["name"]=>
          string(9) "张清喜"
          ["age"]=>
          int(21)
          ["desc"]=>
          string(18) "江西的小伙子"
        }
      }
      [1]=>
      array(5) {
        ["_index"]=>
        string(2) "hq"
        ["_type"]=>
        string(9) "hq_member"
        ["_id"]=>
        string(20) "GYuebG4B8k6m0qLHL5nR"
        ["_score"]=>
        float(0.9092851)
        ["_source"]=>
        array(3) {
          ["name"]=>
          string(9) "高久峰"
          ["age"]=>
          int(21)
          ["desc"]=>
          string(24) "陕西安康的小伙子"
        }
      }
    }
  }
}

(5).批量索引文档

$allData = [
   ['name' => '谢丽芬', 'age' => 25, 'desc' => '广东富婆'],
   ['name' => '韩星星', 'age' => 25, 'desc' => '江西老表']
];
$ret = $es->addAll($allData);
var_dump($ret);

返回内容:

{
["took"]=>
int(341)
["errors"]=>
bool(false)
["items"]=>
array(2) {
[0]=>
array(1) {
["index"]=>
array(9) {
["_index"]=>
string(3) "1hq"
["_type"]=>
string(9) "hq_member"
["_id"]=>
string(20) "pi_zbG4BdMVi8p37iZ_K"
["_version"]=>
int(1)
["result"]=>
string(7) "created"
["_shards"]=>
array(3) {
["total"]=>
int(2)
["successful"]=>
int(1)
["failed"]=>
int(0)
}
["_seq_no"]=>
int(0)
["_primary_term"]=>
int(1)
["status"]=>
int(201)
}
}
[1]=>
array(1) {
["index"]=>
array(9) {
["_index"]=>
string(3) "1hq"
["_type"]=>
string(9) "hq_member"
["_id"]=>
string(20) "py_zbG4BdMVi8p37iZ_K"
["_version"]=>
int(1)
["result"]=>
string(7) "created"
["_shards"]=>
array(3) {
["total"]=>
int(2)
["successful"]=>
int(1)
["failed"]=>
int(0)
}
["_seq_no"]=>
int(1)
["_primary_term"]=>
int(1)
["status"]=>
int(201)
}
}
}
}

(6).删除文档

$ret = $es->delete('GouebG4B8k6m0qLHMJlx');
var_dump($ret);

返回内容:

{
["_index"]=>
string(2) "hq"
["_type"]=>
string(9) "hq_member"
["_id"]=>
string(20) "GouebG4B8k6m0qLHMJlx"
["_version"]=>
int(2)
["result"]=>
string(7) "deleted"
["_shards"]=>
array(3) {
["total"]=>
int(2)
["successful"]=>
int(1)
["failed"]=>
int(0)
}
["_seq_no"]=>
int(7)
["_primary_term"]=>
int(2)
}

(7).创建索引

$ret = $es->createIndex('chen');
var_dump($ret);

返回内容:

{
["acknowledged"]=>
bool(true)
["shards_acknowledged"]=>
bool(true)
["index"]=>
string(4) "chen"
}

(8).删除索引

$ret = $es->deleteIndex('chen');
var_dump($ret);

返回内容:

{
["acknowledged"]=>
bool(true)
}

(9).设置索引的配置

$ret = $es->setIndexConfig([
    'number_of_replicas' => 0, //数据备份数,如果只有一台机器,设置为0,设置了好像要重启才生效,醉了
]);
var_dump($ret);

返回内容:

 {
  ["acknowledged"]=>
  bool(true)
}

(10).获取索引的配置

$ret = $es->getIndexConfig('hq');
var_dump($ret);

返回内容:

 {
  ["hq"]=>
  array(1) {
    ["settings"]=>
    array(1) {
      ["index"]=>
      array(6) {
        ["creation_date"]=>
        string(13) "1573780336188"
        ["number_of_shards"]=>
        string(1) "1"
        ["number_of_replicas"]=>
        string(1) "0"
        ["uuid"]=>
        string(22) "VsJeaujeQdeiPsbQ9ZAPAg"
        ["version"]=>
        array(1) {
          ["created"]=>
          string(7) "7040299"
        }
        ["provided_name"]=>
        string(2) "hq"
      }
    }
  }
}

扫描二维码推送至手机访问。

版权声明:本文由高久峰个人博客发布,如需转载请注明出处。

本文链接:https://blog.20230611.cn/post/112.html

分享给朋友:

“php elasticsearch基础使用” 的相关文章

PHP getenv函数和putenv函数的学习

PHP getenv函数和putenv函数的学习

(1).在PHP中可以查看的环境变量包括: (1.1).电脑环境变量 (2.1).服务器环境变量(2).getenv()函数获取一个环境变量的值.参数1是环境变量的key,参数2值为true的时候仅从你的电脑环境变量中查找,参数2值为false会从两种变量中全部查询//获取我电脑登录的用户名,输出A...

php json_encode 使用注意

php json_encode 使用注意

参数中包含gb2312的字符串,返回结果是false或者null(不同PHP版本具有差异性)代码:<?php $dbms = 'mysql'; $host = '192.168.8.8'; $dbName =&n...

php生成器yield from详解

php生成器yield from详解

PHP7中,通过生成器委托(yield from),可以将其他生成器、可迭代的对象、数组委托给外层生成器。外层的生成器会先顺序 yield 委托出来的值,然后继续 yield 本身中定义的值。同时yield from也能获取到生成器的返回值...

php关闭浏览器继续运行

php关闭浏览器继续运行

//设置客户端断开依然运行 ignore_user_abort(true); //设置脚本不超时 set_time_limit(0); //死循环每隔1秒访问一次网址 while (true) {     sleep(1);  &nb...

PHP包含远程文件,PHP执行远程文件,PHP引入远程文件

PHP包含远程文件,PHP执行远程文件,PHP引入远程文件

(1).php.ini配置允许加载远程文件allow_url_fopen = On(2).创建本地文件invoke.php<?php require('https://blog.20230611.cn/test.txt');(3).创建远程文件https:/...

EasyTask使用redis队列教程

EasyTask使用redis队列教程

场景:模拟验证码发送。仅做代码演示。(1).创建一个验证码发送接口sendCaptcha/**  * 发送验证码  */ public function sendCaptcha() {     //外部参数(获...