设为首页收藏本站

安徽论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 7336|回复: 0

php操作ElasticSearch搜索引擎流程详解

[复制链接]

85

主题

0

回帖

267

积分

中级会员

Rank: 3Rank: 3

积分
267
发表于 2022-3-26 10:56:15 | 显示全部楼层 |阅读模式
网站内容均来自网络,本站只提供信息平台,如有侵权请联系删除,谢谢!
目录

〝 古人学问遗无力,少壮功夫老始成 〞

如果这篇文章能给你带来一点帮助,希望给飞兔小哥哥一键三连,表示支持,谢谢各位小伙伴们。

一、安装

通过composer安装
  1. composer require 'elasticsearch/elasticsearch'
复制代码
二、使用

创建ES类
  1. <?php

  2. require 'vendor/autoload.php';

  3. //如果未设置密码
  4. $es = \Elasticsearch\ClientBuilder::create()->setHosts(['xxx.xxx.xxx.xxx'])->build();

  5. //如果es设置了密码
  6. $es = \Elasticsearch\ClientBuilder::create()->setHosts(['http://username:password@xxx.xxx.xxx.xxx:9200'])->build()
复制代码
三、新建ES数据库

index 对应关系型数据(以下简称MySQL)里面的数据库,而不是对应MySQL里面的索引
  1. <?php
  2. $params = [
  3.     'index' => 'autofelix_db', #index的名字不能是大写和下划线开头
  4.     'body' => [
  5.         'settings' => [
  6.             'number_of_shards' => 5,
  7.             'number_of_replicas' => 0
  8.         ]
  9.     ]
  10. ];
  11. $es->indices()->create($params);
复制代码
四、创建表

       
  • 在MySQL里面,光有了数据库还不行,还需要建立表,ES也是一样的   
  • ES中的type对应MySQL里面的表   
  • ES6以前,一个index有多个type,就像MySQL中一个数据库有多个表一样   
  • 但是ES6以后,每个index只允许一个type   
  • 在定义字段的时候,可以看出每个字段可以定义单独的类型   
  • 在first_name中还自定义了 分词器 ik,这是个插件,是需要单独安装的
  1. <?php
  2. $params = [
  3.     'index' => 'autofelix_db',
  4.     'type' => 'autofelix_table',
  5.     'body' => [
  6.         'mytype' => [
  7.             '_source' => [
  8.                 'enabled' => true
  9.             ],
  10.             'properties' => [
  11.                 'id' => [
  12.                     'type' => 'integer'
  13.                 ],
  14.                 'first_name' => [
  15.                     'type' => 'text',
  16.                     'analyzer' => 'ik_max_word'
  17.                 ],
  18.                 'last_name' => [
  19.                     'type' => 'text',
  20.                     'analyzer' => 'ik_max_word'
  21.                 ],
  22.                 'age' => [
  23.                     'type' => 'integer'
  24.                 ]
  25.             ]
  26.         ]
  27.     ]
  28. ];
  29. $es->indices()->putMapping($params);
复制代码
五、插入数据

       
  • 现在数据库和表都有了,可以往里面插入数据了   
  • 在ES里面的数据叫文档   
  • 可以多插入一些数据,等会可以模拟搜索功能
  1. <?php
  2. $params = [
  3.     'index' => 'autofelix_db',
  4.     'type' => 'autofelix_table',
  5.     //'id' => 1, #可以手动指定id,也可以不指定随机生成
  6.     'body' => [
  7.         'first_name' => '飞',
  8.         'last_name' => '兔',
  9.         'age' => 26
  10.     ]
  11. ];
  12. $es->index($params);
复制代码
六、 查询所有数据
  1. <?php
  2. $data = $es->search();

  3. var_dump($data);
复制代码
七、查询单条数据

       
  • 如果你在插入数据的时候指定了id,就可以查询的时候加上id   
  • 如果你在插入的时候未指定id,系统将会自动生成id,你可以通过查询所有数据后查看其id
  1. <?php
  2. $params = [
  3.     'index' => 'autofelix_db',
  4.     'type' => 'autofelix_table',
  5.     'id' =>  //你插入数据时候的id
  6. ];
  7. $data = $es->get($params);
复制代码
八、搜索

