如何使用search_after从elasticsearch获取上一页?

Ant*_* Zh 2 pagination elasticsearch

我正在尝试使用 ElasticSearch 创建快速分页。我已阅读有关操作员的此文档页面search_after。我了解如何创建“向前”分页。但在这种情况下,我无法意识到如何移动到上一页。

Pie*_*mon 10

在我们正在处理的项目中,我们将简单地反转排序方向,然后将其search_after用作search_before.

这是一个迟到的答案,但比必须跟踪应用程序的结果要好一些。对于该特定场景,Scroll API(我不知道当时是否可用)应该更适合。

  • 在最新版本的 ElasticSearch (`v7.16`) 中,建议使用 `search_after` API 而不是旧的滚动 API。请参阅:https://www.elastic.co/guide/en/elasticsearch/reference/current/scroll-api.html (3认同)

js_*_*alf 3

尽管该 API 之前没有搜索功能,但您可以使用此解决方法。

向后移动很容易,我也必须这样做。只需在您使用的任何语言的变量中跟踪它即可。

我用指针对一个对象进行搜索索引,以跟踪我在数据中的位置。例如:

var $scope.search.display = 0;
var $scope.searchIndex = {};
var data = getElasticSearchQuery() //This is your data from the elastic query 
if (!$scope.searchIndex[$scope.search.display + 10] && data.hits.length > 0) {
    $scope.searchIndex[$scope.search.display + 10] = data.hits[data.hits.length - 1].sort;
}
Run Code Online (Sandbox Code Playgroud)

如果您有“下一个”和“上一个”按钮,那么在弹性的 POST 请求中只需为 search_after 参数分配正确的索引:

$scope.prevButton = function(){
  $scope.search.display -= 10;
  if($scope.search.display < 10){
    $scope.search.searchAfter = null;
  }
  if($scope.searchIndex[$scope.search.display]){
    $scope.search.searchAfter = $scope.searchIndex[$scope.search.display]
  }
  $scope.sendResults(); //send the post in an elastic search query
};

$scope.nextButton = function() {
  $scope.search.display += 10;
  if($scope.searchIndex[$scope.search.display]){
    $scope.search.searchAfter = $scope.searchIndex[$scope.search.display];
  }
  $scope.sendResults(); //send the post in an elastic search query
};
Run Code Online (Sandbox Code Playgroud)

这应该能让你站起来。10 是我的尺寸,这意味着我有 10 个结果的分页。