How to make pagination search with SearchAfter() using .NET NEST API

Viewed 151

I work on a small .NET 6 API project with elastic search using Nest package. I have an API controller that is supposed to send a specific number of results ex: 10 with every request with elasticSerach.SearchAfter() method. I search for a code example to know how to use it but I didn't find a clear example for a beginner like me.

1 Answers

Use scroll api:

https://www.elastic.co/guide/en/elasticsearch/client/net-api/current/scrolling-documents.html

First call, will be valable 10m (elastic take a snapshop for X minutes, and you can use it to scroll (=paginate). This point is very important. The max duration es can store the snapshot is 1d (1 day, i thinck it should be enough for your case).

var searchResponse = Client.Search<Project>(s => s
    .Query(q => q
        // your query
    )
    .Size(10)
    .Scroll("10m") 
);

And after, for each "SearchAfter", to get the next 10 elements

searchResponse = Client.Scroll<Project>("10m", searchResponse.ScrollId);

If you have large amount of data, or need more feature, take a look at search_after (better, but more complex): https://www.elastic.co/guide/en/elasticsearch/reference/current/paginate-search-results.html#search-after

Related