Search code examples
elasticsearchamazon-opensearch

Query the latest nested object in OpenSearch/ElasticSearch


I'm using OpenSearch to allow users to search a complex data structure. One of the use cases requires me to display records only if the latest nested object meets the requirements, but google and the docs are being rather unhelpful. Example data structure:

{
  "id": 0,
  "nestedObject": [
    {
      "date": ...,
      "boolean": ...,
    }
    {
      "date": ...,
      "boolean": ...,
    }
  ]
}

the pseudo search for this would be: nestedObject.date == max(nestedObject.date) && nestedObject.boolean === true

If this is possible, how would I go about it?


Solution

  • The simplest way to do it would be to add an additional boolean field to the nested objects and set it to True for the latest nested object during indexing. This way your pseudo search would become:

    nestedObject.isLatest == true && nestedObject.boolean == true