当前位置:Gxlcms > PHP教程 > 浅谈PHP Elasticsearch的简单使用方法

浅谈PHP Elasticsearch的简单使用方法

时间:2021-07-01 10:21:17 帮助过:64人阅读

本篇文章给大家介绍一下PHP中使用Elasticsearch的简单方法。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

推荐学习:《PHP视频教程》

PHP中使用Elasticsearch

  1. composer require elasticsearch/elasticsearch

会自动加载合适的版本!我的php是5.6的,它会自动加载5.3的elasticsearch版本!

  1. Using version ^5.3 for elasticsearch/elasticsearch
  2. ./composer.json has been updated
  3. Loading composer repositories with package information
  4. Updating dependencies (including require-dev)
  5. Package operations: 4 installs, 0 updates, 0 removals
  6. - Installing react/promise (v2.7.0): Downloading (100%)
  7. - Installing guzzlehttp/streams (3.0.0): Downloading (100%)
  8. - Installing guzzlehttp/ringphp (1.1.0): Downloading (100%)
  9. - Installing elasticsearch/elasticsearch (v5.3.2): Downloading (100%)
  10. Writing lock file
  11. Generating autoload files

简单使用

  1. <?php
  2. class MyElasticSearch
  3. {
  4. private $es;
  5. // 构造函数
  6. public function __construct()
  7. {
  8. include('../vendor/autoload.php');
  9. $params = array(
  10. '127.0.0.1:9200'
  11. );
  12. $this->es = \Elasticsearch\ClientBuilder::create()->setHosts($params)->build();
  13. }
  14. public function search() {
  15. $params = [
  16. 'index' => 'megacorp',
  17. 'type' => 'employee',
  18. 'body' => [
  19. 'query' => [
  20. 'constant_score' => [ //非评分模式执行
  21. 'filter' => [ //过滤器,不会计算相关度,速度快
  22. 'term' => [ //精确查找,不支持多个条件
  23. 'about' => '谭'
  24. ]
  25. ]
  26. ]
  27. ]
  28. ]
  29. ];
  30. $res = $this->es->search($params);
  31. print_r($res);
  32. }
  33. }
  1. <?php
  2. require "./MyElasticSearch.php";
  3. $es = new MyElasticSearch();
  4. $es->search();

执行结果

  1. Array
  2. (
  3. [took] => 2
  4. [timed_out] =>
  5. [_shards] => Array
  6. (
  7. [total] => 5
  8. [successful] => 5
  9. [skipped] => 0
  10. [failed] => 0
  11. )
  12. [hits] => Array
  13. (
  14. [total] => 1
  15. [max_score] => 1
  16. [hits] => Array
  17. (
  18. [0] => Array
  19. (
  20. [_index] => megacorp
  21. [_type] => employee
  22. [_id] => 3
  23. [_score] => 1
  24. [_source] => Array
  25. (
  26. [first_name] => 李
  27. [last_name] => 四
  28. [age] => 24
  29. [about] => 一个PHP程序员,热爱编程,谭康很帅,充满激情。
  30. [interests] => Array
  31. (
  32. [0] => 英雄联盟
  33. )
  34. )
  35. )
  36. )
  37. )
  38. )

