Determine Nested Object Count in Elasticsearch Document

Hello, Elasticsearch community,

I'm currently working with Elasticsearch and have a scenario where I need to identify the count of nested objects within a document. The document structure includes nested fields, and I'm looking for an efficient way to retrieve the number of nested objects.

Could anyone please provide guidance or share any Elasticsearch queries or approaches that can help me achieve this? I want to accurately determine the count of nested objects within a given document.

Thank you in advance for your assistance!


The best thing to do IMO is to compute that on your side before indexing the document:

  "foo": [{"bar":"baz"},{"bar":"baz"}],
  "foo_length": 2

If you can't do that at index time, you can use runtime fields and write a script which computes that. See Runtime fields | Elasticsearch Guide [8.12] | Elastic

But this will be slower than the 1st approach.

It won't be possible on our end before indexing the document.
Can we check the nested object count for an existing document?

It's that for a single document? Would you like to search on that field? Sort by that field? Or just display that information?

Yes, it is for a single document, and we would like to search on that field and display that information.

So it's something you want to have for every document in the index. Not a single one.

As you can't modify the existing dataset, I'm pasting here the answer I did already which I hope could help you:

But again, please be aware that this will be slower than then indexing the size of the array.

I created a video in the past which covers that topic. You might want to look at it:

The demo code is available at

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.