如何使用 AND(过滤/必须)按相同属性过滤 OpenSearch 中的文档?

问题描述 投票:0回答:1

使用此索引:

PUT test
{
  "mappings": {
    "properties": {
      "id": {
        "type": "keyword"
      },
      "body": {
        "type": "text"
      },
      "subjects": {
        "type": "nested",
        "properties": {
          "id": {
            "type": "keyword"
          },
          "path_id": {
            "type": "keyword"
          }
        }
      }
    }
  }
}

并添加这 3 个文档:

POST test/_doc
{
  "id": "1",
  "body": "topic 1",
  "subjects": [
    {
      "id": "calculus-ii",
      "path_id": ["math", "advanced-math", "calculus-ii"]
    },
    {
      "id": "calculus-iii",
      "path_id": ["math", "advanced-math", "calculus-iii"]
    }
  ]
}

POST test/_doc
{
  "id": "2",
  "body": "topic 2",
  "subjects": [
    {
      "id": "calculus-i",
      "path_id": ["math", "advanced-math", "calculus-i"]
    },
    {
      "id": "calculus-ii",
      "path_id": ["math", "advanced-math", "calculus-ii"]
    }
  ]
}

POST test/_doc
{
  "id": "3",
  "body": "topic 3",
  "subjects": [
    {
      "id": "equations",
      "path_id": ["math", "basic-math", "equations"]
    }
  ]
}

我想根据嵌套属性

subjects.path_id
进行搜索,仅搜索同时具有两个主题的文档:
calculus-ii
calculus-iii

当我使用

should
时,它会找到主题 1 和 2。这意味着搜索输入的结构设置正确:

GET test/_search
{
  "query": {
    "nested": {
      "path": "subjects",
      "query": {
        "bool": {
          "should": [
            {
              "terms": {
                "subjects.path_id": ["calculus-ii"]
              }
            },
            {
              "terms": {
                "subjects.path_id": ["calculus-iii"]
              }
            }
          ]
        }
      }
    }
  }
}

但是,当我将

should
更改为
must
filter
时,结果为空。

如何将此行为从

OR
更改为
AND

opensearch
1个回答
0
投票

问题似乎出在嵌套属性上。更改为以下内容后,查询按预期工作:

GET test/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "subjects",
            "query": {
              "term": {
                "subjects.id": "calculus-ii"
              }
            }
          }
        },
        {
          "nested": {
            "path": "subjects",
            "query": {
              "term": {
                "subjects.id": "calculus-iii"
              }
            }
          }
        }
      ]
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.