From 83a4d11b509e4c6d5091366f5236c18659e94584 Mon Sep 17 00:00:00 2001 From: Paul Irwin Date: Tue, 27 Oct 2026 07:07:02 -0600 Subject: [PATCH] Add index pages to the web UI (closes #91) Adds an Indexes page listing every index with its document count and size on disk, and a page per index with tabs for its fields and configuration, its documents (paged one at a time or looked up by key), and its raw JSON definition. Both go through the Azure SDK. Along the way: - Implement GET /indexes/{name}/stats (index statistics). - Serialize the index listing like the single-index route, so GetIndexesAsync no longer fails on scoring-profile text weights and the listing includes semantic configurations. - search=* matches every document even when the index has no searchable fields. - Render aria-selected and aria-busy as "true"/"false", so the selected tab on the Search page is styled and announced. Co-Authored-By: Claude Opus 5.5 --- .../DashboardIntegrationTests.cs | 39 ++ .../EmulatorIntegrationTests.cs | 87 +++ .../IndexRoundTripIntegrationTests.cs | 29 +- .../IndexPagesTests.cs | 148 ++++ .../LuceneNetIndexSearcherTests.cs | 26 + .../Components/Layout/MainLayout.razor | 1 + .../Components/Pages/IndexDetails.razor | 642 ++++++++++++++++++ .../Components/Pages/Indexes.razor | 169 +++++ .../Components/Pages/Search.razor | 38 +- .../Controllers/IndexesController.cs | 106 ++- AzureSearchEmulator/Dashboard/ByteSize.cs | 31 + AzureSearchEmulator/Dashboard/DocumentJson.cs | 66 ++ .../Dashboard/EmulatorClientFactory.cs | 8 +- .../Dashboard/ErrorEnvelope.cs | 37 + AzureSearchEmulator/Dashboard/IndexSchema.cs | 93 +++ AzureSearchEmulator/Program.cs | 2 +- .../SearchData/LuceneStorage.cs | 49 ++ .../Searching/LuceneNetIndexSearcher.cs | 5 +- AzureSearchEmulator/wwwroot/css/dashboard.css | 212 +++++- README.md | 4 + 20 files changed, 1712 insertions(+), 80 deletions(-) create mode 100644 AzureSearchEmulator.UnitTests/IndexPagesTests.cs create mode 100644 AzureSearchEmulator/Components/Pages/IndexDetails.razor create mode 100644 AzureSearchEmulator/Components/Pages/Indexes.razor create mode 100644 AzureSearchEmulator/Dashboard/ByteSize.cs create mode 100644 AzureSearchEmulator/Dashboard/DocumentJson.cs create mode 100644 AzureSearchEmulator/Dashboard/ErrorEnvelope.cs create mode 100644 AzureSearchEmulator/Dashboard/IndexSchema.cs create mode 100644 AzureSearchEmulator/SearchData/LuceneStorage.cs diff --git a/AzureSearchEmulator.IntegrationTests/DashboardIntegrationTests.cs b/AzureSearchEmulator.IntegrationTests/DashboardIntegrationTests.cs index 8b9192a..b370684 100644 --- a/AzureSearchEmulator.IntegrationTests/DashboardIntegrationTests.cs +++ b/AzureSearchEmulator.IntegrationTests/DashboardIntegrationTests.cs @@ -59,6 +59,45 @@ public async Task Search_ServesThePage() Assert.Contains("href=\"search\" class=\"topnav-link active\"", html); } + /// + /// Like the search page, the index pages render only once their circuit connects (issue #91). + /// They live under /browse because /indexes and /indexes/{name} are the + /// API's own routes. + /// + [Theory] + [InlineData("/browse")] + [InlineData("/browse/test-dashboard-any")] + public async Task Indexes_ServesThePage(string path) + { + await factory.WaitUntilServingAsync(); + using var client = factory.CreateHttpClient(); + + var response = await client.GetAsync(path, TestContext.Current.CancellationToken); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType?.MediaType); + + var html = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken); + + Assert.Contains("href=\"browse\" class=\"topnav-link active\"", html); + } + + /// + /// The other half of the pair: adding pages about indexes must leave the API's index listing + /// answering with JSON. + /// + [Fact] + public async Task IndexesApi_StillAnswersWithJson() + { + await factory.WaitUntilServingAsync(); + using var client = factory.CreateHttpClient(); + + var response = await client.GetAsync("/indexes", TestContext.Current.CancellationToken); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + } + [Fact] public async Task Dashboard_StylesheetIsServed() { diff --git a/AzureSearchEmulator.IntegrationTests/EmulatorIntegrationTests.cs b/AzureSearchEmulator.IntegrationTests/EmulatorIntegrationTests.cs index 3240143..6e5276f 100644 --- a/AzureSearchEmulator.IntegrationTests/EmulatorIntegrationTests.cs +++ b/AzureSearchEmulator.IntegrationTests/EmulatorIntegrationTests.cs @@ -65,6 +65,93 @@ public async Task GetIndexNames_ShouldListCreatedIndex() } } + /// + /// The listing used to go through OData's serializer, which wrote text weights as an array of + /// empty objects the SDK could not read and left out semantic configurations (found while + /// building the dashboard's index pages, issue #91). + /// + [Fact] + public async Task GetIndexes_ReturnsFullDefinitions() + { + const string indexName = "test-get-indexes-full"; + var indexClient = factory.CreateSearchIndexClient(); + + var index = new SearchIndex(indexName) + { + Fields = + { + new SimpleField("id", SearchFieldDataType.String) { IsKey = true }, + new SearchableField("name") + }, + ScoringProfiles = + { + new ScoringProfile("boost") { TextWeights = new TextWeights(new Dictionary { ["name"] = 2 }) } + }, + SemanticSearch = new SemanticSearch + { + Configurations = + { + new SemanticConfiguration("default", new SemanticPrioritizedFields { TitleField = new SemanticField("name") }) + } + } + }; + + await indexClient.CreateIndexAsync(index, TestContext.Current.CancellationToken); + + try + { + SearchIndex? listed = null; + + await foreach (var i in indexClient.GetIndexesAsync(TestContext.Current.CancellationToken)) + { + if (i.Name == indexName) + { + listed = i; + } + } + + Assert.NotNull(listed); + Assert.Equal(2, listed.Fields.Count); + Assert.Equal(2, listed.ScoringProfiles.Single().TextWeights.Weights["name"]); + Assert.Equal("default", listed.SemanticSearch?.Configurations.Single().Name); + } + finally + { + await indexClient.DeleteIndexAsync(indexName, TestContext.Current.CancellationToken); + } + } + + /// + /// The dashboard's index pages show these, so the SDK has to be able to read them (issue #91). + /// + [Fact] + public async Task GetIndexStatistics_ReportsDocumentsAndStorage() + { + const string indexName = "test-index-statistics"; + var indexClient = factory.CreateSearchIndexClient(); + await CreateIndexAsync(indexClient, indexName); + + try + { + var empty = (await indexClient.GetIndexStatisticsAsync(indexName, TestContext.Current.CancellationToken)).Value; + + Assert.Equal(0, empty.DocumentCount); + + var searchClient = factory.CreateSearchClient(indexName); + await UploadDocumentsAsync(searchClient); + + var statistics = (await indexClient.GetIndexStatisticsAsync(indexName, TestContext.Current.CancellationToken)).Value; + + Assert.Equal(CreateProductDocuments().Count, statistics.DocumentCount); + Assert.True(statistics.StorageSize > empty.StorageSize); + Assert.Equal(0, statistics.VectorIndexSize); + } + finally + { + await indexClient.DeleteIndexAsync(indexName, TestContext.Current.CancellationToken); + } + } + [Fact] public async Task UploadDocuments_ShouldSucceed() { diff --git a/AzureSearchEmulator.IntegrationTests/IndexRoundTripIntegrationTests.cs b/AzureSearchEmulator.IntegrationTests/IndexRoundTripIntegrationTests.cs index ef73c17..2e4da15 100644 --- a/AzureSearchEmulator.IntegrationTests/IndexRoundTripIntegrationTests.cs +++ b/AzureSearchEmulator.IntegrationTests/IndexRoundTripIntegrationTests.cs @@ -127,22 +127,17 @@ public async Task GetModifyPut_DoesNotStripUnmodelledProperties() } /// - /// Documents a known gap rather than a guarantee: the collection listing still serializes - /// through OData, which emits only what the EDM model declares, so the properties preserved - /// through the extension bag are absent there. + /// The collection listing carries the same definition as the individual route, including the + /// properties preserved through the extension bag. /// /// - /// Asserted so the boundary is explicit and a future change to the listing endpoint is a - /// deliberate decision rather than a silent one. If this test starts failing because the - /// properties now appear, that is an improvement — update the test. - /// - /// The gap has narrowed twice: scoringProfiles was listed here until issue #47 made - /// it a modelled property, and vectorSearch until issue #46 did the same. In both - /// cases the EDM model began emitting it and it moved to the assertions below. Anything - /// still named here is genuinely unmodelled. + /// This used to document a gap: the listing serialized through OData, which emits only what + /// the EDM model declares, so corsOptions and the like were missing from it. It moved + /// to the same serializer as the individual route in issue #91, after the SDK's + /// GetIndexesAsync was found failing on OData's rendering of text weights. /// [Fact] - public async Task ListEndpoint_DoesNotYetIncludeUnmodelledProperties() + public async Task ListEndpoint_IncludesTheFullDefinition() { const string indexName = "test-roundtrip-listing"; var client = await CreateClientAsync(); @@ -156,15 +151,7 @@ public async Task ListEndpoint_DoesNotYetIncludeUnmodelledProperties() .FirstOrDefault(i => i?["name"]?.GetValue() == indexName); Assert.NotNull(listed); - Assert.Null(listed["corsOptions"]); - - // Modelled since issues #47 and #46, so the listing carries them like any other - // declared property. - Assert.NotNull(listed["scoringProfiles"]); - Assert.NotNull(listed["vectorSearch"]); - - // The individual route is the one that carries the full definition. - Assert.NotNull((await GetIndexAsync(client, indexName))["corsOptions"]); + Assert.True(JsonNode.DeepEquals(await GetIndexAsync(client, indexName), listed)); await DeleteIndexAsync(client, indexName); } diff --git a/AzureSearchEmulator.UnitTests/IndexPagesTests.cs b/AzureSearchEmulator.UnitTests/IndexPagesTests.cs new file mode 100644 index 0000000..57d0aa5 --- /dev/null +++ b/AzureSearchEmulator.UnitTests/IndexPagesTests.cs @@ -0,0 +1,148 @@ +using Azure.Search.Documents.Indexes.Models; +using AzureSearchEmulator.Dashboard; +using AzureSearchEmulator.SearchData; +using Lucene.Net.Store; +using Xunit; + +namespace AzureSearchEmulator.UnitTests; + +/// +/// Tests for the pieces behind the dashboard's index pages (issue #91) that do not need a running +/// emulator: how a definition is laid out as a table, and how a document is pulled out of a +/// response for its raw view. +/// +public class IndexPagesTests +{ + [Fact] + public void Flatten_PutsSubfieldsAfterTheirParent() + { + var fields = new List + { + new("id", SearchFieldDataType.String) { IsKey = true, IsSortable = true }, + new("address", SearchFieldDataType.Complex) + { + Fields = + { + new SearchField("city", SearchFieldDataType.String) { IsFilterable = true }, + new SearchField("geo", SearchFieldDataType.Complex) + { + Fields = { new SearchField("lat", SearchFieldDataType.Double) } + } + } + }, + new("rating", SearchFieldDataType.Int32) { IsHidden = true } + }; + + var rows = IndexSchema.Flatten(fields); + + Assert.Equal(["id", "address", "address/city", "address/geo", "address/geo/lat", "rating"], rows.Select(i => i.Path)); + Assert.Equal([0, 0, 1, 1, 2, 0], rows.Select(i => i.Depth)); + Assert.True(rows[0].IsKey); + Assert.True(rows[1].IsComplex); + Assert.False(rows[2].IsComplex); + Assert.True(rows[2].Filterable); + Assert.False(rows[5].Retrievable); + Assert.Null(rows[2].Retrievable); + } + + [Fact] + public void Flatten_DescribesAnalyzersAndVectors() + { + var fields = new List + { + new("plain", SearchFieldDataType.String) { AnalyzerName = LexicalAnalyzerName.EnLucene }, + new("split", SearchFieldDataType.String) + { + IndexAnalyzerName = LexicalAnalyzerName.Keyword, + SearchAnalyzerName = LexicalAnalyzerName.StandardLucene + }, + new("vector", SearchFieldDataType.Collection(SearchFieldDataType.Single)) + { + VectorSearchDimensions = 3, + VectorSearchProfileName = "hnsw" + } + }; + + var rows = IndexSchema.Flatten(fields); + + Assert.Equal("en.lucene", rows[0].Analyzer); + Assert.Equal("index: keyword, search: standard.lucene", rows[1].Analyzer); + Assert.Null(rows[2].Analyzer); + Assert.Equal(3, rows[2].Dimensions); + Assert.Equal("hnsw", rows[2].VectorProfile); + Assert.Equal("Collection(Edm.Single)", rows[2].Type); + } + + [Fact] + public void IsKeySortable_FollowsTheKeyField() + { + var sortable = new SearchIndex("a") { Fields = { new SearchField("id", SearchFieldDataType.String) { IsKey = true, IsSortable = true } } }; + var unsortable = new SearchIndex("b") { Fields = { new SearchField("id", SearchFieldDataType.String) { IsKey = true } } }; + + Assert.True(IndexSchema.IsKeySortable(sortable)); + Assert.False(IndexSchema.IsKeySortable(unsortable)); + Assert.Equal("id", IndexSchema.KeyField(sortable)); + } + + [Fact] + public void DocumentJson_TakesTheFirstSearchResultWithoutAnnotations() + { + var json = DocumentJson.Extract("""{"@odata.count": 2, "value": [{"@search.score": 1.0, "id": "1", "name": "Café "}]}"""); + + Assert.Equal("""{"id":"1","name":"Café "}""", json); + } + + [Fact] + public void DocumentJson_TakesALookedUpDocumentAsIs() + { + Assert.Equal("""{"id":"1"}""", DocumentJson.Extract("""{"id": "1"}""")); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("""{"value": []}""")] + [InlineData("not json")] + [InlineData("[1, 2]")] + public void DocumentJson_WithNoDocument_IsNull(string? body) + { + Assert.Null(DocumentJson.Extract(body)); + } + + [Theory] + [InlineData(0, "0 B")] + [InlineData(1023, "1023 B")] + [InlineData(1024, "1 KB")] + [InlineData(1536, "1.5 KB")] + [InlineData(15 * 1024 + 512, "16 KB")] + [InlineData(5L * 1024 * 1024 * 1024, "5 GB")] + public void ByteSize_UsesTheLargestWholeUnit(long bytes, string expected) + { + Assert.Equal(expected, ByteSize.Format(bytes)); + } + + [Fact] + public void LuceneStorage_SumsTheDirectorysFiles() + { + using var directory = new RAMDirectory(); + + foreach (var (name, length) in new[] { ("a", 10), ("b", 32) }) + { + using var output = directory.CreateOutput(name, IOContext.DEFAULT); + output.WriteBytes(new byte[length], length); + } + + Assert.Equal(42, LuceneStorage.GetSize(directory)); + } + + /// + /// An index nothing has been written to yet has no folder on disk. + /// + [Fact] + public void LuceneStorage_OfAMissingDirectory_IsZero() + { + using var directory = new SimpleFSDirectory(Path.Combine(Path.GetTempPath(), "azs-missing-" + Guid.NewGuid().ToString("N"))); + + Assert.Equal(0, LuceneStorage.GetSize(directory)); + } +} diff --git a/AzureSearchEmulator.UnitTests/LuceneNetIndexSearcherTests.cs b/AzureSearchEmulator.UnitTests/LuceneNetIndexSearcherTests.cs index 0f82609..2710417 100644 --- a/AzureSearchEmulator.UnitTests/LuceneNetIndexSearcherTests.cs +++ b/AzureSearchEmulator.UnitTests/LuceneNetIndexSearcherTests.cs @@ -52,6 +52,32 @@ public async Task Search_NullSearch_ReturnsAllDocuments() Assert.Equal(5, response.Results.Count); } + /// + /// A wildcard matches every document whether or not the index has a field to search. It used + /// to fail with "no searchable fields", which the SDK's SearchAsync("*") and the + /// dashboard's document pager both ran into (issue #91). + /// + [Theory] + [InlineData("simple", "*")] + [InlineData("full", "*")] + [InlineData("full", "*:*")] + public async Task Search_Wildcard_OnAnIndexWithNoSearchableFields_ReturnsAllDocuments(string queryType, string search) + { + var index = LuceneTestHelper.CreateCityIndex(); + + foreach (var field in index.Fields) + { + field.Searchable = false; + } + + using var helper = new LuceneTestHelper(index, LuceneTestHelper.CreateCityDocuments()); + var searcher = new LuceneNetIndexSearcher(new StubIndexReaderFactory(helper.Directory)); + + var response = await searcher.Search(index, new SearchRequest { Search = search, QueryType = queryType, Top = 50 }); + + Assert.Equal(6, response.Results.Count); + } + [Fact] public async Task Search_SimpleTextQuery_ReturnsMatchingDocuments() { diff --git a/AzureSearchEmulator/Components/Layout/MainLayout.razor b/AzureSearchEmulator/Components/Layout/MainLayout.razor index fb90392..d10a09b 100644 --- a/AzureSearchEmulator/Components/Layout/MainLayout.razor +++ b/AzureSearchEmulator/Components/Layout/MainLayout.razor @@ -17,6 +17,7 @@ diff --git a/AzureSearchEmulator/Components/Pages/IndexDetails.razor b/AzureSearchEmulator/Components/Pages/IndexDetails.razor new file mode 100644 index 0000000..c6f6e16 --- /dev/null +++ b/AzureSearchEmulator/Components/Pages/IndexDetails.razor @@ -0,0 +1,642 @@ +@page "/browse/{Name}" +@using Azure +@using Azure.Search.Documents +@using Azure.Search.Documents.Models +@using AzureSearchEmulator.Dashboard +@using Azure.Search.Documents.Indexes.Models +@using SdkSearchIndex = Azure.Search.Documents.Indexes.Models.SearchIndex +@* Not prerendered, for the same reason as the search page: every load goes through the SDK. *@ +@rendermode @(new InteractiveServerRenderMode(prerender: false)) +@inject EmulatorClientFactory Clients +@inject NavigationManager Navigation + +@Name · Indexes · Azure Search Emulator + + + +@if (_loadError is not null) +{ +
+

@Name

+

@_loadError

+
+} +else if (_index is null) +{ +
+ +

Loading @Name…

+
+} +else +{ +
+
+
+

@_index.Name

+

+ @_index.Fields.Count top-level @(_index.Fields.Count == 1 ? "field" : "fields") + @if (_keyField is not null) + { + · key @_keyField + } + @if ((_total ?? _statistics?.DocumentCount) is { } total) + { + · @total.ToString("N0") @(total == 1 ? "document" : "documents") + } + @if (_statistics is { } statistics) + { + · @ByteSize.Format(statistics.StorageSize) on disk + } +

+
+ Search +
+ +
+ + + +
+ +
+ @switch (_tab) + { + case DetailsTab.Documents: + @RenderDocuments() + break; + case DetailsTab.Definition: + @if (_definitionJson is not null) + { +

The definition as the emulator returns it to GET /indexes/@_index.Name.

+ + } + break; + default: + @RenderFields() + break; + } +
+
+} + +@code { + private enum DetailsTab + { + Fields, + Documents, + Definition + } + + [Parameter] + public string Name { get; set; } = ""; + + [SupplyParameterFromQuery(Name = "tab")] + public string? TabQuery { get; set; } + + /// The 1-based position of the document being shown. + [SupplyParameterFromQuery(Name = "doc")] + public int? DocumentQuery { get; set; } + + private string? _loadedName; + private string? _loadError; + private SdkSearchIndex? _index; + private IReadOnlyList _fields = []; + private string? _keyField; + private bool _keySortable; + private string? _definitionJson; + private SearchIndexStatistics? _statistics; + private DetailsTab _tab; + + // Documents tab. _position is null while showing a document looked up by key rather than paged to. + private bool _documentsLoaded; + private bool _loadingDocument; + private long? _total; + private int? _position; + private SearchDocument? _document; + private string? _documentJson; + private string? _documentError; + private int _jumpTo = 1; + private string _lookupKey = ""; + + protected override async Task OnParametersSetAsync() + { + // Query parameters change under the page whenever it updates its own address, which should + // not reload anything. Only following a link to another index does. + if (Name == _loadedName) + { + return; + } + + _loadedName = Name; + _loadError = null; + _index = null; + _documentsLoaded = false; + _total = null; + _statistics = null; + _document = null; + _documentJson = null; + _documentError = null; + + var recorder = new HttpExchangeRecorder(); + + try + { + _index = (await Clients.CreateIndexClient(recorder).GetIndexAsync(Name)).Value; + } + catch (RequestFailedException ex) when (ex.Status == 404) + { + _loadError = $"There is no index or alias named '{Name}'."; + return; + } + catch (Exception ex) when (ex is RequestFailedException or HttpRequestException or InvalidOperationException) + { + _loadError = ex.Message; + return; + } + + _fields = IndexSchema.Flatten(_index.Fields); + _keyField = IndexSchema.KeyField(_index); + _keySortable = IndexSchema.IsKeySortable(_index); + _definitionJson = recorder.LastExchange?.Response?.Body; + _statistics = await GetStatisticsAsync(); + + _tab = TabQuery?.ToLowerInvariant() switch + { + "documents" => DetailsTab.Documents, + "definition" => DetailsTab.Definition, + _ => DetailsTab.Fields + }; + + if (_tab == DetailsTab.Documents || DocumentQuery is not null) + { + _tab = DetailsTab.Documents; + await ShowDocumentAtAsync(Math.Max(0, (DocumentQuery ?? 1) - 1)); + } + } + + /// + /// The page is still useful without them, so a failure only leaves the size out. + /// + private async Task GetStatisticsAsync() + { + try + { + return (await Clients.CreateIndexClient().GetIndexStatisticsAsync(_index!.Name)).Value; + } + catch (Exception ex) when (ex is RequestFailedException or HttpRequestException) + { + return null; + } + } + + private async Task SelectTabAsync(DetailsTab tab) + { + _tab = tab; + + if (tab == DetailsTab.Documents && !_documentsLoaded) + { + await ShowDocumentAtAsync(0); + } + + UpdateAddress(); + } + + /// + /// Fetches the document at a 0-based position with a match-all search for a single result, which + /// is the only way the API offers to walk an index's documents. + /// + private async Task ShowDocumentAtAsync(int position) + { + if (_index is null || _loadingDocument) + { + return; + } + + _loadingDocument = true; + _documentError = null; + + var recorder = new HttpExchangeRecorder(); + + try + { + var page = await FetchAtAsync(position, recorder); + + // A position past the end, from an edited address or documents deleted since, lands on + // the last document rather than on nothing. + if (page.Document is null && page.Total is > 0) + { + position = (int)Math.Min(page.Total.Value - 1, int.MaxValue); + page = await FetchAtAsync(position, recorder); + } + + _total = page.Total; + _position = page.Document is null ? null : position; + _document = page.Document; + _documentJson = page.Json; + _jumpTo = position + 1; + } + catch (RequestFailedException ex) + { + _documentError = ErrorEnvelope.Message(recorder.LastExchange) ?? ex.Message; + } + catch (HttpRequestException ex) + { + _documentError = ex.Message; + } + finally + { + _documentsLoaded = true; + _loadingDocument = false; + } + + UpdateAddress(); + } + + private async Task<(SearchDocument? Document, string? Json, long? Total)> FetchAtAsync(int position, HttpExchangeRecorder recorder) + { + var options = new SearchOptions + { + Size = 1, + Skip = position, + IncludeTotalCount = true + }; + + if (_keySortable) + { + options.OrderBy.Add($"{_keyField} asc"); + } + + var response = await Clients.CreateSearchClient(_index!.Name, recorder).SearchAsync("*", options); + + // Only the page that arrived with the response; enumerating further would follow + // continuation links with requests of their own. + SearchDocument? document = null; + + await foreach (var page in response.Value.GetResultsAsync().AsPages()) + { + document = page.Values.FirstOrDefault()?.Document; + break; + } + + return (document, DocumentJson.Extract(recorder.LastExchange?.Response?.Body), response.Value.TotalCount); + } + + private async Task LookupAsync() + { + var key = _lookupKey.Trim(); + + if (_index is null || key.Length == 0 || _loadingDocument) + { + return; + } + + _loadingDocument = true; + _documentError = null; + + var recorder = new HttpExchangeRecorder(); + + try + { + _document = (await Clients.CreateSearchClient(_index.Name, recorder).GetDocumentAsync(key)).Value; + _documentJson = DocumentJson.Extract(recorder.LastExchange?.Response?.Body); + _position = null; + } + catch (RequestFailedException ex) when (ex.Status == 404) + { + _documentError = $"No document has the key '{key}'."; + } + catch (RequestFailedException ex) + { + _documentError = ErrorEnvelope.Message(recorder.LastExchange) ?? ex.Message; + } + catch (HttpRequestException ex) + { + _documentError = ex.Message; + } + finally + { + _loadingDocument = false; + } + + UpdateAddress(); + } + + private async Task JumpAsync() + { + if (_total is { } total && total > 0) + { + await ShowDocumentAtAsync((int)Math.Clamp(_jumpTo - 1L, 0, Math.Min(total - 1, int.MaxValue))); + } + } + + /// + /// Keeps the tab and document position in the address bar, so a reload or a copied link comes + /// back to the same document. + /// + private void UpdateAddress() + { + var documents = _tab == DetailsTab.Documents; + + var address = Navigation.GetUriWithQueryParameters(new Dictionary + { + ["tab"] = _tab == DetailsTab.Fields ? null : _tab.ToString().ToLowerInvariant(), + ["doc"] = documents && _position is { } position ? position + 1 : null + }); + + if (address != Navigation.Uri) + { + Navigation.NavigateTo(address, replace: true); + } + } + + private RenderFragment RenderFields() => __builder => + { +
+ + + + + + + + + + + + + + + @foreach (var field in _fields) + { + + + + @if (field.IsComplex) + { + @* Complex fields carry no attributes of their own; their subfields do. *@ + + } + else + { + + + + + + + } + + } + +
FieldTypeRetr.SearchFilterSortFacetAnalyzer / vector
+ @field.Path + @if (field.IsKey) + { + key + } + @field.Type@Flag(field.Retrievable)@Flag(field.Searchable)@Flag(field.Filterable)@Flag(field.Sortable)@Flag(field.Facetable) + @if (field.Dimensions is { } dimensions) + { + @dimensions dimensions + @if (field.VectorProfile is { } profile) + { + · @profile + } + } + else + { + @field.Analyzer + } +
+
+

✓ on · blank off · – not set in the definition

+ + @if (_index!.ScoringProfiles.Count > 0) + { +

Scoring profiles

+
+ @foreach (var profile in _index.ScoringProfiles) + { +
+ @profile.Name + @if (profile.Name == _index.DefaultScoringProfile) + { + default + } +
+
@DescribeScoringProfile(profile)
+ } +
+ } + + @if (_index.Suggesters.Count > 0) + { +

Suggesters

+
+ @foreach (var suggester in _index.Suggesters) + { +
@suggester.Name
+
@string.Join(", ", suggester.SourceFields)
+ } +
+ } + + @if (_index.SemanticSearch?.Configurations is { Count: > 0 } semantic) + { +

Semantic configurations

+
+ @foreach (var configuration in semantic) + { + var fields = configuration.PrioritizedFields; + +
+ @configuration.Name + @if (configuration.Name == _index.SemanticSearch.DefaultConfigurationName) + { + default + } +
+
+ @DescribeParts( + ("title", fields.TitleField?.FieldName), + ("content", JoinFields(fields.ContentFields.Select(i => i.FieldName))), + ("keywords", JoinFields(fields.KeywordsFields.Select(i => i.FieldName)))) +
+ } +
+ } + + @if (_index.VectorSearch?.Profiles is { Count: > 0 } vectorProfiles) + { +

Vector profiles

+
+ @foreach (var profile in vectorProfiles) + { +
@profile.Name
+
@DescribeParts(("algorithm", profile.AlgorithmConfigurationName), ("vectorizer", profile.VectorizerName))
+ } +
+ } + + @if (_index.CorsOptions?.AllowedOrigins is { Count: > 0 } origins) + { +

CORS

+
+
Allowed origins
+
@string.Join(", ", origins)
+
+ } + }; + + private RenderFragment RenderDocuments() => __builder => + { + var total = _total ?? 0; + +
+
+ + + + +
+ +
+ + of @total.ToString("N0") + +
+ + @if (_keyField is not null) + { +
+ + +
+ } +
+ + @if (_documentError is not null) + { + + } + + @if (!_documentsLoaded) + { +
+ +

Loading documents…

+
+ } + else if (total == 0 && _document is null) + { +

This index has no documents.

+ } + else if (_document is not null) + { + var key = _keyField is not null && _document.TryGetValue(_keyField, out var keyValue) + ? DocumentValueFormatter.Format(keyValue) + : null; + +
+
+
+

@(key ?? "(no key)")

+
+ + @if (_position is { } position) + { + Document @((position + 1).ToString("N0")) of @total.ToString("N0") + @if (_keySortable) + { + · in key order + } + } + else + { + Looked up by key + } + +
+ +
+ @foreach (var (name, value) in _document) + { +
@name
+
@DocumentValueFormatter.Format(value)
+ } +
+ + @if (_documentJson is not null) + { +
+ JSON + +
+ } +
+ + @if (_fields.Any(i => i.Retrievable == false)) + { +

Fields that are not retrievable are left out, as they are from every query.

+ } + } + }; + + private static RenderFragment Flag(bool? value) => __builder => + { + switch (value) + { + case true: + ✓ + break; + case null: + – + break; + } + }; + + private static string? JoinFields(IEnumerable fields) => + fields.Any() ? string.Join(", ", fields) : null; + + /// Labelled parts, leaving out the ones the definition does not set. + private static string DescribeParts(params (string Label, string? Value)[] parts) => + string.Join(" · ", parts.Where(i => !string.IsNullOrEmpty(i.Value)).Select(i => $"{i.Label}: {i.Value}")); + + private static string DescribeScoringProfile(Azure.Search.Documents.Indexes.Models.ScoringProfile profile) + { + var weights = profile.TextWeights?.Weights is { Count: > 0 } textWeights + ? string.Join(", ", textWeights.Select(i => $"{i.Key} ×{i.Value:0.##}")) + : null; + + var functions = profile.Functions.Count > 0 + ? string.Join(", ", profile.Functions.Select(i => $"{i.GetType().Name.Replace("ScoringFunction", "").ToLowerInvariant()}({i.FieldName})")) + : null; + + var described = DescribeParts(("weights", weights), ("functions", functions)); + + return described.Length > 0 ? described : "No weights or functions"; + } +} diff --git a/AzureSearchEmulator/Components/Pages/Indexes.razor b/AzureSearchEmulator/Components/Pages/Indexes.razor new file mode 100644 index 0000000..ac8a4c2 --- /dev/null +++ b/AzureSearchEmulator/Components/Pages/Indexes.razor @@ -0,0 +1,169 @@ +@page "/browse" +@using Azure +@using AzureSearchEmulator.Dashboard +@using Azure.Search.Documents.Indexes.Models +@using SdkSearchIndex = Azure.Search.Documents.Indexes.Models.SearchIndex +@* Not prerendered, for the same reason as the search page: every load goes through the SDK. *@ +@rendermode @(new InteractiveServerRenderMode(prerender: false)) +@inject EmulatorClientFactory Clients + +Indexes · Azure Search Emulator + +

