'','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; } }