123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121 |
- <?php namespace App\Servers\ElasticSearch\Lib;
- use Illuminate\Pagination\LengthAwarePaginator;
- use Illuminate\Pagination\Paginator;
- /**
- * ES Sql
- *
- * @author 刘相欣
- *
- */
- class Sql{
- // 查询属性
- private $query = ['index'=>'','type'=>'','body'=>[]];
- private $client = null;
- private $searchResult = null;
- /**
- * 指定索引
- *
- * @param \Elasticsearch\Client $client ES链接
- * @param String $index 索引名称
- * @param String $type 类型
- * @return $this
- *
- */
- public function __construct($client,$index,$type='_doc'){
- // 终端
- $this->client = $client;
- // 指定索引
- $this->query['index'] = $index;
- $this->query['type'] = $type;
- // 链式操作
- return $this;
- }
- /**
- * 忽略错误
- *
- * @param Array $ignore 忽略的错误代码
- *
- * @return $this
- */
- public function ignore( array $ignore=[400,401,403,404,408,409]){
- // 更新忽略错误
- $this->query['client'] = ['ignore' => $ignore];
- // 链式操作
- return $this;
- }
- /**
- * SQL查询
- *
- * @param String $query 查询sql语句
- * @param String $format 简短标头如json,yaml,smile,cbor,txt,csv,tsv
- * @param Array $body 更多参数
- * String $cursor 游标
- * Int $fetch_size 分页条数
- */
- public function sql($query,$body=[],$format='json'){
- // // 简短标头,如json,yaml,smile,cbor,txt,csv,tsv
- // $params = ['format'=>$format];
- // // 查询sql语句
- // $params['body']['query'] = $query;
- // // 游标
- // if( !empty($body['cursor']) ) $params['body']['cursor'] = $body['cursor'];
- // // 游标
- // if( !empty($body['fetch_size']) ) $params['body']['fetch_size'] = $body['fetch_size'];
- // 转换成参数
- $param = $this->translate($query);
- $this->query['body'] = $param;
-
- if( isset($param['fields']) ) $this->query['body']['_source'] = array_column($param['fields'],'field');
-
- unset($this->query['body']['fields']);
- // 查询结果
- $result = $this->client->search($this->query);
- dd($result);
- // 最终数据
- $data = [];
- // 循环获取数据
- foreach ($result['rows'] as $row) {
- // 重新赋值
- $temp = [];
- // 匹配字段
- foreach ($row as $key => $value) {
-
- $temp[$result['columns'][$key]['name']] = $value;
- }
- // 获取数据
- $data[] = $temp;
- }
- // 获取数据
- $data = ['data'=>$data];
- // 获取数据
- if( !empty($body['fetch_size']) ) $data['cursor'] = $result['cursor'];
- // 进行查询
- return $data;
- }
- /**
- * SQL转DSL查询
- *
- * @param String $query 查询sql语句
- *
- */
- public function translate($query){
- // 查询sql语句
- $params['body']['query'] = $query;
- // 查询结果
- $result = $this->client->sql()->translate($params);
- // 进行查询
- return $result;
- }
- }
|