ES精髓的地方就在于搜索
  1. <?php
  2. $params = [
  3.     'index' => 'autofelix_db',
  4.     'type' => 'autofelix_table',
  5.     'body' => [
  6.         'query' => [
  7.             'constant_score' => [ //非评分模式执行
  8.                 'filter' => [ //过滤器,不会计算相关度,速度快
  9.                     'term' => [ //精确查找,不支持多个条件
  10.                         'first_name' => '飞'
  11.                     ]
  12.                 ]
  13.             ]
  14.         ]
  15.     ]
  16. ];

  17. $data = $es->search($params);
  18. var_dump($data);
复制代码
九、测试代码

基于Laravel环境,包含删除数据库,删除文档等操作
  1. <?php
  2. use Elasticsearch\ClientBuilder;
  3. use Faker\Generator as Faker;

  4. /**
  5. * ES 的 php 实测代码
  6. */
  7. class EsDemo
  8. {
  9.     private $EsClient = null;
  10.     private $faker = null;

  11.     /**
  12.      * 为了简化测试,本测试默认只操作一个Index,一个Type
  13.      */
  14.     private $index = 'autofelix_db';
  15.     private $type = 'autofelix_table';

  16.     public function __construct(Faker $faker)
  17.     {
  18.         /**
  19.          * 实例化 ES 客户端
  20.          */
  21.         $this->EsClient = ClientBuilder::create()->setHosts(['xxx.xxx.xxx.xxx'])->build();
  22.         /**
  23.          * 这是一个数据生成库
  24.          */
  25.         $this->faker = $faker;
  26.     }

  27.     /**
  28.      * 批量生成文档
  29.      * @param $num
  30.      */
  31.     public function generateDoc($num = 100) {
  32.         foreach (range(1,$num) as $item) {
  33.             $this->putDoc([
  34.                 'first_name' => $this->faker->name,
  35.                 'last_name' => $this->faker->name,
  36.                 'age' => $this->faker->numberBetween(20,80)
  37.             ]);
  38.         }
  39.     }

  40.     /**
  41.      * 删除一个文档
  42.      * @param $id
  43.      * @return array
  44.      */
  45.     public function delDoc($id) {
  46.         $params = [
  47.             'index' => $this->index,
  48.             'type' => $this->type,
  49.             'id' =>$id
  50.         ];
  51.         return $this->EsClient->delete($params);
  52.     }

  53.     /**
  54.      * 搜索文档,query是查询条件
  55.      * @param array $query
  56.      * @param int $from
  57.      * @param int $size
  58.      * @return array
  59.      */
  60.     public function search($query = [], $from = 0, $size = 5) {
  61. //        $query = [
  62. //            'query' => [
  63. //                'bool' => [
  64. //                    'must' => [
  65. //                        'match' => [
  66. //                            'first_name' => 'Cronin',
  67. //                        ]
  68. //                    ],
  69. //                    'filter' => [
  70. //                        'range' => [
  71. //                            'age' => ['gt' => 76]
  72. //                        ]
  73. //                    ]
  74. //                ]
  75. //
  76. //            ]
  77. //        ];
  78.         $params = [
  79.             'index' => $this->index,
  80. //            'index' => 'm*', #index 和 type 是可以模糊匹配的,甚至这两个参数都是可选的
  81.             'type' => $this->type,
  82.             '_source' => ['first_name','age'], // 请求指定的字段
  83.             'body' => array_merge([
  84.                 'from' => $from,
  85.                 'size' => $size
  86.             ],$query)
  87.         ];
  88.         return $this->EsClient->search($params);
  89.     }

  90.     /**
  91.      * 一次获取多个文档
  92.      * @param $ids
  93.      * @return array
  94.      */
  95.     public function getDocs($ids) {
  96.         $params = [
  97.             'index' => $this->index,
  98.             'type' => $this->type,
  99.             'body' => ['ids' => $ids]
  100.         ];
  101.         return $this->EsClient->mget($params);
  102.     }

  103.     /**
  104.      * 获取单个文档
  105.      * @param $id
  106.      * @return array
  107.      */
  108.     public function getDoc($id) {
  109.         $params = [
  110.             'index' => $this->index,
  111.             'type' => $this->type,
  112.             'id' =>$id
  113.         ];
  114.         return $this->EsClient->get($params);
  115.     }

  116.     /**
  117.      * 更新一个文档
  118.      * @param $id
  119.      * @return array
  120.      */
  121.     public function updateDoc($id) {
  122.         $params = [
  123.             'index' => $this->index,
  124.             'type' => $this->type,
  125.             'id' =>$id,
  126.             'body' => [
  127.                 'doc' => [
  128.                     'first_name' => '张',
  129.                     'last_name' => '三',
  130.                     'age' => 99
  131.                 ]
  132.             ]
  133.         ];
  134.         return $this->EsClient->update($params);
  135.     }

  136.     /**
  137.      * 添加一个文档到 Index 的Type中
  138.      * @param array $body
  139.      * @return void
  140.      */
  141.     public function putDoc($body = []) {
  142.         $params = [
  143.             'index' => $this->index,
  144.             'type' => $this->type,
  145.             // 'id' => 1, #可以手动指定id,也可以不指定随机生成
  146.             'body' => $body
  147.         ];
  148.         $this->EsClient->index($params);
  149.     }

  150.     /**
  151.      * 删除所有的 Index
  152.      */
  153.     public function delAllIndex() {
  154.         $indexList = $this->esStatus()['indices'];
  155.         foreach ($indexList as $item => $index) {
  156.             $this->delIndex();
  157.         }
  158.     }

  159.     /**
  160.      * 获取 ES 的状态信息,包括index 列表
  161.      * @return array
  162.      */
  163.     public function esStatus() {
  164.         return $this->EsClient->indices()->stats();
  165.     }

  166.     /**
  167.      * 创建一个索引 Index (非关系型数据库里面那个索引,而是关系型数据里面的数据库的意思)
  168.      * @return void
  169.      */
  170.     public function createIndex() {
  171.         $this->delIndex();
  172.         $params = [
  173.             'index' => $this->index,
  174.             'body' => [
  175.                 'settings' => [
  176.                     'number_of_shards' => 2,
  177.                     'number_of_replicas' => 0
  178.                 ]
  179.             ]
  180.         ];
  181.         $this->EsClient->indices()->create($params);
  182.     }

  183.     /**
  184.      * 检查Index 是否存在
  185.      * @return bool
  186.      */
  187.     public function checkIndexExists() {
  188.         $params = [
  189.             'index' => $this->index
  190.         ];
  191.         return $this->EsClient->indices()->exists($params);
  192.     }

  193.     /**
  194.      * 删除一个Index
  195.      * @return void
  196.      */
  197.     public function delIndex() {
  198.         $params = [
  199.             'index' => $this->index
  200.         ];
  201.         if ($this->checkIndexExists()) {
  202.             $this->EsClient->indices()->delete($params);
  203.         }
  204.     }

  205.     /**
  206.      * 获取Index的文档模板信息
  207.      * @return array
  208.      */
  209.     public function getMapping() {
  210.         $params = [
  211.             'index' => $this->index
  212.         ];
  213.         return $this->EsClient->indices()->getMapping($params);
  214.     }

  215.     /**
  216.      * 创建文档模板
  217.      * @return void
  218.      */
  219.     public function createMapping() {
  220.         $this->createIndex();
  221.         $params = [
  222.             'index' => $this->index,
  223.             'type' => $this->type,
  224.             'body' => [
  225.                 $this->type => [
  226.                     '_source' => [
  227.                         'enabled' => true
  228.                     ],
  229.                     'properties' => [
  230.                         'id' => [
  231.                             'type' => 'integer'
  232.                         ],
  233.                         'first_name' => [
  234.                             'type' => 'text',
  235.                             'analyzer' => 'ik_max_word'
  236.                         ],
  237.                         'last_name' => [
  238.                             'type' => 'text',
  239.                             'analyzer' => 'ik_max_word'
  240.                         ],
  241.                         'age' => [
  242.                             'type' => 'integer'
  243.                         ]
  244.                     ]
  245.                 ]
  246.             ]
  247.         ];
  248.         $this->EsClient->indices()->putMapping($params);
  249.         $this->generateDoc();
  250.     }
  251. }
复制代码
到此这篇关于php操作ElasticSearch搜索引擎流程详解的文章就介绍到这了,更多相关php ElasticSearch搜索引擎内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
                                                        
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
免责声明
1. 本论坛所提供的信息均来自网络,本网站只提供平台服务,所有账号发表的言论与本网站无关。
2. 其他单位或个人在使用、转载或引用本文时,必须事先获得该帖子作者和本人的同意。
3. 本帖部分内容转载自其他媒体,但并不代表本人赞同其观点和对其真实性负责。
4. 如有侵权,请立即联系,本网站将及时删除相关内容。
懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表