elasticsearch-php 核心操作实战指南:索引管理、搜索查询与文档增删改

原创2026-10-12 21:49:241,613 阅读
文章标签:搜索引擎后端

elasticsearch-php 核心操作实战指南:索引管理、搜索查询与文档增删改

本篇指南基于 elasticsearch-php(官方 Elasticsearch PHP 客户端)的 Operations 文档 展开,系统讲解通过 $client 对象完成索引生命周期管理、Query DSL 搜索、单文档/批量写入、实时读取、更新与删除等全部核心操作。读完本文,你将掌握客户端方法命名与 REST 端点的对应规律、参数数组与 JSON 请求体的转换技巧,并能直接照抄文中的完整代码模板接入自己的业务项目。

客户端结构:方法如何对应 REST 端点

elasticsearch-php 的设计理念非常直观:方法的命名与 Elasticsearch REST 端点一一对应。例如 REST 的 PUT /my_index(创建索引)对应 $client->indices()->create(),GET /my_index/_search(搜索)对应 $client->search()。因此,熟悉 Elasticsearch REST API 的开发者几乎可以零成本迁移到 PHP 客户端。

核心操作(索引文档、搜索、获取、更新、删除)都直接挂在 $client 根对象上;而索引与集群管理则分别位于 $client->indices() 与 $client->cluster() 两个命名空间对象下。从源码结构看,这一划分由 NamespaceTrait 统一实现:indices()、cluster()、cat()、ml()、security() 等数十个方法采用懒加载单例模式,首次调用时创建对应的端点对象并缓存在 $this->namespace 数组中,后续调用直接复用。

同时,客户端特意为 IDE 自动补全做了优化:所有核心操作(indexing、searching、getting 等)都能在 $client 对象上直接列出,索引与集群管理则集中在 $client->indices() 和 $client->cluster() 对象下。实际的方法清单可以在 src/Traits/ClientEndpointsTrait.php(根级端点)与 src/Endpoints/Indices.php(索引命名空间)中查看,每个方法都以 PHPDoc 形式标注了全部参数说明与必填项。

构建客户端

所有操作的起点都是通过 ClientBuilder 构建一个客户端实例:

use Elastic\Elasticsearch\ClientBuilder;

$client = ClientBuilder::create()->build();

如果需要连接远程集群,可以使用 setHosts() 指定节点地址,例如:

$client = ClientBuilder::create()
    ->setHosts(['https://localhost:9200'])
    ->build();

更完整的连接、认证与 Cloud 配置可参考 connecting.md 与 configuration.md。

索引管理操作

索引管理操作负责集群中索引的创建、删除,以及 mappings/settings 的更新。这些操作全部位于 indices 命名空间,与根客户端上的其他方法相互独立。

创建索引

创建一个最简单的索引:

$client = ClientBuilder::create()->build();
$params = [
    'index' => 'my_index'
];

// Create the index
$response = $client->indices()->create($params);

你可以指定 Create Index API 支持的任何参数。所有本应放在请求体(request body)中的参数,统一放在 body 键下:

$client = ClientBuilder::create()->build();
$params = [
    'index' => 'my_index',
    'body' => [
        'settings' => [
            'number_of_shards' => 3,
            'number_of_replicas' => 2
        ],
        'mappings' => [
            '_source' => [
                'enabled' => true
            ],
            'properties' => [
                'first_name' => [
                    'type' => 'keyword'
                ],
                'age' => [
                    'type' => 'integer'
                ]
            ]
        ]
    ]
];

// Create the index with mappings and settings now
$response = $client->indices()->create($params);

从 Indices.php 的 create() 实现 可以看出,该方法会校验 index 为必填参数,并将 body 作为 PUT 请求体发送到 /{index} 端点,其余 URL 参数(如 wait_for_active_shards、timeout、master_timeout、pretty 等)则通过 addQueryString() 拼接到查询字符串中。在创建索引时,若 body 未提供也能创建成功——此时 Elasticsearch 会使用默认 settings 和动态 mapping。

创建索引(进阶示例)

