How to get a previous page from elasticsearch using search_after?

We are trying to make fast pagination with search_after.
It is possible to move forward by search_after.
We are using next request:

{
    "size":5,
    "search_after": [1508827804000, "data#123"],
     "sort": [{
		"date": {
			"order": "desc"
		}
	}, {
		"_uid": {
			"order": "desc"
		}
	}]
}

But how to get previous page? Is it possible to make it only by Elasticsearch API?
Our solution: for getting pointer on previous page we build such query

Into ES 2.x we used this request

{
"index": "my_index",
"type": "data",
"body": {
	"size": 11,
	"query": {
		"bool": {
			"filter": {
				"bool": {
					"must": [{
						"range": {
							"date": {
								"gte": "2017-10-17T09:26:00"
							}
						}
					}, {
						"range": {
							"date": {
								"lte": "2017-10-24T09:26:00"
							}
						}
					}, {
						"bool": {
							"should": [{
								"bool": {
									"must": [{
										"term": {
											"date": "2017-10-24T06:50:03+0000"
										}
									}, {
										"range": {
											"_uid": {
												"gt": "data#59eee29b367df1860f335c32"
											}
										}
									}]
								}
							}, {
								"range": {
									"data": {
										"gt": "2017-10-24T06:50:03+0000"
									}
								}
							}]
						}
					}]
				}
			}
		}
	},
	"sort": [{
		"date": {
			"order": "asc"
		}
	}, {
		"cID": {
			"order": "asc"
		}
	}]
}

}
If we needed to move forward, we would change gt to lt and sort from asc to desc.
This request doesn't work into ES 5.x and higher.

This query looks very complicated. Generally, you can use search_after but reverse the sort order to get the page before. See also a similar discussion on GitHub: https://github.com/elastic/elasticsearch/issues/24364

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