PHP操作ElasticSearch:如何向已创建的索引中插入文档数据
PHP 向 Elasticsearch 索引插入数据实现方案
前置依赖
确保你已经通过Composer安装了对应ES版本的官方PHP客户端,安装命令:composer require elasticsearch/elasticsearch
注意客户端主版本需要和你部署的Elasticsearch服务主版本保持一致,避免兼容性问题。
单条数据插入(适合用户创建时同步单条写入场景)
<?php require 'vendor/autoload.php'; // 初始化ES客户端,替换为你实际的ES服务地址 $client = Elasticsearch\ClientBuilder::create() ->setHosts(['http://127.0.0.1:9200']) ->build(); // 写入参数构造 $params = [ 'index' => 'my_index', // 和你创建的索引名保持一致 'id' => 'user_123', // 可选参数,自定义文档ID,不填则ES自动生成唯一ID,建议绑定用户ID方便后续查询 'body' => [ 'first_name' => '李', // 对应mapping的keyword类型,支持精确匹配 'age' => 28, // 对应mapping的integer类型,必须传入整型数值 'last_name' => '四' // 对应mapping的text类型,会自动分词 ] ]; // 执行写入操作 $response = $client->index($params); // 可通过返回结果判断是否写入成功 if ($response['result'] === 'created' || $response['result'] === 'updated') { echo "数据写入成功"; }
批量数据插入(适合批量导入用户场景)
如果需要一次性写入多条数据,使用bulk接口性能更高:
<?php require 'vendor/autoload.php'; $client = Elasticsearch\ClientBuilder::create() ->setHosts(['http://127.0.0.1:9200']) ->build(); $params = ['body' => []]; // 示例批量插入10条用户数据 $userList = [ ['id' => 1, 'first_name' => '王', 'age' => 22, 'last_name' => '五'], ['id' => 2, 'first_name' => '赵', 'age' => 30, 'last_name' => '六'], // 更多用户数据... ]; foreach ($userList as $user) { // 先添加写入操作标识 $params['body'][] = [ 'index' => [ '_index' => 'my_index', '_id' => 'user_' . $user['id'] ] ]; // 再添加用户文档内容 $params['body'][] = [ 'first_name' => $user['first_name'], 'age' => $user['age'], 'last_name' => $user['last_name'] ]; } // 执行批量写入 $response = $client->bulk($params); // 检查是否有写入错误 if (isset($response['errors']) && $response['errors'] === true) { echo "部分数据写入失败,可遍历response的items字段查看具体错误原因"; }
额外说明
如果你的Elasticsearch服务开启了身份认证,初始化客户端时需要补充认证配置,示例如下:
$client = Elasticsearch\ClientBuilder::create() ->setHosts(['https://你的ES服务地址:9200']) ->setBasicAuthentication('elastic', '你的ES登录密码') ->setSSLVerification(false) // 本地测试可关闭SSL验证,生产环境建议填写证书路径开启验证 ->build();
内容的提问来源于stack exchange,提问作者naive_user
相关产品推荐
相关产品推荐

