Home > OS >  ES exists query
ES exists query

Time:06-04

I have a document which has nested field:

  • testData.testDataId

I only want to get the documents that have testData.testDataId as null

Here is my query:

{
  "bool": {
    "must_not": [
      { "exists": { "field": "testData.testDataId", "boost": 1.0 } }
    ],
    "adjust_pure_negative": true,
    "boost": 1.0
  }
}

But I've got and those documents which has 'testData' as null too. Is it possible disable?

For example: I have those 3 documents

[
  {
    "name": "test_user_1",
    "additionalInfo": { "phoneNumber": "00000000", "address": "test_address" },
    "testData": { "testDataId": "some_id", "description": "test_description" }
  },
  {
    "name": "test_user_2",
    "additionalInfo": { "phoneNumber": "00000000", "address": "test_address" },
    "testData": { "description": "test_description" }
  },
  {
    "name": "test_user_3",
    "additionalInfo": { "phoneNumber": "00000000", "address": "test_address" }
  }
]

I wish to only retrieve test_user_2

CodePudding user response:

Tldr;

Since you are dealing with nested field you need to use a nested query.

To fix

GET /72491619/_search
{
  "query": {
    "nested": {
      "path": "testData",
      "query": {
        "bool": {
          "must_not": [
            {
              "exists": {
                "field": "testData.testDataId"
                }
            }
          ]
        }
      }
    }
  }
}

To reproduce

To set up the index and the data I used the api calls below:

PUT /72491619/
{
  "mappings": {
    "properties": {
      "name": {
        "type": "keyword"
      },
      "additionalInfo":{
        "type": "nested",
        "properties": {
          "phoneNumber": {
            "type": "keyword"
          },
          "address": {
            "type": "keyword"
          }
        }
      },
      "testData":{
        "type": "nested",
        "properties": {
          "testDataId": {
            "type": "keyword"
          },
          "description": {
            "type": "keyword"
          }
        }
      }
    }
  }
}

POST /_bulk
{"index":{"_index":"72491619"}}
{"name":"test_user_1","additionalInfo":{"phoneNumber":"00000000","address":"test_address"},"testData":{"testDataId":"some_id","description":"test_description"}}
{"index":{"_index":"72491619"}}
{"name":"test_user_2","additionalInfo":{"phoneNumber":"00000000","address":"test_address"},"testData":{"description":"test_description"}}
{"index":{"_index":"72491619"}}
{"name":"test_user_3","additionalInfo":{"phoneNumber":"00000000","address":"test_address"}}
  • Related