下面的示例展示了如何定义 analyzer、tokenizer、filter 与索引 settings。它与上一个示例本质相同,但更贴近真实生产环境——因为这种嵌套语法很容易写错:

$params = [
    'index' => 'reuters',
    'body' => [
        'settings' => [
            'number_of_shards' => 1,
            'number_of_replicas' => 0,
            'analysis' => [
                'filter' => [
                    'shingle' => [
                        'type' => 'shingle'
                    ]
                ],
                'char_filter' => [
                    'pre_negs' => [
                        'type' => 'pattern_replace',
                        'pattern' => '(\\w+)\\s+((?i:never|no|nothing|nowhere|noone|none|not|havent|hasnt|hadnt|cant|couldnt|shouldnt|wont|wouldnt|dont|doesnt|didnt|isnt|arent|aint))\\b',
                        'replacement' => '~$1 $2'
                    ],
                    'post_negs' => [
                        'type' => 'pattern_replace',
                        'pattern' => '\\b((?i:never|no|nothing|nowhere|noone|none|not|havent|hasnt|hadnt|cant|couldnt|shouldnt|wont|wouldnt|dont|doesnt|didnt|isnt|arent|aint))\\s+(\\w+)',
                        'replacement' => '$1 ~$2'
                    ]
                ],
                'analyzer' => [
                    'reuters' => [
                        'type' => 'custom',
                        'tokenizer' => 'standard',
                        'filter' => ['lowercase', 'stop', 'kstem']
                    ]
                ]
            ]
        ],
        'mappings' => [
            'properties' => [
                'title' => [
                    'type' => 'text',
                    'analyzer' => 'reuters',
                    'copy_to' => 'combined'
                ],
                'body' => [
                    'type' => 'text',
                    'analyzer' => 'reuters',
                    'copy_to' => 'combined'
                ],
                'combined' => [
                    'type' => 'text',
                    'analyzer' => 'reuters'
                ],
                'topics' => [
                    'type' => 'keyword'
                ],
                'places' => [
                    'type' => 'keyword'
                ]
            ]
        ]
    ]
];
$client->indices()->create($params);

这个示例中嵌套结构的关键点:

  • 顶层的 settings 包含索引本身的配置(分片数、副本数等),以及 analyzer 定义;
  • analysis 嵌套在 settings 内部,用于放置 tokenizer、filter、char filter 与 analyzer;
  • mappings 同样是 settings 之外的顶层元素(注意:示例注释中称其"嵌套在 settings 内部",实际它与 settings 平级),包含各字段的映射定义。

char_filter 中使用的 pattern_replace 是一个常见的否定词处理技巧:将 "not good" 这类否定短语改写为 ~good,以便后续分析器正确理解否定语义,这是舆情/文本分析类场景中值得借鉴的配置。

删除索引

删除索引非常简单:

$params = ['index' => 'my_index'];
$response = $client->indices()->delete($params);

从 delete() 实现 看,它同样校验 index 必填,并向 /{index} 发送 DELETE 请求,同时支持 ignore_unavailable、allow_no_indices、expand_wildcards 等查询参数——这意味着你可以用 _all 或 * 通配符删除多个索引,但请谨慎操作。

PUT Settings API

PUT Settings API 允许修改索引中所有动态的 settings:

$params = [
    'index' => 'my_index',
    'body' => [
        'settings' => [
            'number_of_replicas' => 0,
            'refresh_interval' => -1
        ]
    ]
];

$response = $client->indices()->putSettings($params);

其中 number_of_replicas 表示副本数,refresh_interval => -1 表示禁用自动刷新(适用于大批量写入场景,写入完成后可改回默认值并手动触发 refresh)。

GET Settings API

GET Settings API 用于查看一个或多个索引当前的配置:

// Get settings for one index
$params = ['index' => 'my_index'];
$response = $client->indices()->getSettings($params);

// Get settings for several indices
$params = [
    'index' => [ 'my_index', 'my_index2' ]
];
$response = $client->indices()->getSettings($params);

PUT Mappings API

PUT Mappings API 允许修改或扩展现有索引的 mapping(注意:已存在的字段类型无法修改,只能新增字段):

