'How to make pagination search with SearchAfter() using .NET NEST API
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.
Solution 1:[1]
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
Solution 2:[2]
You could use a separate class with a static constructor:
public static class LongTimeOperation
{
static LongTimeOperation()
{
Thread.Sleep(10000);
Resource = (++count).ToString();
}
public static string Resource { get; set; }
private static int count = 0;
}
[TestFixture]
public class TestFixture1
{
[OneTimeSetUp]
public void OneTimeSetUp()
{
resource = LongTimeOperation.Resource;
}
[Test]
public void Test1() => Assert.That(resource, Is.EqualTo("1"));
[Test]
public void Test2() => Assert.That(resource, Is.EqualTo("1"));
private string resource;
}
[TestFixture]
public class TestFixture2
{
[OneTimeSetUp]
public void OneTimeSetUp()
{
resource = LongTimeOperation.Resource;
}
[Test]
public void Test1() => Assert.That(resource, Is.EqualTo("1"));
[Test]
public void Test2() => Assert.That(resource, Is.EqualTo("1"));
private string resource;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | LeBigCat |
| Solution 2 | Wilhelm Medetz |
