How to enforce ordering within nested objects?

I'm using elasticsearch as a Key-Value store, so that I can guarantee the query always return just 1 document. There is a nested field in the document schema, and I want to make sure multiple values within the nested object are returned in order.

More concretely, I have

{
    "mappings": {
        "properties": {
            "neighborhood": {
                "type": "keyword"
            },
            "forecast": {
                "type": "nested",
                "properties": {
                    "date": {
                        "type": "date"
                    },
                    "demand": {
                        "type": "double"
                    }
                }
            }
        }
    }
}

my base query looks like this:

{
    "query": {
        "bool": {
            "must": [
                {
                    "term": {
                        "neighborhood": "Hogwarts"
                    }
                }
            ]
        }
    }
}

and I got back result with randomly ordered forecast objects not sorted by date

"_source": {
                    "neighborhood": "Hogwarts",
                    "forecast": [
                        {
                            "date": 3,
                            "demand": 4.895964622497559
                        },
                        {
                            "date": 1,
                            "demand": 5.326427459716797
                        },
                        {
                            "date": 2,
                            "demand": 5.326427459716797
                        }
}

How do i modify the query so that it can return document where within the forecast object it is sorted by date.

I found many examples which explained how to sort the multiple parent documents based on nested objects fields, but I haven't seen an example explaining how to enforce ordering of values within nested objects itself.

Thanks!

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