当存在“should”、“must”和“must_not”子句时,Elastic Search“should”子句无法按预期工作

Ban*_*ore 3 elasticsearch

我已将此处提供的数据加载到弹性搜索中。

现在我正在尝试查询帐户。

  1. 年龄必须为 38 岁。
  2. 状态不应该是“ID”。
  3. 地址应包含以下任一内容:(这不起作用)
    • 文本“车道”或
    • 完整文本《磨坊大道》

请求:POST - http://localhost:9200/bank/account/_search?pretty

{
  "query": {
    "bool": {
      "should": [
        { "match": { "address": "lane" } },
        { "match_phrase": { "address": "mill avenue" } }
      ],
      "must": [
        { "match": { "age": "38" } }
      ],
      "must_not": [
        { "match": { "state": "ID" } }
      ]
    }
  },
  "from": 0,
  "size": 1,
  "_source": ["account_number", "balance", "firstname", "lastname", "age", "email", "address", "state"],
  "sort": [
    { "account_number": "asc" },
    { "balance": "desc"}
  ]
}
Run Code Online (Sandbox Code Playgroud)

回复

{
  "took": 8,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 36,
    "max_score": null,
    "hits": [
      {
        "_index": "bank",
        "_type": "account",
        "_id": "21",
        "_score": null,
        "_source": {
          "account_number": 21,
          "firstname": "Estella",
          "address": "859 Portal Street",
          "balance": 7004,
          "state": "WV",
          "age": 38,
          "email": "estellapaul@zillatide.com",
          "lastname": "Paul"
        },
        "sort": [
          21,
          7004
        ]
      }
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

您可以检查响应。已收到地址为“859 Portal Street”的记录,但不包含“lane”或“mill avenue”

弹性搜索版本:5.1.1

----编辑---- 解决方案(感谢此处发布的@Lax和@mattweber ):
minimum_should_match如果存在must/must_not,则需要解决方案。

{
  "query": {
    "bool": {
      "minimum_should_match": 1,
      "should": [
        { "match": { "address": "avenue" } },
        { "match_phrase": { "address": "Williams Place" } }
      ],
      "must": [
        { "match": { "age": "38" } }
      ],
      "must_not": [
        { "match": { "state": "ID" } }
      ],
      "filter": {
        "range": {
          "balance": {
            "gte": 20000,
            "lte": 30000
          }
        }
      }
    }
  },
  "from": 0,
  "size": 1000,
  "_source": ["account_number", "balance", "firstname", "lastname", "age", "email", "address", "state"],
  "sort": [
    { "account_number": "asc" },
    { "balance": "desc"}
  ],
  "aggs": {
    "group_by_state": {
      "terms": {
        "field": "state.keyword"
      },
      "aggs": {
        "average_balance": {
          "avg": {
            "field": "balance"
          }
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

Lax*_*Lax 6

当必须/必须不存在时,您需要添加:

minimum_should_match" : 1
Run Code Online (Sandbox Code Playgroud)

在 should 数组之后