Home > Blockchain >  Match documents where _id exists in nested array of objects
Match documents where _id exists in nested array of objects

Time:11-05

I have the following elastic search index

{
  "companies": {
    "aliases": {},
    "mappings": {
      "properties": {
        "industries": {
          "type": "nested",
          "properties": {
            "_id": {
              "type": "text",
              "fields": {
                "keyword": {
                  "type": "keyword",
                  "ignore_above": 256
                }
              }
            },
            "description": {
              "type": "text"
            },
            "priority": {
              "type": "integer"
            },
            "title": {
              "type": "text"
            }
          }
        }
      }
    }
  }
}

and i would like to search for all companies where the industries array contains a tag with the _id = 81ca8f45-5b6a-11ed-96b4-0242ac110002.

I tried the following query but i cannot get it to match any document.

{
  "query": {
    "bool": {
      "should": [
        {
          "nested": {
            "path": "industries",
            "query": {
              "bool": {
                "should": [
                  {
                    "term": {
                      "industries._id": "81ca8f45-5b6a-11ed-96b4-0242ac110002"
                    }
                  }
                ]
              }
            }
          }
        },
        {
          "term": {
            "industries._id": "81ca8f45-5b6a-11ed-96b4-0242ac110002"
          }
        }
      ]
    }
  }
}

Is it even possible to match the _id field? Because i tested the following term query and it returned me a good result.

{
  "query": {
    "bool": {
      "should": [
        {
          "term": {
            "industries.priority": 1
          }
        }
      ]
    }
  }
}

CodePudding user response:

Try use Term Query with keyword field. Change to "industries._id.keyword"

{
  "query": {
    "bool": {
      "should": [
        {
          "nested": {
            "path": "industries",
            "query": {
              "bool": {
                "should": [
                  {
                    "term": {
                      "industries._id.keyword": "81ca8f45-5b6a-11ed-96b4-0242ac110002"
                    }
                  }
                ]
              }
            }
          }
        },
        {
          "term": {
            "industries._id.keyword": "81ca8f45-5b6a-11ed-96b4-0242ac110002"
          }
        }
      ]
    }
  }
}
  • Related