如何在弹性搜索中结合过滤器编写嵌套查询?

How to write a nested query in combination with filters in Elastic Search?

我需要执行嵌套查询,尝试在对象数组中进行搜索。除此之外,我还需要搜索其他参数。我正在为那些使用过滤器。如何有效地组合过滤器和嵌套查询?对不起,我不是 ES 专家。

这是我尝试在 Kibana 中执行的查询:

GET test-index/_search
    {
      "query": {
        "bool": {
          "filter": [
            {
              "term": {
                "isPublic": true
              }
            },
            {
              "term": {
                "isDeleted": false
              }
            }
          ]
        },
        "nested": {
          "path": "data.location.countries",
          "query": {
            "bool": {
              "must": [
                {
                  "match": {
                    "data.location.countries.name": "United States"
                  }
                },
                {
                  "range": {
                    "data.location.countries.weight": {
                      "gt": 30
                    }
                  }
                }
              ]
            }
          }
        }
      },
      "size": "60",
      "from": 0,
      "sort": [
        {
          "followers": {
            "order": "desc"
          }
        }
      ]
    }

返回错误:

{
  "error": {
    "root_cause": [
      {
        "type": "parsing_exception",
        "reason": "[bool] malformed query, expected [END_OBJECT] but found [FIELD_NAME]",
        "line": 17,
        "col": 5
      }
    ],
    "type": "parsing_exception",
    "reason": "[bool] malformed query, expected [END_OBJECT] but found [FIELD_NAME]",
    "line": 17,
    "col": 5
  },
  "status": 400
}

有人可以分享一些这方面的知识吗?

将嵌套查询移至 bool.filter:

{
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            "isPublic": true
          }
        },
        {
          "term": {
            "isDeleted": false
          }
        },
        {
          "nested": {
            "path": "data.location.countries",
            "query": {
              "bool": {
                "must": [
                  {
                    "match": {
                      "data.location.countries.name": "United States"
                    }
                  },
                  {
                    "range": {
                      "data.location.countries.weight": {
                        "gt": 30
                      }
                    }
                  }
                ]
              }
            }
          }
        }
      ]
    }
  },
  "size": "60",
  "from": 0,
  "sort": [
    {
      "followers": {
        "order": "desc"
      }
    }
  ]
}

您不能在 compound query afaik 之外使用超过 1 个查询。