$params = [
    'index' => 'my_index',
    'body' => [
        '_source' => [
            'enabled' => true
        ],
        'properties' => [
            'first_name' => [
                'type' => 'text',
                'analyzer' => 'standard'
            ],
            'age' => [
                'type' => 'integer'
            ]
        ]
    ]
];

// Update the index mapping
$client->indices()->putMapping($params);

GET Mappings API

GET Mappings API 返回索引的 mapping 详情,可按需指定一个或多个索引:

// Get mappings for all indices
$response = $client->indices()->getMapping();

// Get mappings in 'my_index'
$params = ['index' => 'my_index'];
$response = $client->indices()->getMapping($params);

// Get mappings for two indices
$params = [
    'index' => [ 'my_index', 'my_index2' ]
];
$response = $client->indices()->getMapping($params);

indices 命名空间中的其他 API

indices 命名空间还包含大量管理 API(添加/删除模板、flush segments、关闭索引等)。如果你的 IDE 支持自动补全,只需输入:

$client->indices()->

即可浏览可用方法列表。也可以直接查看 \Elasticsearch\Namespaces\Indices.php(本仓库中对应 src/Endpoints/Indices.php)获取完整的方法清单及每个方法的 PHPDoc 参数说明。

搜索操作

搜索是 Elasticsearch 的核心能力,客户端为你开放了 REST API 暴露的每一个查询与参数,并尽可能遵循命名规范。

Match 查询

先用标准 curl 表示一个 match 查询:

curl -XGET 'localhost:9200/my_index/_search' -d '{
    "query" : {
        "match" : {
            "testField" : "abc"
        }
    }
}'

在客户端中构造同样的查询:

$params = [
    'index' => 'my_index',
    'body'  => [
        'query' => [
            'match' => [
                'testField' => 'abc'
            ]
        ]
    ]
];

$results = $client->search($params);

注意 PHP 数组的结构与布局和 JSON 请求体完全一致,这使得将 JSON 示例转换为 PHP 非常简单。对于复杂示例,可以先把数组重新编码回 JSON 进行核对:

$params = [
    'index' => 'my_index',
    'body'  => [
        'query' => [
            'match' => [
                'testField' => 'abc'
            ]
        ]
    ]
];

print_r(json_encode($params['body']));

输出结果:

{"query":{"match":{"testField":"abc"}}}

使用原生 JSON 字符串

在测试或从其他系统迁移时,直接使用原生 JSON 会更方便。你可以在 body 中传入 JSON 字符串,客户端会自动识别:

$json = '{
    "query" : {
        "match" : {
            "testField" : "abc"
        }
    }
}';

$params = [
    'index' => 'my_index',
    'body'  => $json
];

$results = $client->search($params);

从 ClientEndpointsTrait 的 search() 实现 可以看到,body 参数被直接传给 createRequest(),原生 JSON 字符串与 PHP 数组都受支持。搜索结果的格式与 Elasticsearch 搜索响应一致,唯一的区别是 JSON 响应被反序列化回 PHP 数组。处理搜索结果就像遍历数组一样简单:

$params = [
    'index' => 'my_index',
    'body'  => [
        'query' => [
            'match' => [
                'testField' => 'abc'
            ]
        ]
    ]
];

$results = $client->search($params);

$milliseconds = $results['took'];
$maxScore     = $results['hits']['max_score'];

$score = $results['hits']['hits'][0]['_score'];
$doc   = $results['hits']['hits'][0]['_source'];

这种数组访问能力来自 Response\Elasticsearch 类:它实现了 ArrayAccess 接口,offsetGet() 会调用 asArray() 将响应体(JSON、NDJSON、CSV 等格式)反序列化为数组;同时也可以通过 asObject() 以对象属性方式访问,或用 asString() 获取原始字符串。注意该响应对象是只读的,写入操作会抛出 ArrayAccessException。对于 4xx/5xx 状态码,客户端默认抛出 ClientResponseException / ServerResponseException 异常。

Bool 查询

使用客户端可以轻松构造 bool 查询。例如下面的查询:

