ElasticSearch应该/必须条款不能按预期工作

时间:2017-05-10 10:35:22

标签: elasticsearch kibana nest elasticsearch-marvel

以下是我的弹性查询

 GET _search
{
  "query": {
    "bool": {
      "must": {
        "match": {
          "marriages.marriage_year": "1630"
        }
      },
      "should": {
        "match": {
          "first_name": {
            "query": "mary",
            "fuzziness": "2"
          }
        }
      },
      "must": {
        "range": {
          "marriages.marriage_year": {
            "gt": "1620",
            "lte": "1740"
          }
        }
      }
    }
  }
}

它返回带有marriages.marriage_year= "1630"的数据,其中Mary作为first_name作为最高得分。我还希望在1620 - 1740之间包含marriages.marriage_year,这些未显示在结果中。它仅显示marriage_year 1630

的数据

1 个答案:

答案 0 :(得分:2)

那是因为你有两个bool/must子句,第二个子句在解析JSON查询时被删除。改写它就像这样,它会起作用:

{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "marriages.marriage_year": "1630"
          }
        },
        {
          "range": {
            "marriages.marriage_year": {
              "gt": "1620",
              "lte": "1740"
            }
          }
        }
      ],
      "should": {
        "match": {
          "first_name": {
            "query": "mary",
            "fuzziness": "2"
          }
        }
      }
    }
  }
}

<强>更新

然后您需要采用不同的方式,并且在bool/must中您只需要range个查询,并在match部分内移动bool/should

{
  "query": {
    "bool": {
      "must": [
        {
          "range": {
            "marriages.marriage_year": {
              "gt": "1620",
              "lte": "1740"
            }
          }
        }
      ],
      "should": [
        {
          "match": {
            "first_name": {
              "query": "mary",
              "fuzziness": "2"
            }
          }
        },
        {
          "match": {
            "marriages.marriage_year": "1630"
          }
        }
      ]
    }
  }
}