Indexes

+ +@if (_loadError is not null) +{ +
+

Could not list indexes

+

@_loadError

+
+} +else if (_indexes is null) +{ +
+ +

Loading indexes…

+
+} +else if (_indexes.Count == 0) +{ +
+

No indexes yet

+

+ Create an index through the REST API or an Azure SDK client pointed at this emulator, and + it will be listed here. +

+
+} +else +{ +
+
+

Indexes @_indexes.Count

+
+ +
    + @foreach (var index in _indexes) + { +
  • +
    + @index.Definition.Name +

    + @index.Definition.Fields.Count @(index.Definition.Fields.Count == 1 ? "field" : "fields") + @if (IndexSchema.KeyField(index.Definition) is { } key) + { + · key @key + } +

    + @if (Features(index.Definition) is { Count: > 0 } features) + { +
      + @foreach (var feature in features) + { +
    • @feature
    • + } +
    + } +
    +
    + @if (index.Statistics is { } statistics) + { +

    + @statistics.DocumentCount.ToString("N0") + @(statistics.DocumentCount == 1 ? "document" : "documents") +

    +

    + @ByteSize.Format(statistics.StorageSize) + on disk +

    + } + else + { +

    Statistics unavailable

    + } + Search +
    +
  • + } +
+
+} + +@code { + private sealed record IndexSummary(SdkSearchIndex Definition, SearchIndexStatistics? Statistics); + + private IReadOnlyList? _indexes; + private string? _loadError; + + protected override async Task OnInitializedAsync() + { + var definitions = new List(); + + try + { + await foreach (var index in Clients.CreateIndexClient().GetIndexesAsync()) + { + definitions.Add(index); + } + } + catch (Exception ex) when (ex is RequestFailedException or HttpRequestException or InvalidOperationException) + { + _loadError = ex.Message; + return; + } + + var summaries = await Task.WhenAll(definitions + .OrderBy(i => i.Name, StringComparer.OrdinalIgnoreCase) + .Select(async i => new IndexSummary(i, await GetStatisticsAsync(i.Name)))); + + _indexes = summaries; + } + + /// + /// Statistics that fail leave the rest of the list standing: the definitions are already in + /// hand, and one broken index should not hide the others. + /// + private async Task GetStatisticsAsync(string indexName) + { + try + { + return (await Clients.CreateIndexClient().GetIndexStatisticsAsync(indexName)).Value; + } + catch (Exception ex) when (ex is RequestFailedException or HttpRequestException) + { + return null; + } + } + + /// The optional parts of the definition the index makes use of. + private static List Features(SdkSearchIndex index) + { + var features = new List(); + + if (index.ScoringProfiles.Count > 0) + { + features.Add("Scoring profiles"); + } + + if (index.Suggesters.Count > 0) + { + features.Add("Suggesters"); + } + + if (index.SemanticSearch?.Configurations.Count > 0) + { + features.Add("Semantic"); + } + + if (index.VectorSearch?.Profiles.Count > 0) + { + features.Add("Vector"); + } + + return features; + } + + private static string IndexLink(string name) => $"browse/{Uri.EscapeDataString(name)}"; + + private static string SearchLink(string name) => $"search?index={Uri.EscapeDataString(name)}"; +} diff --git a/AzureSearchEmulator/Components/Pages/Search.razor b/AzureSearchEmulator/Components/Pages/Search.razor index 24eee9f..5f60436 100644 --- a/AzureSearchEmulator/Components/Pages/Search.razor +++ b/AzureSearchEmulator/Components/Pages/Search.razor @@ -1,5 +1,4 @@ @page "/search" -@using System.Text.Json @using Azure @using Azure.Search.Documents.Models @using AzureSearchEmulator.Dashboard @@ -149,9 +148,9 @@ else @if (_exchange is not null || _error is not null) { -
+
- @if (_exchange is not null) { - -