Elastic 6.x - Get next document ID in index based on date/time?

Hi,

There was a similar question in the forums years ago, but it didn't get answered so I thought I'd ask and see if maybe something has changed or there is a specific way to do this.

I have an elastic query that gets a document by ID. I want to retrieve the next document in the index based on a sorted date field that also stores the time.

Below is my current query which doesn't work obviously because it is returning always document _id = 48. I am not sure of the syntax needed to get the next document based on the date_posted field taking into account the date posted of the current document _id 48.

{
  "size" : 1,
  "query": { 
    "bool": { 
    
      "filter": [ 
      
        { "term":  { "_id":"48" }}
       
      ]
    }
  },
  "sort": [
      {
         "date_posted": {
            "order": "asc"
         }
      }
   ]
}

I believe that the only way to do that is by sending 2 queries. The first is a GET by id then read the timestamp and fetch all documents where timestamp is greater or equal to that timestamp but where id is not the previous one. And sort as you did.

My 2 cents.

I believe that this what Kibana is doing to get the surrounded documents (feature introduced recently IIRC).

1 Like

Thanks for the reply, I ended up doing that and also added a size parameter with a value of 1 and ensure my date field had a full date/time stored in case two documents had the same "date_posted" in my case.

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