如何限制多索引搜索查询中每个索引的搜索结果?
How to limit search results from each index in a multi index search query?
我正在使用 Elasticsearch 6.3 版,我想跨多个查询 indices.Elasticsearch 支持这一点,我可以在 url 中将多个索引作为逗号分隔值,并在请求中使用一个查询body 并给出 size 参数来限制搜索结果的数量 returned.However 这限制了整体搜索结果的大小并且可能导致某些索引没有结果 - 所以我想从每个索引中获取前 n 个结果指数.
我尝试使用多重搜索 api (_msearch) 但似乎我必须为所有索引提供相同的查询和大小并且有效,但我无法获得单一聚合整个结果,有没有办法解决这两个问题?
解决方案 1:
您的 _msearch
查询是正确的。我要做的是为每个索引发出一个查询(没有聚合!),其中包含您想要的索引大小,以及另一个仅针对聚合的查询,如下所示:
{ "index": "index1" }
{ "size": 5, "query": { ... }}
{ "index": "index2" }
{ "size": 5, "query": { ... }}
{ "index": "index3" }
{ "size": 5, "query": { ... }}
{ "index": "index1,index2,index3" }
{ "size": 0, "query": { ... }, "aggs": { ... } }
因此前三个查询将 return 记录来自三个索引中每一个的命中,最后一个查询将 return 在所有索引上计算的聚合,但没有文档。
解决方案 2:
另一种解决此问题的方法是在 query
部分中进行单个查询,然后聚合索引名称并使用 top_hits
从每个索引中检索匹配项,像这样:
POST index1,index2,index3/_search
{
"size": 0,
"query": { ... },
"aggs": {
"indexes": {
"terms": {
"field": "_index",
"size": 50
},
"aggs": {
"hits": {
"top_hits": {
"size": 5
}
}
}
}
}
}
我正在使用 Elasticsearch 6.3 版,我想跨多个查询 indices.Elasticsearch 支持这一点,我可以在 url 中将多个索引作为逗号分隔值,并在请求中使用一个查询body 并给出 size 参数来限制搜索结果的数量 returned.However 这限制了整体搜索结果的大小并且可能导致某些索引没有结果 - 所以我想从每个索引中获取前 n 个结果指数.
我尝试使用多重搜索 api (_msearch) 但似乎我必须为所有索引提供相同的查询和大小并且有效,但我无法获得单一聚合整个结果,有没有办法解决这两个问题?
解决方案 1:
您的 _msearch
查询是正确的。我要做的是为每个索引发出一个查询(没有聚合!),其中包含您想要的索引大小,以及另一个仅针对聚合的查询,如下所示:
{ "index": "index1" }
{ "size": 5, "query": { ... }}
{ "index": "index2" }
{ "size": 5, "query": { ... }}
{ "index": "index3" }
{ "size": 5, "query": { ... }}
{ "index": "index1,index2,index3" }
{ "size": 0, "query": { ... }, "aggs": { ... } }
因此前三个查询将 return 记录来自三个索引中每一个的命中,最后一个查询将 return 在所有索引上计算的聚合,但没有文档。
解决方案 2:
另一种解决此问题的方法是在 query
部分中进行单个查询,然后聚合索引名称并使用 top_hits
从每个索引中检索匹配项,像这样:
POST index1,index2,index3/_search
{
"size": 0,
"query": { ... },
"aggs": {
"indexes": {
"terms": {
"field": "_index",
"size": 50
},
"aggs": {
"hits": {
"top_hits": {
"size": 5
}
}
}
}
}
}