curl -XGET 'localhost:9200/my_index/_search' -d '{
    "query" : {
        "bool" : {
            "must": [
                {
                    "match" : { "testField" : "abc" }
                },
                {
                    "match" : { "testField2" : "xyz" }
                }
            ]
        }
    }
}'

在 PHP 中结构如下(注意方括号的位置):

$params = [
    'index' => 'my_index',
    'body'  => [
        'query' => [
            'bool' => [
                'must' => [
                    [ 'match' => [ 'testField' => 'abc' ] ],
                    [ 'match' => [ 'testField2' => 'xyz' ] ],
                ]
            ]
        ]
    ]
];

$results = $client->search($params);

注意 must 子句接受的是数组的数组。内部会被序列化为 JSON 对象数组,最终输出与 curl 示例完全一致。关于 PHP 中 JSON 数组与对象的更多细节,见 php_json_objects.md。

更复杂的示例:filter + should

构造一个同时包含 filter 和 query 的 bool 查询,这是 Elasticsearch 查询中非常常见的组合:

curl 版本:

curl -XGET 'localhost:9200/my_index/_search' -d '{
    "query" : {
        "bool" : {
            "filter" : {
                "term" : { "my_field" : "abc" }
            },
            "should" : {
                "match" : { "my_other_field" : "xyz" }
            }
        }
    }
}'

PHP 版本:

$params = [
    'index' => 'my_index',
    'body'  => [
        'query' => [
            'bool' => [
                'filter' => [
                    'term' => [ 'my_field' => 'abc' ]
                ],
                'should' => [
                    'match' => [ 'my_other_field' => 'xyz' ]
                ]
            ]
        ]
    ]
];

$results = $client->search($params);

filter 子句只做过滤不参与评分(且结果可被缓存),should 子句用于提升相关性,这种组合在"精确过滤 + 相关度排序"场景中性能与效果俱佳。

滚动(Scroll)分页

Scroll 功能用于批量分页大量文档,例如导出某个用户的所有文档。它比普通搜索更高效,因为无需维护昂贵的优先队列来排序所有文档。

Scroll 的原理是维护索引的一个"时间点快照"(point-in-time view),基于该快照逐页读取。即使后台有持续的索引/更新/删除操作,这个窗口也能保证分页的一致性。流程是:先发起带 scroll 参数的搜索请求,返回第一批文档和一个 scroll_id,之后用 scroll_id 持续翻页,直到游标耗尽。

这是一个可以作为高级操作模板的完整示例:

$client = ClientBuilder::create()->build();
$params = [
    'scroll' => '30s',          // 两次 scroll 请求之间的间隔,应设置得较小!
    'size'   => 50,             // 每个分片返回多少条结果
    'index'  => 'my_index',
    'body'   => [
        'query' => [
            'match_all' => new \stdClass()   // 注意:空对象必须用 stdClass 表示 {}
        ]
    ]
];

// 执行搜索,响应中包含第一批文档和 scroll_id
$response = $client->search($params);

// 循环直到 scroll "游标" 耗尽
while (isset($response['hits']['hits']) && count($response['hits']['hits']) > 0) {

    // **
    // 在这里处理 $response['hits']['hits'] 数组
    // **

    // 获取新的 scroll_id
    // 必须总是刷新 _scroll_id!它有时会变化
    $scroll_id = $response['_scroll_id'];

    // 发起 Scroll 请求并继续
    $response = $client->scroll([
        'body' => [
            'scroll_id' => $scroll_id,  // 使用之前获取的 _scroll_id
            'scroll'    => '30s'        // 相同的超时窗口
        ]
    ]);
}

两个关键细节值得注意:

  • 必须始终刷新 _scroll_id:Elasticsearch 返回的 _scroll_id 可能在翻页过程中发生变化,务必每次都从最新响应中重新获取;
  • 空对象用 \stdClass:match_all 在 JSON 中是 {},在 PHP 数组中必须用 new \stdClass()(或 new \ArrayObject([]),集成测试中也有类似用法)表示,否则会序列化为空数组 [],语义完全不同。

