如何在PHP中使用search()查询Elasticsearch的top_stories全量数据?
解决Elasticsearch PHP客户端获取top_stories数据的问题
首先,你之前用match查询空字符串的方式不对——match是用来匹配字段中的具体内容,空字符串并不能帮你拿到所有包含top_stories的文档。下面给你几种针对性的解决方案:
1. 获取所有包含top_stories字段的文档
如果你的需求是拿到所有存在top_stories字段的文档,用exists查询是最直接的方式:
// 假设你已经初始化了Elasticsearch客户端 $client = Elasticsearch\ClientBuilder::create()->build(); $params = [ 'index' => '你的索引名称', 'type' => 'curated', // ES7及以上版本可省略该参数,或设为'_doc' 'body' => [ 'query' => [ 'bool' => [ 'must' => [ 'exists' => [ 'field' => 'top_stories' ] ] ] ] ] ]; $response = $client->search($params); // 遍历结果提取top_stories数据 foreach ($response['hits']['hits'] as $hit) { $topStoriesContent = $hit['_source']['top_stories']; // 这里可以按需处理你的top_stories数据 }
2. 仅返回top_stories字段(无需完整文档)
如果不需要返回整个文档,只想拿到top_stories的内容,可以加上_source过滤,减少数据传输量:
$params = [ 'index' => '你的索引名称', 'type' => 'curated', '_source' => ['top_stories'], // 指定只返回top_stories字段 'body' => [ 'query' => [ 'exists' => [ 'field' => 'top_stories' ] ] ] ]; $response = $client->search($params);
为什么你的原代码返回空?
你之前写的$body['query']['bool']['should'] = ['match' => ['top_stories'=> '']];有两个核心问题:
match查询空字符串,只会匹配字段值本身为空的文档,而不是所有包含该字段的文档- 当
should数组里只有一个条件时,默认权重极低,几乎不会命中任何结果(除非手动调整minimum_should_match参数,但这完全没必要)
所以用exists查询才是符合你需求的正确方向。
额外提示
- 如果需要分页获取大量数据,可以在
params中添加size(每页数量)和from(起始位置)参数,或者使用scroll API实现高效批量查询 - 确保你的PHP客户端版本和Elasticsearch服务器版本兼容,避免因语法差异导致的问题
内容的提问来源于stack exchange,提问作者Nehil Mistry
相关产品推荐
相关产品推荐

