反转匹配或匹配未设置某些 ID 的数组中的每个元素

Reverse a match or match every element in an array where some IDs are not set

正在努力进行此 ES 查询。基本上,我有一个嵌套对象,例如:

{
  "id": "00000000-0000-0000-0000-000000000000",
  "exchangeRate": 0.01,
  "payments": [
    {
      "id": "00000000-0000-0000-0000-000000000000",
      "paymentId": "some-id",
      "currency": "USD",
      "amount": 400.0
    },
    {
      "id": "00000000-0000-0000-0000-000000000000",
      "currency": "USD",
      "paymentId": "some-id2",
      "amount": -200.0
    },
    {
      "id": "00000000-0000-0000-0000-000000000000",
      "currency": "USD",
      "amount": -200.0
    }
  ]
}

我想匹配一个对象,其中定义了一些“paymentId”键,但不是全部。所以上面的对象是匹配的。而像这样的东西:

{
  "id": "00000000-0000-0000-0000-000000000000",
  "exchangeRate": 0.01,
  "payments": [
    {
      "id": "00000000-0000-0000-0000-000000000000",
      "paymentId": "some-id",
      "currency": "USD",
      "amount": 400.0
    },
    {
      "id": "00000000-0000-0000-0000-000000000000",
      "currency": "USD",
      "paymentId": "some-id2",
      "amount": -200.0
    },
    {
      "id": "00000000-0000-0000-0000-000000000000",
      "currency": "USD",
      "paymentId": "some-id3",
      "amount": -200.0
    }

不匹配。

我进行了一个查询,如果定义了所有 paymendIds 并且 returns 所有对象都是正确的。这个查询是:

{
  "query": {
    "bool": {
      "must": {
        "nested": {
          "path": "payments",
          "query": {
            "exists": {
              "field": "payments.paymendIds"
            }
          }
        }
      }
    }
  }
}

问题是我该如何扭转这种局面?因此,如果它匹配此查询,则不会 return 作为匹配项。因为放置“must_not”只是起到相反的作用。它 return 是根本没有定义任何 paymentIds 的所有记录。这是我想要匹配的东西,但我需要所有那些甚至只有 some 的 paymentIds 集。

您可以在 nested 上下文中一一比较 payments 对象的 field value sizes

假设 payments.idpayments.paymentId 都是 keyword 映射类型,你可以说:

GET your-index/_search
{
  "query": {
    "nested": {
      "path": "payments",
      "query": {
        "script": {
          "script": "doc['payments.id'].size() != doc['payments.paymentId'].size()"
        }
      }
    }
  }
}