另外,文档搜索完毕后,建议调用 $client->clearScroll() 显式清理 scroll 上下文以释放服务端资源(该端点实现见 clearScroll())。更多分页方式可参考官方分页文档,若需要"按页/按条"自动迭代的封装,客户端还提供了 SearchResponseIterator 与 SearchHitIterator 两个迭代器助手(用法见 iterators.md)。

索引文档

向 Elasticsearch 添加文档即"索引 JSON 文档"。由于 PHP 关联数组可以天然地编码为 JSON,因此只需构造关联数组交给客户端即可。

单文档索引

索引单条文档时,可以显式提供 ID,也可以让 Elasticsearch 自动生成:

$params = [
    'index' => 'my_index',
    'id'    => 'my_id',
    'body'  => [ 'testField' => 'abc']
];

// 文档将被索引到 my_index/_doc/my_id
$response = $client->index($params);
$params = [
    'index' => 'my_index',
    'body'  => [ 'testField' => 'abc']
];

// 文档将被索引到 my_index/_doc/<autogenerated ID>
$response = $client->index($params);

从 index() 实现 可以看到:提供 id 时走 PUT /{index}/_doc/{id}(指定 ID,若文档已存在则整体覆盖);不提供 id 时走 POST /{index}/_doc(自动生成 ID)。两种写法都校验 index 与 body 为必填参数。

如果需要设置其他参数(如 routing 路由),在数组中与 index 等并列传入即可。例如同时设置 routing 与 timestamp:

$params = [
    'index'     => 'my_index',
    'id'        => 'my_id',
    'routing'   => 'company_xyz',
    'timestamp' => strtotime("-1d"),
    'body'      => [ 'testField' => 'abc']
];

$response = $client->index($params);

routing 用于将文档路由到特定分片,对"按租户/用户隔离数据"的场景非常关键。timestamp 是自定义字段,会作为文档的一部分写入 _source。

Bulk 批量索引

Elasticsearch 的 bulk API 期望 JSON 的 action/metadata 对,以换行分隔。PHP 中的构造方式类似:先创建一个 action 数组对象(例如 index 对象),再创建文档 body 对象,对所有文档重复这一过程。

一个简单的例子:

for($i = 0; $i < 100; $i++) {
    $params['body'][] = [
        'index' => [
            '_index' => 'my_index',
        ]
    ];

    $params['body'][] = [
        'my_field'     => 'my_value',
        'second_field' => 'some more values'
    ];
}

$responses = $client->bulk($params);

实际场景中文档数往往远超单次 bulk 请求的合理负载,因此需要分批发送:

$params = ['body' => []];

for ($i = 1; $i <= 1234567; $i++) {
    $params['body'][] = [
        'index' => [
            '_index' => 'my_index',
            '_id'    => $i
        ]
    ];

    $params['body'][] = [
        'my_field'     => 'my_value',
        'second_field' => 'some more values'
    ];

    // 每 1000 条文档暂停并发送一次 bulk 请求
    if ($i % 1000 == 0) {
        $responses = $client->bulk($params);

        // 清空旧的 bulk 请求
        $params = ['body' => []];

        // 处理完毕后释放 bulk 响应以节省内存
        unset($responses);
    }
}

// 发送最后一批数据(如果存在)
if (!empty($params['body'])) {
    $responses = $client->bulk($params);
}

bulk() 端点实现 显示:请求体以 application/x-ndjson(NDJSON)格式发送,body 为必填参数;如果提供 index,则请求发送到 /{index}/_bulk,否则发送到 /_bulk。每批 1000 条是常见的经验值,可在实践中按文档大小与集群负载调整。集成测试 BulkTest.php 中提供了大量可直接运行的 bulk 写入与批量删除示例。

获取文档

Elasticsearch 提供实时 GET:一旦文档被索引且客户端收到确认,就可以立即从任意分片获取该文档。Get 操作通过完整的 index/type/id 路径请求:

$params = [
    'index' => 'my_index',
    'id'    => 'my_id'
];

// 获取 /my_index/_doc/my_id
$response = $client->get($params);

get() 实现 要求 id 与 index 均为必填参数,向 /{index}/_doc/{id} 发送 GET 请求。除了 get,客户端还提供 getSource()(仅取 _source)、exists()(HEAD 判断文档是否存在,返回布尔语义的 asBool())等变体,方便按需选用。

