Determine ranking result

I am running ES and PHP. I am trying to display stats when I view a specific document.

Suppose you have any search result in Elasticsearch, like this list of big cities sorted by population desc:

sort order ranking - name - population

rank 1 - CITY A - pop. 5m

rank 2 - CITY B - pop. 4m

rank 3 - CITY C - pop. 3m

When I now view CITY B (rank 2) on a web page (by its _id) I want to show 'next city' (rank 3) and 'previous city' (rank 1) links when I view the city ranked 2 -- taking into account the original query.

How can this be done? I could not find anything about this topic.

You can use search_after:
https://www.elastic.co/guide/en/elasticsearch/reference/master/search-request-search-after.html

With this feature you can return the documents that are ranked "before" or "after" another document.