Karine
Karine

Reputation: 621

ElasticSearch query filter on nested documents

I need to filter my index based on a nested property :

myNestedProperty: [
   { id: 1, displayName: toto },
   { id: 2, displayName: tata },
   { id: 3, displayName: titi }
]

myNestedProperty: [
   { id: 4, displayName: dodo },
   { id: 5, displayName: dada },
   { id: 6, displayName: didi }
]

I would like to count how many have a Toto and how many does not. I try with the following query :

"aggs": {
"HasToto": {
  "filter": {
    "nested": {
      "path": "myNestedProperty",
      "query": {
        "match": {
          "myNestedProperty.id": "1"
        }
      } 
    }
  }
},
"NoToto": {
  "filter": {
    "nested": {
      "path": "myNestedProperty",
      "query": {
        "bool": {
          "must_not": [
            {"match": {
          "myNestedProperty.id": "1"
        }}
          ]
        } 
      } 
    }
  }
 }
}

The "HasToto" seems to return the expected result but it's not the case of "NoToto" filter (Too much data returned).

Rules : "Toto" can only be there once in myNestedProperty. If I have "Toto", I can't have "Dodo" or another one. It's a hierarchical object :
-- Toto
---- Tata
------- Titi

I simplify the data due to their complexity, I hope it's enough clear with this simple object.

How to achieve this please ? Thanks in advance.

Upvotes: 2

Views: 136

Answers (1)

Karine
Karine

Reputation: 621

I found the solution \o/

"aggs": {
"HasToto": {
  "filter": {
    "bool": {
      "must": {
        "nested": {
      "path": "myNestedProperty",
      "query": {
        "match": {
          "myNestedProperty.id": "1"
        }
      } 
    }
      }
    }}
},
"NoToto": {
  "filter": {
      "bool": {
          "must_not": [
            {
              "nested": {
                  "path": "myNestedProperty",
                  "query": {
                    "match": {
                        "myNestedProperty.id": "1"
                    }
                  }
                }
              }
          ]
      } 
    }
  }
}

Upvotes: 1

Related Questions