更新文档

更新文档有两种方式:完全替换现有文档内容,或仅对部分字段做局部更新(修改已有字段或新增字段)。

局部文档更新(Partial Update)

通过在 body 中指定 doc 实现局部更新,doc 中的字段会与现有文档合并:

$params = [
    'index' => 'my_index',
    'id'    => 'my_id',
    'body'  => [
        'doc' => [
            'new_field' => 'abc'
        ]
    ]
];

// 更新 /my_index/_doc/my_id
$response = $client->update($params);

脚本化文档更新(Scripted Update)

当需要执行脚本化更新时——例如计数器自增或向数组追加新值——需要提供脚本及通常的一组参数:

$params = [
    'index' => 'my_index',
    'id'    => 'my_id',
    'body'  => [
        'script' => 'ctx._source.counter += count',
        'params' => [
            'count' => 4
        ]
    ]
];

$response = $client->update($params);

脚本使用 Painless 语言(lang 参数默认即 painless),ctx._source 代表文档的 _source,params.count 从请求参数中取值,避免脚本硬编码。

Upsert 操作

Upsert 即"Update or Insert"。它会尝试运行更新脚本,但如果文档不存在(或要更新的字段不存在),则插入默认值:

$params = [
    'index' => 'my_index',
    'id'    => 'my_id',
    'body'  => [
        'script' => [
            'source' => 'ctx._source.counter += params.count',
            'params' => [
                'count' => 4
            ],
        ],
        'upsert' => [
            'counter' => 1
        ],
    ]
];

$response = $client->update($params);

这里 upsert 定义了文档不存在时的初始值 counter => 1,之后每次更新都会在现有值基础上加 4。这是实现"计数器/访问量统计"类需求的标准写法。从 update() 实现 看,id、index、body 均为必填参数,且支持 retry_on_conflict(冲突重试次数)、if_seq_no / if_primary_term(乐观锁)等并发控制参数。

删除文档

删除文档通过指定完整的 /index/_doc_/id 路径完成:

$params = [
    'index' => 'my_index',
    'id'    => 'my_id'
];

// 删除 /my_index/_doc_/my_id
$response = $client->delete($params);

delete() 实现 向 /{index}/_doc/{id} 发送 DELETE 请求,id 与 index 必填。需要按查询条件批量删除时,可使用 deleteByQuery()(对应 /_delete_by_query 端点,支持 conflicts、scroll_size、slices 等参数),这是清理过期数据的高效手段。

小结:从 REST 到 PHP 的映射规律

操作 REST 端点 PHP 调用
创建索引 PUT /my_index $client->indices()->create($params)
删除索引 DELETE /my_index $client->indices()->delete($params)
更新索引设置 PUT /my_index/_settings $client->indices()->putSettings($params)
查询索引设置 GET /my_index/_settings $client->indices()->getSettings($params)
更新 mapping PUT /my_index/_mapping $client->indices()->putMapping($params)
查询 mapping GET /my_index/_mapping $client->indices()->getMapping($params)
搜索 GET/POST /my_index/_search $client->search($params)
滚动分页 GET/POST /_search/scroll $client->scroll($params)
索引文档(指定 ID) PUT /my_index/_doc/my_id $client->index($params)
索引文档(自动 ID) POST /my_index/_doc $client->index($params)
批量操作 POST /my_index/_bulk $client->bulk($params)
获取文档 GET /my_index/_doc/my_id $client->get($params)
更新文档 POST /my_index/_update/my_id $client->update($params)
删除文档 DELETE /my_index/_doc/my_id $client->delete($params)

掌握以上规律后,Elasticsearch REST API 的任何端点都能在 src/Traits/ClientEndpointsTrait.php 与 src/Endpoints 目录中找到一一对应的 PHP 方法,并借助 PHPDoc 注释快速确认每个参数的语义与默认值。建议进一步阅读 indexing_documents.md、search_operations.md、getting_documents.md、updating_documents.md、deleting_documents.md 与 index_management.md 获取各主题的完整说明。

登录后查看全文
elasticsearch-php