首页 > 解决方案 > 如何在弹性搜索中使用必须和应该

问题描述

我在弹性搜索中有这样的数据:

{
    a : "status",
    b : "01"
},
{
    a : "status b",
    b : "02"
}

我想用mustand获取所有数据should

我试过这样的机智mustshould查询

{
  "query": {
    "bool": {
      "must":[
        {
          "match": {
            "a": "status b"
          }
        }],
      "should":[ {
        "match": {
          "b": "01"
        }
      }]
    }
  }
}

但查询should不起作用,任何人都可以帮助我吗?

标签: elasticsearchelasticsearch-query

解决方案


由于您没有提到您的映射,我根据您的数据创建了自己的映射并索引了您的示例文档,它工作正常。

您还可以使用_analyze API检查您的数据是如何被索引的,这将帮助您有效地调试问题。另外,使用解释 API,它会告诉你为什么你的 should 子句不匹配任何文档。

索引定义

{
    "mappings": {
        "properties": {
            "a": {
                "type": "text"
            },
            "b": {
                "type": "integer"
            }
        }
    }
}

索引示例文档

{
    a : "status",
    b : "01"
},
{
    a : "status b",
    b : "02"
}

笔记搜索查询也和你的一样

{
    "query": {
        "bool": {
            "must": [
                {
                    "match": {
                        "a": "status b"
                    }
                }
            ],
            "should": [
                {
                    "match": {
                        "b": "01"
                    }
                }
            ]
        }
    }
}

它带来了两个示例文档

"hits": [
            {
                "_index": "so_must_should",
                "_type": "_doc",
                "_id": "1",
                "_score": 1.2111092,
                "_source": {
                    "a": "status",
                    "b": "01"
                }
            },
            {
                "_index": "so_must_should",
                "_type": "_doc",
                "_id": "2",
                "_score": 0.77041256,
                "_source": {
                    "a": "status b",
                    "b": "02"
                }
            }
        ]

请交叉检查您的映射并将其与此示例进行比较,如果您还有其他问题,请告诉我。


推荐阅读