• laravel中使用ElasticSearch详情


    一、快速开始

    1. laravel 安装es

      composer require elasticsearch/elasticsearch
      
    2. 环境配置 .env

      ELASTIC_HOST=192.168.20.129:9200 # 这里是你的 ElasticSearch 服务器 IP 及端口号
      ELASTIC_LOG_INDEX=bf_log # ElasticSearch 索引
      ELASTIC_LOG_TYPE=log # ElasticSearch 类型
      
    3. Es 配置文件 /config/elasticsearch.php

      <?php
      
      return [
          'hosts' => [
              env('ELASTIC_HOST')
          ],
          'log_index' => env('ELASTIC_LOG_INDEX'),
          'log_type' => env('ELASTIC_LOG_TYPE'),
      ];
      
    4. document 的使用

      <?php
      namespace AppHttpControllersHome;
      
      use AppHttpControllersController;
      use ElasticsearchClientBuilder;
      
      class HomeController extends Controller {
          public $client = null;
      
          public function __construct() {
              $this-> client = ClientBuilder::create()->build();
          }
      
        //创建
          public function index(){
              $params = [
                  'index' => 'my_index',
                  'type' => 'my_type',
                  'id' => 'my_id',
                  'body' => ['testField' => 'abc']
              ];
      
              $response = $this->client->index($params);
              print_r($response);
          }
        
      }
      

      执行 localhost/home, 返回

      Array(
          [_index] => my_index
          [_type] => my_type
          [_id] => my_id
          [_version] => 1	#每刷新一次version值会+1,从1递增
          [result] => created	#第一次执行result值是created,第二次刷新是update
          [_shards] => Array(
                  [total] => 2
                  [successful] => 1
                  [failed] => 0)
          [_seq_no] => 0	#每刷新一次,seq_no会+1,从0递增
          [_primary_term] => 1)
      

      on brower exec ‘Localhost/home/get’ , then there is return:

      Array(
          [_index] => my_index
          [_type] => my_type
          [_id] => my_id
          [_version] => 2
          [_seq_no] => 1
          [_primary_term] => 1
          [found] => 1
          [_source] => Array(
                  [testField] => abc
              ))
      

      on brower exec ‘Localhost/home/getSources’ , then there is return:

      Array ( [testField] => abc )
      

      on brower exec ‘Localhost/home/search’ , then there is return:

      Array(
          [took] => 13
          [timed_out] => 
          [_shards] => Array(
                  [total] => 1
                  [successful] => 1
                  [skipped] => 0
                  [failed] => 0 )
          [hits] => Array (
                  [total] => Array (
                          [value] => 1
                          [relation] => eq )
                  [max_score] => 0.2876821
                  [hits] => Array (
                          [0] => Array (
                                  [_index] => my_index
                                  [_type] => my_type
                                  [_id] => my_id
                                  [_score] => 0.2876821
                                  [_source] => Array (
                                          [testField] => abc )))))
      

      on brower exec ‘Localhost/home/delete’ , then there is return: (retry exec ,it will shows 404)

      Array (
          [_index] => my_index
          [_type] => my_type
          [_id] => my_id
          [_version] => 3
          [result] => deleted
          [_shards] => Array (
                  [total] => 2
                  [successful] => 1
                  [failed] => 0 )
          [_seq_no] => 2
          [_primary_term] => 1)
      

      on brower exec ‘Localhost/home/deleteDoc’ , then there is return:

      Array ( [acknowledged] => 1 )
      

      on brower exec ‘Localhost/home/createDoc’ , then there is return:

      Array(
          [acknowledged] => 1
          [shards_acknowledged] => 1
          [index] => my_index )
      

    二、配置

    2.1 host配置

    2.1.1 inline host 配置

    2.1.2 extend host 配置

    2.2 认证与加密

    2.3 设置重连次数

    2.4 开启日志

    Elasticsearch-PHP 支持日志记录,但由于性能原因,所以默认没有开启。如果你希望开启日志,你就要选择一个日志记录工具并安装它,然后在客户端中开启日志。推荐使用 Monolog,不过任何实现 PSR/Log 接口的日志记录工具都可以使用。

    你会发现在安装 elasticsearch-php 时会建议安装 Monolog。为了使用 Monolog,请把它加入 composer.json

    "monolog/monolog": "~1.0"
    

    然后用 composer 更新

    一旦安装好 Monolog(或其他日志记录工具),你就要创建一个日志对象并且注入到客户端中。 ClientBuilder 对象有一个静态方法来构建一个通用的 Monolog-based 日志对象。你只需要提供存放日志路径就行:

    也可以指定记录的日志级别:

    // set severity with second parameter (parameter is not must)
    $logger = ClientBuilder::defaultLogger('path/to/your.log', Logger::INFO);
    
    $client = ClientBuilder::create()       
                ->setLogger($logger)        
                ->build();
    

    defaultLogger() 方法只是一个辅助方法,不要求你使用它。你可以自己创建日志对象,然后注入

    2.5 配置 http handler

    2.6 设置连接池

    2.7 设置选择器

    2.8 设置序列化

    2.9 自定义 connectFoctoryconnectFactory

    2.10 设置闭包(endpoint)

    2.11 从hash配置中创建客户端

    3. 按请求配置

    3.1 忽略异常

    Elasticsearch-PHP 的类库是会对普通的问题抛出异常的。这些异常跟 Elasticsearch 返回的 HTTP 响应码一一对应。例如,获取一个不存在的文档会抛出 MissingDocument404Exception

    异常对于处理一些问题(如找不到文档、语法错误、版本冲突等)十分有用。但是有时候你只是想要处理返回的数据而不想捕获异常。

    如果你想忽略异常,你可以配置 ignore 参数。ignore 参数可以接收字符串也可以接收数组

    你可以通过数组的方式指定忽略多个 HTTP 状态码:

    $client = ClientBuilder::create()->build();
    $params = [
        'index'  => 'test_missing',
        'type'   => 'test',
        'client' => [ 'ignore' => [400, 404] ] 
    ];
    echo $client->get($params);
    

    注意,返回的数据是字符串格式,而不是 JSON 数据。而在第一个示例中返回的是 JSON 数据,客户端会 decode 该 JSON 数据为数组。一旦客户端无法得知返回的异常数据格式,客户端就不会 decode 返回结果。

    3.2 自定义查询参数

    有时候你要自己提供自定义参数,比如为第三方插件或代理提供认证 token。在 Elasticsearch-php 的白名单中存储着所有的查询参数,这是为了防止你指定一个参数,而 Elasticsearch 却不接收。

    如果你要自定义参数,你就要忽略掉这种白名单机制。为了达到这种效果,请增加 custom 参数:

    $client = ClientBuilder::create()->build();
    
    $params = [
        'index' => 'test',
        'type' => 'test',
        'id' => 1,
        'parent' => 'abc', // white-listed Elasticsearch parameter
        'client' => [
            'custom' => [
                'customToken' => 'abc', 
                'otherToken' => 123
            ]
        ]
    ];
    $exists = $client->exists($params);
    

    注:‘customToken’ => ‘abc’, // user-defined, not white listed, not checked

    3.3 返回详细输出

    客户端默认只返回响应体body数据。如果你需要更多信息(如头信息、相应状态码等),你可以让客户端返回更多详细信息。通过 verbose 参数可以开启这个功能。

    $client = ClientBuilder::create()->build();
    
    $params = [
        'index' => 'test',
        'type' => 'test',
        'id' => 1,
        'client' => [
            'verbose' => true
        ]
    ];
    $response = $client->get($params);
    print_r($response);
    

    系统将返回 [transfer_stats,curl,effective_url,headers,status,reason,body] 的信息

    3.4 CURL超时设置

    通过 timeoutconnect_timeout 参数可以配置每个请求的 Curl 超时时间。这个配置主要是控制客户端的超时时间。 connect_timeout 参数控制在连接阶段完成前,curl 的等待时间。而 timeout 参数则控制整个请求完成前,最多等待多长时间。

    如果超过超时时间,curl 会关闭连接并返回一个致命错误。两个参数都要用 作为参数。

    注意:客户端超时并 意味着 Elasticsearch 中止请求。Elasticsearch 会继续执行请求直到请求完成。在慢查询或是 bulk 请求下,操作会在后台继续执行,对客户端来说这些动作是隐蔽的。如果客户端在超时后立即断开连接,然后又立刻发送另外一个请求。由于客户端没有处理服务端回压(译者注:这里国内翻译成背压,但是知乎有文章指出这个翻译不够精准,会造成程序员难以理解,所以这里翻译成回压)的机制,这有可能会造成服务端过载。遇到这种情况,你会发现线程池队列会慢慢变大,当队列超出负荷,Elasticsearch 会发送 EsRejectedExecutionException 的异常。

    $client = ClientBuilder::create()->build();
    
    $params = [
        'index' => 'test',
        'type' => 'test',
        'id' => 1,
        'client' => [
            'timeout' => 10,        // ten second timeout
            'connect_timeout' => 10
        ]
    ];
    $response = $client->get($params);
    

    3.5 future 异步模式

    客户端支持异步方式批量发送请求。通过 client 选项的 future 参数可以开启(HTTP handler 要支持异步模式):

    $client = ClientBuilder::create()->build();
    
    $params = [
        'index' => 'test',
        'type' => 'test',
        'id' => 1,
        'client' => [
            'future' => 'lazy'
        ]
    ];
    $future = $client->get($params);
    $results = $future->wait();       // resolve the future
    

    Future 模式有两个参数可选: truelazy 。关于异步执行方法以及如何处理返回结果的详情,请到 Future 模式 中查看。

    3.6 SSL加密

    在创建客户端时,一般需要指定 SSL 配置,因为通常所有的请求都需要加密(查询 安全一节获取更多详情)。然而,在每个请求中配置 SSL 加密也是有可能的。例如,如果你需要在某个特定的请求中使用自签名证书,你可以通过在 client 选项中配置 verify 参数:

    $client = ClientBuilder::create()->build();
    
    $params = [
        'index' => 'test',
        'type' => 'test',
        'id' => 1,
        'client' => [
            'verify' => 'path/to/cacert.pem'      //Use a self-signed certificate
        ]
    ];
    $result = $client->get($params);
    
  • 相关阅读:
    前后端分离
    分库分表之终极设计方案
    题解-CF1491
    题解-ARC113
    题解-CF578D LCS Again
    团队冲刺第二阶段5
    团队冲刺第二阶段4
    团队冲刺第二阶段3
    团队冲刺第二阶段2
    团队冲刺第二阶段1
  • 原文地址:https://www.cnblogs.com/daozhangblog/p/12446321.html
Copyright © 2020-2023  润新知