ElasticsearchService.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. namespace App\Service;
  3. use Elasticsearch\ClientBuilder;
  4. use function Hyperf\Support\retry;
  5. class ElasticsearchService
  6. {
  7. protected $client;
  8. public function __construct()
  9. {
  10. // 使用 ClientBuilder 创建客户端实例
  11. $this->client = ClientBuilder::create()->build();
  12. }
  13. public function createIndex()
  14. {
  15. $info = $this->client->info();
  16. $params = [
  17. 'index' => 'articles',
  18. 'body' => [
  19. 'mappings' => [
  20. 'properties' => [
  21. 'id' => ['type' => 'long'],
  22. 'catid' => ['type' => 'integer'],
  23. 'level' => ['type' => 'integer'],
  24. 'title' => ['type' => 'text'],
  25. 'introduce' => ['type' => 'text'],
  26. 'tag' => ['type' => 'keyword'],
  27. 'keyword' => ['type' => 'text'],
  28. 'author' => ['type' => 'keyword'],
  29. 'copyfrom' => ['type' => 'text'],
  30. 'fromurl' => ['type' => 'text'],
  31. 'hits' => ['type' => 'integer'],
  32. 'ip' => ['type' => 'keyword'],
  33. 'status' => ['type' => 'integer'],
  34. 'islink' => ['type' => 'integer'],
  35. 'linkurl' => ['type' => 'text'],
  36. 'imgurl' => ['type' => 'text'],
  37. 'admin_user_id' => ['type' => 'integer'],
  38. 'cat_arr_id' => ['type' => 'text'],
  39. 'created_at' => ['type' => 'date'],
  40. 'updated_at' => ['type' => 'date'],
  41. 'is_original' => ['type' => 'integer'],
  42. 'content' => ['type' => 'text'],
  43. ],
  44. ],
  45. ],
  46. ];
  47. try {
  48. var_dump($this->client->indices(), '=============1=========1=================='); // 调试响应对象
  49. $response = $this->client->indices()->create($params);
  50. var_dump($response, '======================1=================='); // 调试响应对象
  51. return $response;
  52. } catch (\Exception $e) {
  53. // 处理异常情况
  54. throw new \RuntimeException("创建索引失败: " . $e->getMessage(), 0, $e);
  55. }
  56. }
  57. public function indexExists($index)
  58. {
  59. try {
  60. return $this->client->indices()->exists(['index' => $index]);
  61. } catch (\Exception $e) {
  62. throw new \RuntimeException("检查索引是否存在失败: " . $e->getMessage(), 0, $e);
  63. }
  64. }
  65. }