tomas
tomas

Reputation: 329

elastic search filter by documents count in nested document

I have this schema in elastic search.

79[
    'ID' : '1233',
    Geomtries:[{
        'doc1' : 'F1',
        'doc2' : 'F2'

    },
    (optional for some of the documents)
    {
        'doc2' : 'F1',
        'doc3' : 'F2'
    }]
]

the Geometries is a nested element. I want to get all of the documents that have one object inside Geometries.

Tried so far :

"script" : {"script" : "if (Geomtries.size < 2) return true"}

But i get exceptions : no such property GEOMTRIES

Upvotes: 1

Views: 1861

Answers (2)

G Quintana
G Quintana

Reputation: 4667

The problem is in the way you access fields in your script, use:

doc['Geometry'].size()
or
_source.Geometry.size()

By the way for performance reasons, I would denormalize and add GeometryNumber field. You can use the transform mapping to compute size at index time.

Upvotes: 1

eemp
eemp

Reputation: 1166

If you have the field as type nested in the mapping, the typical doc[fieldkey].values.size() approached does not seem to work. I found the following script to work:

{
  "from" : 0,
  "size" : <SIZE>,
  "query" : {
    "filtered" : {
      "filter" : {
        "script" : {
          "script" : "_source.containsKey('Geomtries') && _source['Geomtries'].size() == 1"
        }
      }
    }
  }
}

NB: You must use _source instead of doc.

Upvotes: 2

Related Questions