client = ClientBuilder::create()->setHosts([self::ES_HOST_NAME])->build(); } private function __clone() { } public static function getInstance(){ if (is_null(self::$instance)) { self::$instance = new self(); } return self::$instance; } public function existsIndex(String $index_name) { $params = [ 'index' => $index_name ]; return $this->client->indices()->exists($params); } /** * 创建索引 */ public function createIndex(String $index_name, array $mapping = []): array { if ($this->existsIndex($index_name)) { throw new Exception('索引已存在'. $index_name); } //只能创建一次 $params = [ 'index' => $index_name, 'body' => [ 'settings' => [ 'number_of_shards' => 5, 'number_of_replicas' => 1 ], 'mappings' => $mapping ] ]; return $this->client->indices()->create($params); } /** * 删除索引 */ public function deleteIndex(String $index_name = ''): array{ $params = ['index' => $index_name]; return $this->client->indices()->delete($params); } /** * 添加文档 * @param $id * @param $doc ['id'=>100, 'title'=>'phone'] * @param string $index_name * @param string $type_name */ public function addDoc($id, $doc, string $index_name = 'gyx_ik', string $type_name = '_doc'): array { $params = [ 'index' => $index_name, 'type' => $type_name, 'id' => $id, 'body' => $doc ]; return $this->client->index($params); } /** * 判断文档存在 * @param int $id * @param string $index_name * @param string $type_name * @return bool */ public function existsDoc(int $id = 1, string $index_name = 'gyx_ik', string $type_name = '_doc'): bool { $params = [ 'index' => $index_name, 'type' => $type_name, 'id' => $id ]; return $this->client->exists($params); } /** * 获取文档 * @param int $id * @param string $index_name * @param string $type_name * @return array */ public function getDoc(int $id = 1, string $index_name = 'gyx_ik', string $type_name = '_doc'): array { $params = [ 'index' => $index_name, 'type' => $type_name, 'id' => $id ]; return $this->client->get($params); } /** * 更新文档 * @param int $id * @param string $index_name * @param string $type_name * @param array $body * @return array */ public function updateDoc(int $id = 1, array $body = [], string $index_name = 'gyx_ik', string $type_name = '_doc'): array { // 可以灵活添加新字段,最好不要乱添加 $params = [ 'index' => $index_name, 'type' => $type_name, 'id' => $id, 'body' => $body ]; return $this->client->update($params); } /** * 删除文档 * @param int $id * @param string $index_name * @param string $type_name * @return array */ public function deleteDoc(int $id = 1, string $index_name = 'gyx_ik', string $type_name = '_doc'): array { $params = [ 'index' => $index_name, 'type' => $type_name, 'id' => $id ]; return $this->client->delete($params); } /** * 搜索文档:分页,排序,权重,过滤 * @param string $index_name * @param string $type_name * @param array $body * @return array */ public function searchDoc(array $body = [], string $index_name = "gyx_ik", string $type_name = "_doc"): array { $params = [ 'index' => $index_name, 'type' => $type_name, 'body' => $body ]; return $this->client->search($params); } }