下面是官方的一些样例整合,

  1. <?php
  2. require '../vendor/autoload.php';
  3. use Elasticsearch\ClientBuilder;
  4. class MyElasticSearch
  5. {
  6. private $client;
  7. // 构造函数
  8. public function __construct()
  9. {
  10. $params = array(
  11. '127.0.0.1:9200'
  12. );
  13. $this->client = ClientBuilder::create()->setHosts($params)->build();
  14. }
  15. // 创建索引
  16. public function create_index($index_name = 'test_ik') { // 只能创建一次
  17. $params = [
  18. 'index' => $index_name,
  19. 'body' => [
  20. 'settings' => [
  21. 'number_of_shards' => 5,
  22. 'number_of_replicas' => 0
  23. ]
  24. ]
  25. ];
  26. try {
  27. return $this->client->indices()->create($params);
  28. } catch (Elasticsearch\Common\Exceptions\BadRequest400Exception $e) {
  29. $msg = $e->getMessage();
  30. $msg = json_decode($msg,true);
  31. return $msg;
  32. }
  33. }
  34. // 删除索引
  35. public function delete_index($index_name = 'test_ik') {
  36. $params = ['index' => $index_name];
  37. $response = $this->client->indices()->delete($params);
  38. return $response;
  39. }
  40. // 创建文档模板
  41. public function create_mappings($type_name = 'goods',$index_name = 'test_ik') {
  42. $params = [
  43. 'index' => $index_name,
  44. 'type' => $type_name,
  45. 'body' => [
  46. $type_name => [
  47. '_source' => [
  48. 'enabled' => true
  49. ],
  50. 'properties' => [
  51. 'id' => [
  52. 'type' => 'integer', // 整型
  53. 'index' => 'not_analyzed',
  54. ],
  55. 'title' => [
  56. 'type' => 'string', // 字符串型
  57. 'index' => 'analyzed', // 全文搜索
  58. 'analyzer' => 'ik_max_word'
  59. ],
  60. 'content' => [
  61. 'type' => 'string',
  62. 'index' => 'analyzed',
  63. 'analyzer' => 'ik_max_word'
  64. ],
  65. 'price' => [
  66. 'type' => 'integer'
  67. ]
  68. ]
  69. ]
  70. ]
  71. ];
  72. $response = $this->client->indices()->putMapping($params);
  73. return $response;
  74. }
  75. // 查看映射
  76. public function get_mapping($type_name = 'goods',$index_name = 'test_ik') {
  77. $params = [
  78. 'index' => $index_name,
  79. 'type' => $type_name
  80. ];
  81. $response = $this->client->indices()->getMapping($params);
  82. return $response;
  83. }
  84. // 添加文档
  85. public function add_doc($id,$doc,$index_name = 'test_ik',$type_name = 'goods') {
  86. $params = [
  87. 'index' => $index_name,
  88. 'type' => $type_name,
  89. 'id' => $id,
  90. 'body' => $doc
  91. ];
  92. $response = $this->client->index($params);
  93. return $response;
  94. }
  95. // 判断文档存在
  96. public function exists_doc($id = 1,$index_name = 'test_ik',$type_name = 'goods') {
  97. $params = [
  98. 'index' => $index_name,
  99. 'type' => $type_name,
  100. 'id' => $id
  101. ];
  102. $response = $this->client->exists($params);
  103. return $response;
  104. }
  105. // 获取文档
  106. public function get_doc($id = 1,$index_name = 'test_ik',$type_name = 'goods') {
  107. $params = [
  108. 'index' => $index_name,
  109. 'type' => $type_name,
  110. 'id' => $id
  111. ];
  112. $response = $this->client->get($params);
  113. return $response;
  114. }
  115. // 更新文档
  116. public function update_doc($id = 1,$index_name = 'test_ik',$type_name = 'goods') {
  117. // 可以灵活添加新字段,最好不要乱添加
  118. $params = [
  119. 'index' => $index_name,
  120. 'type' => $type_name,
  121. 'id' => $id,
  122. 'body' => [
  123. 'doc' => [
  124. 'title' => '苹果手机iPhoneX'
  125. ]
  126. ]
  127. ];
  128. $response = $this->client->update($params);
  129. return $response;
  130. }
  131. // 删除文档
  132. public function delete_doc($id = 1,$index_name = 'test_ik',$type_name = 'goods') {
  133. $params = [
  134. 'index' => $index_name,
  135. 'type' => $type_name,
  136. 'id' => $id
  137. ];
  138. $response = $this->client->delete($params);
  139. return $response;
  140. }
  141. // 查询文档 (分页,排序,权重,过滤)
  142. public function search_doc($keywords = "电脑",$index_name = "test_ik",$type_name = "goods",$from = 0,$size = 2) {
  143. $params = [
  144. 'index' => $index_name,
  145. 'type' => $type_name,
  146. 'body' => [
  147. 'query' => [
  148. 'bool' => [
  149. 'should' => [
  150. [ 'match' => [ 'title' => [
  151. 'query' => $keywords,
  152. 'boost' => 3, // 权重大
  153. ]]],
  154. [ 'match' => [ 'content' => [
  155. 'query' => $keywords,
  156. 'boost' => 2,
  157. ]]],
  158. ],
  159. ],
  160. ],
  161. 'sort' => ['price'=>['order'=>'desc']]
  162. , 'from' => $from, 'size' => $size
  163. ]
  164. ];
  165. $results = $this->client->search($params);
  166. // $maxScore = $results['hits']['max_score'];
  167. // $score = $results['hits']['hits'][0]['_score'];
  168. // $doc = $results['hits']['hits'][0]['_source'];
  169. return $results;
  170. }
  171. }
  1. <?php
  2. require "./MyElasticSearch.php";
  3. $es = new MyElasticSearch();
  4. $r = $es->delete_index();
  5. $r = $es->create_index();
  6. $r = $es->create_mappings();
  7. $r = $es->get_mapping();
  8. print_r($r);
  9. $docs = [];
  10. $docs[] = ['id'=>1,'title'=>'苹果手机','content'=>'苹果手机,很好很强大。','price'=>1000];
  11. $docs[] = ['id'=>2,'title'=>'华为手环','content'=>'荣耀手环,你值得拥有。','price'=>300];
  12. $docs[] = ['id'=>3,'title'=>'小度音响','content'=>'智能生活,快乐每一天。','price'=>100];
  13. $docs[] = ['id'=>4,'title'=>'王者荣耀','content'=>'游戏就玩王者荣耀,快乐生活,很好很强大。','price'=>998];
  14. $docs[] = ['id'=>5,'title'=>'小汪糕点','content'=>'糕点就吃小汪,好吃看得见。','price'=>98];
  15. $docs[] = ['id'=>6,'title'=>'小米手环3','content'=>'秒杀限量,快来。','price'=>998];
  16. $docs[] = ['id'=>7,'title'=>'iPad','content'=>'iPad,不一样的电脑。','price'=>2998];
  17. $docs[] = ['id'=>8,'title'=>'中华人民共和国','content'=>'中华人民共和国,伟大的国家。','price'=>19999];
  18. foreach ($docs as $k => $v) {
  19. $r = $es->add_doc($v['id'],$v);
  20. print_r($r);
  21. }
  22. $r = $es->get_doc();
  23. $r = $es->update_doc();
  24. $r = $es->delete_doc();
  25. $r = $es->exists_doc();
  26. $r = $es->search_doc("手环 电脑");
  27. $r = $es->search_doc("玩");
  28. $r = $es->search_doc("中华");
  29. print_r($r);

更多编程相关知识,请访问:编程视频!!

以上就是浅谈PHP Elasticsearch的简单使用方法的详细内容,更多请关注gxlcms其它相关文章!

人气教程排行