1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- <?php
- namespace App\Service;
- use Elasticsearch\ClientBuilder;
- use function Hyperf\Support\retry;
- class ElasticsearchService
- {
- protected $client;
- public function __construct()
- {
- // 使用 ClientBuilder 创建客户端实例
- $this->client = ClientBuilder::create()->build();
- }
- public function createIndex()
- {
- $info = $this->client->info();
- $params = [
- 'index' => 'articles',
- 'body' => [
- 'mappings' => [
- 'properties' => [
- 'id' => ['type' => 'long'],
- 'catid' => ['type' => 'integer'],
- 'level' => ['type' => 'integer'],
- 'title' => ['type' => 'text'],
- 'introduce' => ['type' => 'text'],
- 'tag' => ['type' => 'keyword'],
- 'keyword' => ['type' => 'text'],
- 'author' => ['type' => 'keyword'],
- 'copyfrom' => ['type' => 'text'],
- 'fromurl' => ['type' => 'text'],
- 'hits' => ['type' => 'integer'],
- 'ip' => ['type' => 'keyword'],
- 'status' => ['type' => 'integer'],
- 'islink' => ['type' => 'integer'],
- 'linkurl' => ['type' => 'text'],
- 'imgurl' => ['type' => 'text'],
- 'admin_user_id' => ['type' => 'integer'],
- 'cat_arr_id' => ['type' => 'text'],
- 'created_at' => ['type' => 'date'],
- 'updated_at' => ['type' => 'date'],
- 'is_original' => ['type' => 'integer'],
- 'content' => ['type' => 'text'],
- ],
- ],
- ],
- ];
- try {
- var_dump($this->client->indices(), '=============1=========1=================='); // 调试响应对象
- $response = $this->client->indices()->create($params);
- var_dump($response, '======================1=================='); // 调试响应对象
- return $response;
- } catch (\Exception $e) {
- // 处理异常情况
- throw new \RuntimeException("创建索引失败: " . $e->getMessage(), 0, $e);
- }
- }
- public function indexExists($index)
- {
- try {
- return $this->client->indices()->exists(['index' => $index]);
- } catch (\Exception $e) {
- throw new \RuntimeException("检查索引是否存在失败: " . $e->getMessage(), 0, $e);
- }
- }
- }
|