作者 邓超

es 批量添加

  1 +<?php
  2 +
  3 +namespace Lib\Es;
  4 +
  5 +
  6 +/**
  7 + * 批量添加数据的类
  8 + * @author:dc
  9 + * @time 2025/8/6 16:37
  10 + * Class BulkData
  11 + * @package Lib\Es
  12 + */
  13 +class BulkData {
  14 +
  15 + /**
  16 + * @var string
  17 + */
  18 + private array $data = [];
  19 +
  20 + /**
  21 + * 添加数据
  22 + * @param string $index 必须全小写
  23 + * @param string $_id 指定文档id
  24 + * @param array $data
  25 + * @author:dc
  26 + * @time 2025/8/6 16:41
  27 + */
  28 + public function add(string $index,string $_id, array $data){
  29 + $index = strtolower($index);
  30 + if(empty($this->data[$index])){
  31 + $this->data[$index] = [];
  32 + }
  33 + $this->data[$index][] = [
  34 + '_id' => $_id,
  35 + '_source' => $data,
  36 + ];
  37 + }
  38 +
  39 +
  40 + /**
  41 + * 转换成es可识别的数据
  42 + * @return array
  43 + * @author:dc
  44 + * @time 2025/8/6 16:42
  45 + */
  46 + public function toParams():array {
  47 + $params = [];
  48 + foreach ($this->data as $index=>$item){
  49 + $params[] = [
  50 + 'index' => [
  51 + '_index' => $index,
  52 + '_id' => $item['_id']
  53 + ]
  54 + ];
  55 + $params[] = $item['_source'];
  56 + }
  57 + return $params;
  58 + }
  59 +
  60 +
  61 +
  62 +
  63 +}
@@ -281,6 +281,23 @@ class Es { @@ -281,6 +281,23 @@ class Es {
281 281
282 } 282 }
283 283
  284 + /**
  285 + * 批量添加数据
  286 + * @param BulkData $data
  287 + * data 格式要求
  288 + * @return array
  289 + * @throws \Elastic\Elasticsearch\Exception\ClientResponseException
  290 + * @throws \Elastic\Elasticsearch\Exception\ServerResponseException
  291 + * @author:dc
  292 + * @time 2025/8/6 16:36
  293 + */
  294 + public function bulk(BulkData $data){
  295 +
  296 + $res = $this->client->bulk($data->toParams());
  297 +
  298 + return $res->asArray();
  299 + }
  300 +
284 301
285 /** 302 /**
286 * @return \Elastic\Elasticsearch\Client 303 * @return \Elastic\Elasticsearch\Client