elasticsearch的基本操作2


#创建索引,指定数据结构
PUT /novel
{
  "settings": {
    "analysis": {
      "analyzer": {
        "ik": {
          "type": "ik_max_word"
        }
      }
    }
  },
  "mappings": {
    "properties": {
      "name": {
        "type": "text",
        "analyzer": "ik_max_word"
      },
      "author": {
        "type": "keyword"
      },
      "descr": {
        "type": "text",
        "analyzer": "ik_max_word"
      },
      "count": {
        "type": "long"
      },
      "onsale": {
        "type": "date",
        "format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"
      }
    }
  }
}



#添加文档,自动生成id
POST /novel/_doc
{
  "name": "盘龙",
  "author": "我是西红柿",
  "count": 100000,
  "onsale": "2021-01-01",
  "descr": "嘻嘻哈哈嘻嘻哈啊信息哈哈"
}

#添加文档,设置id
POST /novel/_doc/2
{
  "name": "盘龙古",
  "author": "我是西红柿",
  "count": 100000,
  "onsale": "2021-01-01",
  "descr": "嘻嘻哈哈嘻嘻哈啊信息哈哈"
}



test2026-08-12 18:56


test2026-08-12 20:06


test2026-08-12 20:06


删除多个索引

$es->getClient()->indices()->delete([
    'index' => 'novel,book,article'
]);
删除所有索引(禁止生产环境)

$es->getClient()->indices()->delete([
    'index' => '_all'
]);
删除前先检查(推荐写法)

public function safeDelete(ElasticsearchService $es)
{
    $client = $es->getClient();

    if ($client->indices()->exists(['index' => 'novel'])) {
        return $client->indices()->delete(['index' => 'novel']);
    }

    return ['message' => '索引不存在'];
}
删除文档(不是索引)

$client->delete([
    'index' => 'novel',
    'id'    => '1'
]);
服务封装

<?php

declare(strict_types=1);

namespace AppService;

use HyperfElasticsearchClientBuilderFactory;

class ElasticsearchService
{
    private $client;

    public function __construct(ClientBuilderFactory $factory)
    {
        $this->client = $factory
            ->create()
            ->setHosts(['http://47.93.11.96:9200'])
            ->build();
    }

    public function getClient()
    {
        return $this->client;
    }
}

test2026-08-12 20:10


use HyperfElasticsearchClientBuilderFactory;
use AppServiceElasticsearchService;

test2026-08-12 20:11


composer require hyperf/elasticsearch

config/autoload/elasticsearch.php

<?php

return [
    'default' => [
        'hosts' => [
            'http://127.0.0.1:9200',
        ],
        'retries' => 2,
        'handler' => HyperfElasticsearchHandlerSwooleHandler::class,
    ],
];


test2026-08-12 20:13