PHP 8.6需要按稳定快照遍历Elasticsearch查询结果时,可先打开PIT,再用每页最后一条记录的sort值作为search_after。整个遍历保持相同查询和排序,使用响应返回的最新pit_id,并在结束或异常时关闭PIT,避免深层from分页和并发写入造成结果漂移。
明确快照与排序
使用支持pit的elasticsearch版本、固定索引和只读查询权限。示例直接调用rest接口,避免混用不同大版本php客户端签名;es_url只允许管理员配置的https地址。
composer require guzzlehttp/guzzle:"^7.0"
PIT会保留搜索上下文并占用资源。示例按_shard_doc排序遍历固定快照,不提供业务相关性排序;如需按时间排序,所有页须保持同一套字段和缺失值规则。

Search after:官方文档示例
循环请求并传递游标
保存为scan.php。处理结果时逐条输出稳定ID;实际导出可改为写文件,但不要重新聚合全部命中到内存数组。
<?php
require __DIR__.'/vendor/autoload.php';
use GuzzleHttp\Client;
$base = rtrim(getenv('ES_URL') ?: '', '/');
$key = getenv('ES_API_KEY');
if (parse_url($base, PHP_URL_SCHEME) !== 'https' || !$key)
throw new RuntimeException('Missing trusted Elasticsearch configuration');
$http = new Client(['base_uri' => $base.'/', 'timeout' => 20,
'headers' => ['Authorization' => 'ApiKey '.$key]]);
function requestJson(Client $c, string $method, string $path, array $options = []): array {
$r = $c->request($method, $path, $options);
return json_decode((string) $r->getBody(), true, 64, JSON_THROW_ON_ERROR);
}
$pit = requestJson($http, 'POST', 'logs-example/_pit?keep_alive=1m')['id'];
$after = null;
try {
while (true) {
$query = ['size' => 500, 'query' => ['match_all' => new stdClass()],
'pit' => ['id' => $pit, 'keep_alive' => '1m'],
'sort' => [['_shard_doc' => 'asc']], 'track_total_hits' => false];
if ($after !== null) $query['search_after'] = $after;
$page = requestJson($http, 'POST', '_search', ['json' => $query]);
$pit = $page['pit_id'] ?? $pit;
if (!empty($page['timed_out']) || ($page['_shards']['failed'] ?? 0) > 0)
throw new RuntimeException('Incomplete search response');
$hits = $page['hits']['hits'] ?? [];
if ($hits === []) break;
foreach ($hits as $hit) echo $hit['_id'], "\n";
$after = $hits[array_key_last($hits)]['sort'];
}
} finally {
requestJson($http, 'DELETE', '_pit', ['json' => ['id' => $pit]]);
}把logs-example改为授权的实际索引。搜索请求已经携带PIT时不再在_search路径指定索引;续页使用完整sort数组,而不是仅使用最后一条_id。
使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。

Search after:官方文档示例
区分快照失效和可续导出
keep_alive只需覆盖两次请求间隔,每次请求续期。若处理一页耗时较久,应调整窗口或缩小每页处理量。PIT失效后不能把旧search_after随便接到新快照上继续宣称无缺漏。
立即学习“PHP免费学习笔记(深入)”;
完整导出还需要记录已写文件与业务检查点。finally中的关闭失败也要记录,依靠过期回收只作为兜底;本例不把搜索超时或部分分片失败当作正常完成。


















