我使用复合查询查询包含300条记录的弹性索引,如下所示:
GET my_index/_search
{
"size": 10,
"query": {
"bool": {
"should": [
{
"bool": {
"should": [
{
"multi_match": {
"query": "card",
"fields": [
"title^1.0"
]
}
}
],
"must": {
"term": {
"_index": {
"value": "my_index"
}
}
}
}
}
]
}
}
}必须索引是因为这可能是一个多索引查询,这取决于某些业务逻辑(必须很可能是一个过滤器,而且我可以更改它,但这不是我问题的一部分。我也用过滤器得到同样的结果)。
虽然我希望这将返回与this子句匹配的文档,但我将返回索引(300)中的所有文档。
为什么会发生这种事?
发布于 2020-08-28 16:13:25
解决方法是将minimumShouldMatch字段添加到查询中。然后,生成的查询变成:
GET my_index/_search
{
"size": 10,
"query": {
"bool": {
"should": [
{
"bool": {
"minimum_should_match": 1,
"should": [
{
"multi_match": {
"query": "card",
"fields": [
"title^1.0"
]
}
}
],
"must": {
"term": {
"_index": {
"value": "my_index"
}
}
}
}
}
]
}
}
}我认为这背后的原因是,优化bool查询是为了提供最大数量的匹配结果(更多匹配-更好)。因此,如果必须/筛选子句匹配,那么应该甚至不执行。通过添加"minimum_should_match":1,我们指示elasticsearch在返回文档之前至少匹配1 we子句。
弹性文件摘录:
bool查询采用更匹配的更好的方法,因此每个匹配必须或应该子句的分数将加在一起,以便为每个文档提供最终的_score。可以使用minimum_should_match参数指定返回的文档必须匹配的of子句的数量或百分比。
如果bool查询至少包含一个must子句,而不包含and或filter子句,则默认值为1,否则默认值为0。
有关其他有效值,请参见minimum_should_match参数。
发布于 2020-08-25 01:10:39
使用索引数据和搜索查询添加工作示例
索引数据:
{
"title":"card",
"cost":"55"
}
{
"title":"Card making",
"cost":"55"
}
{
"title":"elasticsearch",
"cost":"55"
}搜索查询:
GET /_search
{
"query": {
"bool": {
"should": [
{
"bool": {
"filter": [
{
"term": {
"_index": {
"value": "index-name"
}
}
}
],
"must": [
{
"multi_match": {
"fields": [
"title^1.0"
],
"query": "card"
}
}
]
}
}
]
}
}
}搜索结果:
"hits": [
{
"_index": "my_index",
"_type": "_doc",
"_id": "1",
"_score": 0.7549127,
"_source": {
"title": "card",
"cost": "55"
}
},
{
"_index": "my_index",
"_type": "_doc",
"_id": "2",
"_score": 0.55654144,
"_source": {
"title": "Card making",
"cost": "55"
}
}
]https://stackoverflow.com/questions/63568981
复制相似问题