Skip to content

Commit 84d5e2b

Browse files
authored
Return @search.nextPageParameters when a search leaves out top (#100)
Fixes #103 ## What was wrong A POST search without `top` returned the first 50 results and no way to get the rest. Azure returns the same 50 plus `@search.nextPageParameters` and `@odata.nextLink` when more results match. The Azure Search SDKs follow these to read every result, so a client that enumerated a search saw only 50. ## What changed - `SearchRequest.Top` is now null when the request leaves it out, so the searcher can tell that apart from `top: 50`. `SearchRequest.DefaultTop` is 50. - When `top` was left out and more results match, the searcher reports the next `skip`. The controller returns the same request with `skip` moved on and still no `top`, so each page gets a continuation of its own, plus `@odata.nextLink` to `docs/search.post.search`. - A request that sets `top` gets no continuation, as in Azure. - No continuation is offered once its `skip` would pass 100,000 (`SearchRequest.MaxSkip`), since the emulator refuses that `skip` with 400. The client stops after the last page it can request. Not covered: GET searches, where Azure returns only a nextLink to another GET, and `top` above 1000, which still returns 400. ## Tests - `SearchPagingTests` (new, unit, 8 tests): the first page and its next skip; following each continuation over 120 documents gives pages of 50, 50 and 20 with every document once; no continuation when the matches fit on one page or when `top` is set; and, over 100,100 documents, a continuation at the skip limit but none past it. - `SearchPagingIntegrationTests` (new, 3 tests, against the container through the .NET SDK): enumerating without `Size` reads all 120 in pages of 50, 50 and 20; `Size = 50` reads 50; the REST response has `skip: 50`, no `top`, the original search and filter, and the nextLink. - DebugClient check 10 (new): uploads 120 more documents and reads every result through the SDK's paging, in pages of 50, 50 and 23. It reads only 50 of 123 on `main`. - Also checked by hand with the Python SDK `azure-search-documents` 11.5.2: a search with no `top` yields all 120 results. All 981 unit tests pass. `dotnet test` from the repo root currently stops before any test runs, on `main` too: restoring `AzureSearchEmulator.Aspire` fails with NU1902, a moderate advisory for MessagePack 2.5.302 ([GHSA-qhrr-8q5h-9q3h](GHSA-qhrr-8q5h-9q3h)) that the project treats as an error. I ran the unit and integration test projects directly.
1 parent da2e42f commit 84d5e2b

7 files changed

Lines changed: 359 additions & 6 deletions

File tree

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
using System.Net.Http.Json;
2+
using System.Text.Json.Nodes;
3+
using Azure.Search.Documents;
4+
using Azure.Search.Documents.Indexes;
5+
using Azure.Search.Documents.Indexes.Models;
6+
using Azure.Search.Documents.Models;
7+
using Xunit;
8+
9+
namespace AzureSearchEmulator.IntegrationTests;
10+
11+
/// <summary>
12+
/// Covers <c>@search.nextPageParameters</c>, which the Azure Search SDK follows to read past
13+
/// the first 50 results of a search that leaves out <c>top</c>.
14+
/// </summary>
15+
public class SearchPagingIntegrationTests(EmulatorFactory factory)
16+
: IClassFixture<EmulatorFactory>
17+
{
18+
private const int DocumentCount = 120;
19+
20+
[Fact]
21+
public async Task SearchWithoutSize_EnumeratesEveryResultAcrossPages()
22+
{
23+
var (indexClient, searchClient, indexName) = await SetUpAsync("test-paging-all");
24+
25+
var response = await searchClient.SearchAsync<SearchDocument>(
26+
"*", new SearchOptions { OrderBy = { "Id" } }, TestContext.Current.CancellationToken);
27+
28+
var pageSizes = new List<int>();
29+
var ids = new List<string>();
30+
31+
await foreach (var page in response.Value.GetResultsAsync().AsPages())
32+
{
33+
pageSizes.Add(page.Values.Count);
34+
ids.AddRange(page.Values.Select(r => (string)r.Document["Id"]));
35+
}
36+
37+
Assert.Equal([50, 50, 20], pageSizes);
38+
Assert.Equal(Enumerable.Range(0, DocumentCount).Select(i => i.ToString("D3")), ids);
39+
40+
await indexClient.DeleteIndexAsync(indexName, TestContext.Current.CancellationToken);
41+
}
42+
43+
[Fact]
44+
public async Task SearchWithSize_ReturnsOnlyThatManyResults()
45+
{
46+
var (indexClient, searchClient, indexName) = await SetUpAsync("test-paging-size");
47+
48+
var response = await searchClient.SearchAsync<SearchDocument>(
49+
"*", new SearchOptions { Size = 50 }, TestContext.Current.CancellationToken);
50+
51+
var count = 0;
52+
53+
await foreach (var _ in response.Value.GetResultsAsync())
54+
{
55+
count++;
56+
}
57+
58+
Assert.Equal(50, count);
59+
60+
await indexClient.DeleteIndexAsync(indexName, TestContext.Current.CancellationToken);
61+
}
62+
63+
/// <summary>
64+
/// The REST shape, for clients that read the continuation themselves instead of through the
65+
/// SDK: the same request with <c>skip</c> moved on, and still no <c>top</c>.
66+
/// </summary>
67+
[Fact]
68+
public async Task SearchPostWithoutTop_ReturnsNextPageParametersAndNextLink()
69+
{
70+
var (indexClient, _, indexName) = await SetUpAsync("test-paging-rest");
71+
72+
using var http = factory.CreateHttpClient();
73+
74+
using var httpResponse = await http.PostAsJsonAsync(
75+
$"indexes/{indexName}/docs/search?api-version=2024-07-01",
76+
new JsonObject { ["search"] = "*", ["filter"] = "Id ne 'none'" },
77+
TestContext.Current.CancellationToken);
78+
79+
httpResponse.EnsureSuccessStatusCode();
80+
81+
var body = (await httpResponse.Content.ReadFromJsonAsync<JsonObject>(TestContext.Current.CancellationToken))!;
82+
var next = body["@search.nextPageParameters"]!.AsObject();
83+
84+
Assert.Equal(50, next["skip"]!.GetValue<int>());
85+
Assert.False(next.ContainsKey("top"));
86+
Assert.Equal("*", next["search"]!.GetValue<string>());
87+
Assert.Equal("Id ne 'none'", next["filter"]!.GetValue<string>());
88+
Assert.EndsWith(
89+
$"/indexes('{indexName}')/docs/search.post.search?api-version=2024-07-01",
90+
body["@odata.nextLink"]!.GetValue<string>());
91+
92+
await indexClient.DeleteIndexAsync(indexName, TestContext.Current.CancellationToken);
93+
}
94+
95+
private async Task<(SearchIndexClient IndexClient, SearchClient SearchClient, string IndexName)> SetUpAsync(
96+
string indexName)
97+
{
98+
var indexClient = factory.CreateSearchIndexClient();
99+
var searchClient = factory.CreateSearchClient(indexName);
100+
101+
try
102+
{
103+
await indexClient.DeleteIndexAsync(indexName, TestContext.Current.CancellationToken);
104+
}
105+
catch (Azure.RequestFailedException ex) when (ex.Status == 404)
106+
{
107+
// expected
108+
}
109+
110+
var index = new SearchIndex(indexName)
111+
{
112+
Fields =
113+
[
114+
new SimpleField("Id", SearchFieldDataType.String) { IsKey = true, IsFilterable = true, IsSortable = true },
115+
new SearchableField("Name"),
116+
]
117+
};
118+
119+
await indexClient.CreateIndexAsync(index, TestContext.Current.CancellationToken);
120+
121+
var documents = Enumerable.Range(0, DocumentCount)
122+
.Select(i => new SearchDocument { ["Id"] = i.ToString("D3"), ["Name"] = "Document " + i })
123+
.ToList();
124+
125+
await searchClient.IndexDocumentsAsync(
126+
IndexDocumentsBatch.Upload(documents),
127+
cancellationToken: TestContext.Current.CancellationToken);
128+
129+
return (indexClient, searchClient, indexName);
130+
}
131+
}
Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
using System.Text.Json.Nodes;
2+
using AzureSearchEmulator.Indexing;
3+
using AzureSearchEmulator.Models;
4+
using AzureSearchEmulator.SearchData;
5+
using AzureSearchEmulator.Searching;
6+
using Lucene.Net.Index;
7+
using Lucene.Net.Store;
8+
using Xunit;
9+
10+
namespace AzureSearchEmulator.UnitTests;
11+
12+
/// <summary>
13+
/// Covers the next page a search offers, which the controller returns as
14+
/// <c>@search.nextPageParameters</c>.
15+
/// </summary>
16+
/// <remarks>
17+
/// Azure offers one only when the request leaves out <c>top</c>: it then returns 50 results and,
18+
/// if more match, a continuation. A request that sets <c>top</c> gets no continuation.
19+
/// </remarks>
20+
public class SearchPagingTests : IDisposable
21+
{
22+
private const int DocumentCount = 120;
23+
24+
private readonly RAMDirectory _directory = new();
25+
private readonly SearchIndex _index;
26+
private readonly LuceneNetIndexWriterFactory _writerFactory;
27+
private readonly LuceneNetIndexSearcher _searcher;
28+
29+
public SearchPagingTests()
30+
{
31+
_index = new SearchIndex
32+
{
33+
Name = "paged",
34+
Fields =
35+
[
36+
new SearchField { Name = "Id", Type = "Edm.String", Key = true, Searchable = false, Filterable = true, Sortable = true },
37+
new SearchField { Name = "Even", Type = "Edm.Boolean", Filterable = true },
38+
]
39+
};
40+
41+
var factory = new SharedDirectoryFactory(_directory);
42+
_writerFactory = new LuceneNetIndexWriterFactory(factory);
43+
_searcher = new LuceneNetIndexSearcher(factory);
44+
45+
var indexer = new LuceneNetSearchIndexer(_writerFactory, factory);
46+
47+
indexer.IndexDocuments(_index, Enumerable.Range(0, DocumentCount)
48+
.Select(i => (IndexDocumentAction)new UploadIndexDocumentAction(new JsonObject
49+
{
50+
["Id"] = i.ToString("D3"),
51+
["Even"] = i % 2 == 0,
52+
}))
53+
.ToList());
54+
}
55+
56+
public void Dispose()
57+
{
58+
// Writer before directory: it holds an open handle and commits on dispose.
59+
_writerFactory.Dispose();
60+
_directory.Dispose();
61+
}
62+
63+
[Fact]
64+
public async Task WithoutTop_ReturnsTheDefaultPageAndTheSkipForTheNextOne()
65+
{
66+
var response = await _searcher.Search(_index, new SearchRequest());
67+
68+
Assert.Equal(SearchRequest.DefaultTop, response.Results.Count);
69+
Assert.Equal(SearchRequest.DefaultTop, response.NextPageSkip);
70+
}
71+
72+
/// <summary>
73+
/// The walk a client makes by following each continuation: 50, 50, then the last 20, with
74+
/// every document returned once.
75+
/// </summary>
76+
[Fact]
77+
public async Task WithoutTop_FollowingEachNextPage_ReturnsEveryDocumentOnce()
78+
{
79+
var ids = new List<string>();
80+
var pageSizes = new List<int>();
81+
int? skip = 0;
82+
83+
while (skip is { } nextSkip)
84+
{
85+
var response = await _searcher.Search(_index, new SearchRequest { Skip = nextSkip, Orderby = "Id" });
86+
87+
pageSizes.Add(response.Results.Count);
88+
ids.AddRange(response.Results.Select(r => r["Id"]!.GetValue<string>()));
89+
skip = response.NextPageSkip;
90+
}
91+
92+
Assert.Equal([50, 50, 20], pageSizes);
93+
Assert.Equal(Enumerable.Range(0, DocumentCount).Select(i => i.ToString("D3")), ids);
94+
}
95+
96+
[Fact]
97+
public async Task WithoutTop_WhenEveryMatchFitsOnOnePage_OffersNoNextPage()
98+
{
99+
// 60 even documents, so skip 10 leaves exactly 50.
100+
var response = await _searcher.Search(_index, new SearchRequest { Filter = "Even eq true", Skip = 10 });
101+
102+
Assert.Equal(50, response.Results.Count);
103+
Assert.Null(response.NextPageSkip);
104+
}
105+
106+
[Theory]
107+
[InlineData(10)]
108+
[InlineData(SearchRequest.DefaultTop)]
109+
[InlineData(1000)]
110+
public async Task WithTop_OffersNoNextPage(int top)
111+
{
112+
var response = await _searcher.Search(_index, new SearchRequest { Top = top });
113+
114+
Assert.Equal(Math.Min(top, DocumentCount), response.Results.Count);
115+
Assert.Null(response.NextPageSkip);
116+
}
117+
118+
/// <summary>
119+
/// A next page whose skip would pass <see cref="SearchRequest.MaxSkip"/> would be refused when
120+
/// sent back, so none is offered once the limit is reached.
121+
/// </summary>
122+
[Theory]
123+
[InlineData(SearchRequest.MaxSkip - 50, SearchRequest.MaxSkip)]
124+
[InlineData(SearchRequest.MaxSkip - 40, null)]
125+
public async Task WithoutTop_NearTheSkipLimit_OffersANextPageOnlyWithinIt(int skip, int? expectedNextPageSkip)
126+
{
127+
using var directory = new RAMDirectory();
128+
var factory = new SharedDirectoryFactory(directory);
129+
using var writerFactory = new LuceneNetIndexWriterFactory(factory);
130+
131+
new LuceneNetSearchIndexer(writerFactory, factory).IndexDocuments(_index, Enumerable.Range(0, SearchRequest.MaxSkip + 100)
132+
.Select(i => (IndexDocumentAction)new UploadIndexDocumentAction(new JsonObject { ["Id"] = i.ToString("D6") }))
133+
.ToList());
134+
135+
var response = await new LuceneNetIndexSearcher(factory).Search(_index, new SearchRequest { Skip = skip });
136+
137+
Assert.Equal(SearchRequest.DefaultTop, response.Results.Count);
138+
Assert.Equal(expectedNextPageSkip, response.NextPageSkip);
139+
}
140+
141+
private class SharedDirectoryFactory(Lucene.Net.Store.Directory directory) : ILuceneDirectoryFactory, ILuceneIndexReaderFactory
142+
{
143+
public Lucene.Net.Store.Directory GetDirectory(string indexName) => directory;
144+
public void ClearCachedDirectory(string indexName) { }
145+
public IndexReader GetIndexReader(string indexName) => DirectoryReader.Open(directory);
146+
public IndexReader RefreshReader(string indexName) => GetIndexReader(indexName);
147+
public void ClearCachedReader(string indexName) { }
148+
}
149+
}

‎AzureSearchEmulator/Controllers/DocumentSearchingController.cs‎

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
using System.Text.Json.Nodes;
1+
using System.Text.Json;
2+
using System.Text.Json.Nodes;
3+
using System.Text.Json.Serialization;
24
using AzureSearchEmulator.Repositories;
35
using AzureSearchEmulator.Searching;
46
using Microsoft.AspNetCore.Mvc;
@@ -11,6 +13,11 @@ public class DocumentSearchingController(
1113
ISearchIndexRepository searchIndexRepository)
1214
: ODataController
1315
{
16+
private static readonly JsonSerializerOptions NextPageJsonOptions = new(JsonSerializerDefaults.Web)
17+
{
18+
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
19+
};
20+
1421
[HttpGet]
1522
[Route("indexes/{indexKey}/docs/$count")]
1623
[Route("indexes({indexKey})/docs/$count")]
@@ -122,7 +129,7 @@ public async Task<IActionResult> SearchPost(string indexKey, [FromBody] SearchRe
122129
ModelState.AddModelError(nameof(request.Top), "Page size must be between 0 and 1000");
123130
}
124131

125-
if (request.Skip is > 100_000 or < 0)
132+
if (request.Skip is > SearchRequest.MaxSkip or < 0)
126133
{
127134
ModelState.AddModelError(nameof(request.Skip), "Skip must be between 0 and 100,000");
128135
}
@@ -172,6 +179,19 @@ public async Task<IActionResult> SearchPost(string indexKey, [FromBody] SearchRe
172179

173180
oDataResponse["value"] = new JsonArray(response.Results.OfType<JsonNode>().ToArray());
174181

182+
// Only on POST, as in Azure: a GET gets a nextLink to another GET, which is not built here.
183+
if (response.NextPageSkip is { } nextPageSkip && HttpMethods.IsPost(Request.Method))
184+
{
185+
// The same request with skip moved on. Top stays absent, so the next page gets a
186+
// continuation of its own.
187+
var nextPage = JsonSerializer.SerializeToNode(request, NextPageJsonOptions)!.AsObject();
188+
nextPage["skip"] = nextPageSkip;
189+
190+
oDataResponse["@search.nextPageParameters"] = nextPage;
191+
oDataResponse["@odata.nextLink"] =
192+
$"{Request.Scheme}://{Request.Host}{Request.PathBase}/indexes('{indexKey}')/docs/search.post.search{Request.QueryString}";
193+
}
194+
175195
return Ok(oDataResponse);
176196
}
177197

‎AzureSearchEmulator/Searching/LuceneNetIndexSearcher.cs‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@ public async Task<SearchResponse> Search(SearchIndex index, SearchRequest reques
126126

127127
var selection = FieldSelection.Parse(index, request.Select);
128128

129-
var hitsWanted = request.Skip + request.Top;
129+
var hitsWanted = request.Skip + (request.Top ?? SearchRequest.DefaultTop);
130130

131131
var response = new SearchResponse { Coverage = SearchCoverage.GetCoverage(request) };
132132

@@ -177,6 +177,14 @@ public async Task<SearchResponse> Search(SearchIndex index, SearchRequest reques
177177
response.Count = docs.TotalHits;
178178
}
179179

180+
// Azure offers a next page only when the request left out top. A caller that set top
181+
// gets what it asked for and pages with skip itself. A next page past the skip limit
182+
// would be refused, so none is offered.
183+
if (request.Top == null && docs.TotalHits > hitsWanted && hitsWanted <= SearchRequest.MaxSkip)
184+
{
185+
response.NextPageSkip = hitsWanted;
186+
}
187+
180188
if (facets != null)
181189
{
182190
// Counted over the whole match set rather than the page above, so paging never

‎AzureSearchEmulator/Searching/SearchRequest.cs‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,19 @@ public class SearchRequest
4141

4242
public int Skip { get; set; } = 0;
4343

44-
public int Top { get; set; } = 50;
44+
public const int DefaultTop = 50;
45+
46+
public const int MaxSkip = 100_000;
47+
48+
/// <summary>
49+
/// The page size the caller asked for, or null when it did not ask.
50+
/// </summary>
51+
/// <remarks>
52+
/// Null is kept apart from <see cref="DefaultTop"/> because Azure treats them differently:
53+
/// only a request without <c>top</c> gets <c>@search.nextPageParameters</c> when more results
54+
/// match.
55+
/// </remarks>
56+
public int? Top { get; set; }
4557

4658
/// <summary>
4759
/// Vector queries to run against the index's vector fields (issue #46).

‎AzureSearchEmulator/Searching/SearchResponse.cs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,4 +19,9 @@ public class SearchResponse
1919
public double? Coverage { get; set; }
2020

2121
public IList<JsonObject> Results { get; set; } = new List<JsonObject>();
22+
23+
/// <summary>
24+
/// The <c>skip</c> for the next page, or null when there is no next page to offer.
25+
/// </summary>
26+
public int? NextPageSkip { get; set; }
2227
}

0 commit comments

Comments
 (0)