From 81c2d5f18a68837e1d258ca37bf5200e87dbae24 Mon Sep 17 00:00:00 2001 From: Jan Calanog Date: Sat, 24 Oct 2026 02:52:36 +0200 Subject: [PATCH 01/23] Add API property search with direct links to matching fields Co-Authored-By: GPT-6 --- docs/data/openapi/api-explorer.md | 6 + .../PropertyTree/ApiPropertyIndex.cs | 47 +++++ .../Export/OpenApiDocumentExporter.cs | 18 ++ .../OperationPageModel.Properties.cs | 57 ++++++ .../Operations/OperationPageModel.cs | 24 +-- .../ElasticsearchMarkdownExporter.Export.cs | 6 +- .../ElasticsearchMarkdownExporter.cs | 26 +++ .../Assets/api-docs.ts | 13 +- .../Assets/api-link-target-flash.test.ts | 20 +++ .../ModalSearch/ModalSearchResultsList.tsx | 12 +- .../ModalSearch/useModalSearchQuery.ts | 2 + .../NavigationSearch/NavigationSearch.tsx | 15 +- .../NavigationSearchComponent.test.tsx | 60 +++++++ .../NavigationSearchTelemetry.test.tsx | 13 +- .../PropertyResultRow.test.tsx | 50 ++++++ .../NavigationSearch/PropertyResultRow.tsx | 147 +++++++++++++++ .../NavigationSearch/SearchResultsList.tsx | 119 ++++++++++--- .../NavigationSearch/apiPropertyResults.ts | 36 ++++ .../useNavigationSearchQuery.ts | 2 + .../useNavigationSearchTelemetry.ts | 6 +- .../SerializationContext.cs | 1 + .../Common/SourceGenerationContext.cs | 2 + .../Docs/ApiOperationMetadata.cs | 4 + .../Docs/ApiPropertyEntry.cs | 35 ++++ .../Docs/DocumentationMappingExtensions.cs | 3 +- .../Search/SearchResultItem.cs | 1 + .../DefaultSearchService.cs | 1 + .../Highlighting/SearchResultProcessor.cs | 22 ++- .../INavigationSearchService.cs | 12 ++ .../NavigationSearchService.cs | 15 ++ .../Query/SearchQueryBuilder.cs | 88 +++++++++ .../SourceGenerationContext.cs | 2 + .../ApiPropertyIndexTests.cs | 121 +++++++++++++ .../ApiPropertySearchTests.cs | 168 ++++++++++++++++++ 34 files changed, 1097 insertions(+), 57 deletions(-) create mode 100644 src/Elastic.ApiExplorer/Components/PropertyTree/ApiPropertyIndex.cs create mode 100644 src/Elastic.ApiExplorer/Operations/OperationPageModel.Properties.cs create mode 100644 src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.test.tsx create mode 100644 src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.tsx create mode 100644 src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts create mode 100644 src/services/search/Elastic.Documentation.Search.Contract/Docs/ApiPropertyEntry.cs create mode 100644 tests/Elastic.ApiExplorer.Tests/ApiPropertyIndexTests.cs create mode 100644 tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs diff --git a/docs/data/openapi/api-explorer.md b/docs/data/openapi/api-explorer.md index 73880c5b96..6f68708b79 100644 --- a/docs/data/openapi/api-explorer.md +++ b/docs/data/openapi/api-explorer.md @@ -16,6 +16,12 @@ The cards for APIs that are in neither group show the API's deployments as small The API title comes from `info.title` in the spec, so fix naming and description copy in the spec. +API search matches parameter and field names, including prefixes and qualified paths. Direct operation and endpoint matches rank above field matches. Combine an endpoint and a field, such as `_search knn`, to find the operation and its matching fields. Each matching operation lists up to three matching fields beneath it, with their paths, types, and locations. Child rows match the field's own name; ancestor names and descriptions provide context without adding unrelated children. Select a field to open its anchor, including fields inside collapsed sections. Arrow keys move through operations and fields in order; Enter opens the selected row. + +Every result uses the same bordered box, with matching fields grouped beneath the operation when present. Matches use the same yellow tint as the destination property's flash. Navigating to a field reveals it and flashes its name, including when search replaces the current page without a full reload. + +The assembler indexes fields from the same property trees used to render operation pages. Fields of a repeated shape appear under its first listing. On the existing semantic index, the indexer adds the nested `api.properties` mapping before incremental synchronization. Property changes participate in the document hash, so a field update is synchronized even when the operation description stays the same. + :::{warning} This feature is still under development and the functionality described on this page might change. ::: diff --git a/src/Elastic.ApiExplorer/Components/PropertyTree/ApiPropertyIndex.cs b/src/Elastic.ApiExplorer/Components/PropertyTree/ApiPropertyIndex.cs new file mode 100644 index 0000000000..71bcf901d8 --- /dev/null +++ b/src/Elastic.ApiExplorer/Components/PropertyTree/ApiPropertyIndex.cs @@ -0,0 +1,47 @@ +// Licensed to Elasticsearch B.V under one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + +using Elastic.ApiExplorer.Infrastructure; +using Elastic.Documentation.Search.Contract; + +namespace Elastic.ApiExplorer.Components.PropertyTree; + +internal static class ApiPropertyIndex +{ + public static IEnumerable Entries(IEnumerable properties, string location) => + properties.Select( + property => new ApiPropertyEntry + { + Name = property.Name, + Path = string.IsNullOrEmpty(property.JsonPath) ? property.Name : property.JsonPath, + Type = property.Type.Text, + Location = location, + Anchor = property.AnchorId, + Description = ApiMarkdown.StripHtml(ApiSeoDescription.ToPlainText(property.DescriptionMarkdown ?? "")) + } + ); + + public static IEnumerable Flatten(ApiPropertyList properties) + { + foreach (var property in properties.Items) + { + yield return property; + if (property.Children.Properties is { } children) + { + foreach (var child in Flatten(children)) + yield return child; + } + if (property.Children.Dictionary is { } dictionary) + { + foreach (var child in Flatten(dictionary.Properties)) + yield return child; + } + foreach (var child in Flatten(property.Children.Variants)) + yield return child; + } + } + + public static IEnumerable Flatten(ApiUnionVariants? variants) => + variants?.Variants.Where(v => v.ShowProperties && v.Properties is not null).SelectMany(v => Flatten(v.Properties!)) ?? []; +} diff --git a/src/Elastic.ApiExplorer/Export/OpenApiDocumentExporter.cs b/src/Elastic.ApiExplorer/Export/OpenApiDocumentExporter.cs index 01da75bd9f..62c3a499f0 100644 --- a/src/Elastic.ApiExplorer/Export/OpenApiDocumentExporter.cs +++ b/src/Elastic.ApiExplorer/Export/OpenApiDocumentExporter.cs @@ -6,6 +6,7 @@ using System.Runtime.CompilerServices; using System.Text; using System.Text.RegularExpressions; +using Elastic.ApiExplorer.Components.PropertyTree; using Elastic.ApiExplorer.Infrastructure; using Elastic.ApiExplorer.Model; using Elastic.ApiExplorer.Operations; @@ -16,6 +17,7 @@ using Elastic.Documentation.Search; using Elastic.Documentation.Search.Contract; using Elastic.Documentation.Versions; +using Microsoft.AspNetCore.Html; using Microsoft.OpenApi; using Microsoft.OpenApi.Reader; @@ -117,6 +119,21 @@ public IEnumerable ConvertToDocuments(OpenApiDocument ope } var body = bodyBuilder.ToString(); + var apiOperation = new ApiOperation(operation.Key, operation.Value, path.Key, path.Value, product); + var builder = new ApiPropertyTreeBuilder( + openApiDocument, + new PropertyDisplayOptions + { + RenderMarkdown = _ => HtmlString.Empty, + ApiRootUrl = productUrl, + VersionsConfiguration = versionsConfiguration + } + ); + var trees = OperationPageModel.BuildPropertyTrees( + apiOperation, + new SchemaAnalyzer(openApiDocument), + new ParameterRowSource(builder, null, OperationEndpoint.Build(apiOperation, operation.Value.Description, [])) + ); // Extract tags as headings var headings = operation.Value.Tags?.Select(t => t.Name).Where(n => !string.IsNullOrEmpty(n)).OfType().ToArray() @@ -143,6 +160,7 @@ public IEnumerable ConvertToDocuments(OpenApiDocument ope ], Api = new ApiOperationMetadata { + Properties = trees.IndexEntries(), Endpoints = ApiEndpointPath.IndexKeys([path.Key, .. AlternatePaths(operation.Value.Description)]), Method = method, Path = path.Key, diff --git a/src/Elastic.ApiExplorer/Operations/OperationPageModel.Properties.cs b/src/Elastic.ApiExplorer/Operations/OperationPageModel.Properties.cs new file mode 100644 index 0000000000..f745bbf212 --- /dev/null +++ b/src/Elastic.ApiExplorer/Operations/OperationPageModel.Properties.cs @@ -0,0 +1,57 @@ +// Licensed to Elasticsearch B.V under one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + +using Elastic.ApiExplorer.Components.PropertyTree; +using Elastic.ApiExplorer.Model; +using Elastic.Documentation.Search.Contract; +using Microsoft.OpenApi; + +namespace Elastic.ApiExplorer.Operations; + +internal record OperationPropertyTrees( + ApiPropertyList Path, + ApiPropertyList Query, + ApiPropertyList Header, + IReadOnlyList Request, + IReadOnlyList Responses +) +{ + public ApiPropertyEntry[] IndexEntries() => + [ + .. ApiPropertyIndex.Entries(ApiPropertyIndex.Flatten(Path), "path"), + .. ApiPropertyIndex.Entries(ApiPropertyIndex.Flatten(Query), "query"), + .. ApiPropertyIndex.Entries(ApiPropertyIndex.Flatten(Header), "header"), + .. ApiPropertyIndex.Entries(Request.SelectMany(Rows), "request"), + .. Responses.SelectMany(response => ApiPropertyIndex.Entries(response.Contents.SelectMany(Rows), "response")) + ]; + + private static IEnumerable Rows(ApiMediaContent content) => + (content.Properties is { } properties ? ApiPropertyIndex.Flatten(properties) : []).Concat( + ApiPropertyIndex.Flatten(content.UnionVariants) + ); +} + +public partial record OperationPageModel +{ + internal static OperationPropertyTrees BuildPropertyTrees(ApiOperation operation, SchemaAnalyzer analyzer, ParameterRowSource source) + { + // Repeated shapes link to their first listing, so consumers must build in page order. + var path = BuildParameters(operation.Parameters, ParameterLocation.Path, source); + var query = BuildParameters(operation.Parameters, ParameterLocation.Query, source); + var header = BuildParameters(operation.Parameters, ParameterLocation.Header, source); + var request = BuildMediaContents( + operation.Operation.RequestBody?.Content, + new PropertyTreeScope + { + Prefix = "req", + JsonPath = "", + IsRequest = true, + DescriptionOverrides = source.Supplemental?.RequestBodyOverrides + }, + analyzer, + source.Builder + ); + return new OperationPropertyTrees(path, query, header, request, BuildResponses(operation.Operation, analyzer, source.Builder)); + } +} diff --git a/src/Elastic.ApiExplorer/Operations/OperationPageModel.cs b/src/Elastic.ApiExplorer/Operations/OperationPageModel.cs index e152827820..91b4d0e40c 100644 --- a/src/Elastic.ApiExplorer/Operations/OperationPageModel.cs +++ b/src/Elastic.ApiExplorer/Operations/OperationPageModel.cs @@ -179,19 +179,7 @@ public static OperationPageModel Create(ApiOperation apiOperation, ApiRenderCont externalDocs = new ExternalDocLink(url, ApiPropertyTreeBuilder.IsElasticDocsUrl(url), operation.ExternalDocs.Description); } - // Built in page order, before the body, so a field that repeats a parameter's fields links up the page to it. - var parameterSource = new ParameterRowSource(builder, supplemental, endpoint); - var pathParameters = BuildParameters(parameters, ParameterLocation.Path, parameterSource); - var queryParameters = BuildParameters(parameters, ParameterLocation.Query, parameterSource); - var headerParameters = BuildParameters(parameters, ParameterLocation.Header, parameterSource); - var requestScope = new PropertyTreeScope - { - Prefix = "req", - JsonPath = "", - IsRequest = true, - DescriptionOverrides = supplemental?.RequestBodyOverrides - }; - var requestContents = BuildMediaContents(operation.RequestBody?.Content, requestScope, analyzer, builder); + var propertyTrees = BuildPropertyTrees(apiOperation, analyzer, new ParameterRowSource(builder, supplemental, endpoint)); return new OperationPageModel { @@ -203,13 +191,13 @@ public static OperationPageModel Create(ApiOperation apiOperation, ApiRenderCont ExternalDocs = externalDocs, Servers = servers, Endpoint = endpoint, - PathParameters = pathParameters, - QueryParameters = queryParameters, - HeaderParameters = headerParameters, - RequestContents = requestContents, + PathParameters = propertyTrees.Path, + QueryParameters = propertyTrees.Query, + HeaderParameters = propertyTrees.Header, + RequestContents = propertyTrees.Request, DescriptionMarkdown = privileges.Description, PostSections = ApiPostSection.From(context, supplemental?.PostSections ?? []), - Responses = BuildResponses(operation, analyzer, builder), + Responses = propertyTrees.Responses, CodeSamples = codeSamples, RequestExamples = requestExamples, ResponseExamples = responseExamples, diff --git a/src/Elastic.Documentation.Indexing/Exporters/Elasticsearch/ElasticsearchMarkdownExporter.Export.cs b/src/Elastic.Documentation.Indexing/Exporters/Elasticsearch/ElasticsearchMarkdownExporter.Export.cs index cf8d65cbd1..2e865e9732 100644 --- a/src/Elastic.Documentation.Indexing/Exporters/Elasticsearch/ElasticsearchMarkdownExporter.Export.cs +++ b/src/Elastic.Documentation.Indexing/Exporters/Elasticsearch/ElasticsearchMarkdownExporter.Export.cs @@ -5,6 +5,7 @@ using System.Collections.Concurrent; using System.IO.Abstractions; using System.Runtime.CompilerServices; +using System.Text.Json; using Elastic.ApiExplorer; using Elastic.ApiExplorer.Export; using Elastic.ApiExplorer.Model; @@ -55,7 +56,10 @@ private void AssignDocumentMetadata(DocumentationDocument doc) doc.Navigation.TableOfContents.ToString("N0"), doc.ContentTier, _fixedSynonymsHash, - string.Join(",", doc.Parents?.Select(p => $"{p.Path}:{p.Title}") ?? []) + string.Join(",", doc.Parents?.Select(p => $"{p.Path}:{p.Title}") ?? []), + doc.Api is null + ? string.Empty + : JsonSerializer.Serialize(doc.Api, Documentation.Search.Contract.SourceGenerationContext.Default.ApiOperationMetadata) ); doc.Hash = hash; } diff --git a/src/Elastic.Documentation.Indexing/Exporters/Elasticsearch/ElasticsearchMarkdownExporter.cs b/src/Elastic.Documentation.Indexing/Exporters/Elasticsearch/ElasticsearchMarkdownExporter.cs index 1852c946ca..ab52c1395f 100644 --- a/src/Elastic.Documentation.Indexing/Exporters/Elasticsearch/ElasticsearchMarkdownExporter.cs +++ b/src/Elastic.Documentation.Indexing/Exporters/Elasticsearch/ElasticsearchMarkdownExporter.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information using System.Text.Json; +using System.Text.Json.Nodes; using System.Text.Json.Serialization; using Elastic.Channels; using Elastic.Documentation.Configuration; @@ -171,6 +172,7 @@ IDocumentationConfigurationContext context }; _ = _orchestrator.AddPreBootstrapTask(async (_, ct) => { + await UpdateApiPropertyMapping(ct); _logger.LogInformation("Initializing content date enrichment infrastructure..."); await _contentDateEnrichment.InitializeAsync(ct); _logger.LogInformation("Content date enrichment infrastructure ready"); @@ -227,6 +229,30 @@ private void ConfigureChannelOptions(string label, IngestChannelOptions _transport.PutAsync($"{target}/_mapping", PostData.String(update.ToJsonString()), ctx), + $"PUT {target}/_mapping", + ctx + ).ConfigureAwait(false); + if (!response.ApiCallDetails.HasSuccessfulStatusCode) + throw new InvalidOperationException($"Could not update API property mapping on '{target}': {response}"); + } + /// public async ValueTask StartAsync(Cancel ctx = default) { diff --git a/src/Elastic.Documentation.Site/Assets/api-docs.ts b/src/Elastic.Documentation.Site/Assets/api-docs.ts index 4a83bb23cc..40dea92979 100644 --- a/src/Elastic.Documentation.Site/Assets/api-docs.ts +++ b/src/Elastic.Documentation.Site/Assets/api-docs.ts @@ -233,7 +233,7 @@ const FLASH_CLASS = 'api-link-target-flash' const FLASH_FALLBACK_MS = 3200 const FLASH_SETTLE_MS = 200 const FLASH_GIVE_UP_MS = 10000 -let initialHashFlashDone = false +let initializedHashTarget: HTMLElement | null = null const flashCleanups = new WeakMap void>() @@ -297,6 +297,7 @@ function flashTarget(target: HTMLElement): void { function onHashChange(): void { revealHashTarget() const target = hashTarget() + initializedHashTarget = target if (target) flashTarget(target) } @@ -710,10 +711,8 @@ export function initApiDocs(): void { if (operationSection) initOperationView() // Schema pages too: a link to a field inside a variant that is not picked must show that variant. revealHashTarget() - // initApiDocs also runs for later htmx swaps, which must not replay a flash for a stale hash - if (!initialHashFlashDone) { - initialHashFlashDone = true - const target = hashTarget() - if (target) flashTarget(target) - } + // A replacement page gets a new target element, even when its fragment is unchanged. + const target = hashTarget() + if (target && target !== initializedHashTarget) flashTarget(target) + initializedHashTarget = target } diff --git a/src/Elastic.Documentation.Site/Assets/api-link-target-flash.test.ts b/src/Elastic.Documentation.Site/Assets/api-link-target-flash.test.ts index a33e5fcb5a..45d2a8d531 100644 --- a/src/Elastic.Documentation.Site/Assets/api-link-target-flash.test.ts +++ b/src/Elastic.Documentation.Site/Assets/api-link-target-flash.test.ts @@ -122,6 +122,26 @@ describe('flash of the linked target', () => { expect(flashing('prop-name')).toBe(false) }) + it('flashes a property reached by an htmx search navigation', async () => { + const api = await open('') + api.initApiDocs() + document.body.innerHTML = MARKUP + history.pushState(null, '', '#prop') + api.initApiDocs() + scrollIntoView() + expect(flashing('prop-name')).toBe(true) + }) + + it('flashes the same fragment again when navigation replaces the page', async () => { + const api = await open('#prop') + api.initApiDocs() + scrollIntoView() + document.body.innerHTML = MARKUP + api.initApiDocs() + scrollIntoView() + expect(flashing('prop-name')).toBe(true) + }) + it('waits until the target is on screen', async () => { ;(await open('#prop')).initApiDocs() jest.advanceTimersByTime(1000) diff --git a/src/Elastic.Documentation.Site/Assets/web-components/ModalSearch/ModalSearchResultsList.tsx b/src/Elastic.Documentation.Site/Assets/web-components/ModalSearch/ModalSearchResultsList.tsx index dc4986e1e4..8ab274d1a2 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/ModalSearch/ModalSearchResultsList.tsx +++ b/src/Elastic.Documentation.Site/Assets/web-components/ModalSearch/ModalSearchResultsList.tsx @@ -351,7 +351,11 @@ const Title = ({ text }: { text: string }) => { margin-bottom: calc(${euiTheme.size.xs} / 2); mark { - background-color: ${euiTheme.colors.backgroundLightPrimary}; + background-color: color-mix( + in srgb, + var(--color-yellow-40) 40%, + transparent + ); font-weight: ${euiTheme.font.weight.bold}; color: ${euiTheme.colors.textParagraph}; } @@ -376,7 +380,11 @@ const Description = ({ text }: { text: string }) => { text-overflow: ellipsis; mark { - background-color: ${euiTheme.colors.backgroundLightPrimary}; + background-color: color-mix( + in srgb, + var(--color-yellow-40) 40%, + transparent + ); font-weight: ${euiTheme.font.weight.bold}; } `} diff --git a/src/Elastic.Documentation.Site/Assets/web-components/ModalSearch/useModalSearchQuery.ts b/src/Elastic.Documentation.Site/Assets/web-components/ModalSearch/useModalSearchQuery.ts index 1e830332c6..ffedcd35cc 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/ModalSearch/useModalSearchQuery.ts +++ b/src/Elastic.Documentation.Site/Assets/web-components/ModalSearch/useModalSearchQuery.ts @@ -8,6 +8,7 @@ import { ATTR_ERROR_TYPE, } from '../../telemetry/semconv' import { traceSpan } from '../../telemetry/tracing' +import { ApiPropertyResult } from '../NavigationSearch/apiPropertyResults' import { useIsNavigationSearchAwaitingNewInput, useNavigationSearchCooldownActions, @@ -43,6 +44,7 @@ const SearchResultItem = z.object({ description: z.string(), score: z.number(), parents: z.array(SearchResultItemParent), + properties: z.array(ApiPropertyResult).optional(), }) export type SearchResultItem = z.infer diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearch.tsx b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearch.tsx index db143b33de..1e69d71ecb 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearch.tsx +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearch.tsx @@ -1,6 +1,10 @@ import { availableIcons } from '../../eui-icons-cache' import { SearchInput } from './SearchInput' import { SearchResultsList } from './SearchResultsList' +import { + navigableSearchResults, + type NavigableResult, +} from './apiPropertyResults' import { useSearchTerm, useSearchActions, @@ -48,6 +52,7 @@ export const NavigationSearch = ({ useNavigationSearchTelemetry(typeFilter) const results = data?.results ?? [] + const navigableResults = navigableSearchResults(results) const hasContent = !!searchTerm.trim() const isSearching = isLoading || isFetching @@ -67,7 +72,7 @@ export const NavigationSearch = ({ handleInputKeyDown, handleMouseMove, } = useNavigationSearchKeyboardNavigation({ - resultsCount: results.length, + resultsCount: navigableResults.length, isLoading: isSearching, onClose: () => setIsPopoverOpen(false), onNavigate: handleResultClick, @@ -192,6 +197,8 @@ export const NavigationSearch = ({ {hasContent && (
onMouseMove: () => void onResultClick: () => void @@ -223,6 +232,8 @@ interface SearchDropdownContentProps { } const SearchDropdownContent = ({ + results, + isLoading, isKeyboardNavigating, onMouseMove, onResultClick, @@ -231,6 +242,8 @@ const SearchDropdownContent = ({ return ( <> { }) }) + it('navigates into a matching property and records its anchor on Enter', async () => { + const url = + '/docs/api/doc/elasticsearch/operation/operation-search#req-track_total_hits' + global.fetch = jest.fn().mockResolvedValue({ + ok: true, + json: async () => ({ + ...emptySearch, + totalResults: 1, + results: [ + { + type: 'api', + url: url.split('#')[0], + title: 'Search', + description: 'Search documents', + score: 5, + parents: [], + properties: [ + { + name: 'track_total_hits', + path: 'track_total_hits', + type: 'boolean', + location: 'request', + description: 'Count hits accurately', + anchor: 'req-track_total_hits', + url, + }, + ], + }, + ], + }), + }) + render() + const input = await screen.findByPlaceholderText( + 'Type ❲/❳ to explore API' + ) + await userEvent.type(input, 'track_total') + const child = await screen.findByRole('link', { + name: /track_total_hits boolean request Count hits accurately/, + }) + expect(child).toHaveAttribute('href', url) + const clicked = jest.fn((event: Event) => event.preventDefault()) + child.addEventListener('click', clicked) + await userEvent.click(input) + expect(input).toHaveFocus() + expect(navigationSearchStore.getState().selectedIndex).toBe(0) + await userEvent.keyboard('{ArrowDown}') + expect(navigationSearchStore.getState().selectedIndex).toBe(1) + await waitFor(() => + expect(child).toHaveAttribute('data-selected', 'true') + ) + await userEvent.keyboard('{Enter}') + expect(clicked).toHaveBeenCalledTimes(1) + expect(logInfo).toHaveBeenCalledWith( + 'navigation_search_result_clicked', + expect.objectContaining({ + 'navigation_search.result.anchor': 'req-track_total_hits', + }) + ) + }) + it('renders the sidebar variant without the sticky wrapper or divider', async () => { const { container } = render( diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearchTelemetry.test.tsx b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearchTelemetry.test.tsx index f5f9abee2c..fb7d75cd41 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearchTelemetry.test.tsx +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearchTelemetry.test.tsx @@ -2,6 +2,7 @@ import * as logging from '../../telemetry/logging' import { cooldownStore } from '../shared/cooldown.store' import { NavigationSearch } from './NavigationSearch' import { SearchResultsList } from './SearchResultsList' +import { navigableSearchResults } from './apiPropertyResults' import { navigationSearchStore } from './navigationSearch.store' import * as queryHook from './useNavigationSearchQuery' import { EuiProvider } from '@elastic/eui' @@ -33,7 +34,10 @@ const mockSearchResults = { description: 'Learn about Elasticsearch', score: 0.95, type: 'docs' as const, - parents: [{ title: 'Docs' }, { title: 'Elasticsearch' }], + parents: [ + { title: 'Docs', url: '/docs' }, + { title: 'Elasticsearch', url: '/docs/elasticsearch' }, + ], }, { url: '/docs/kibana/dashboard', @@ -41,7 +45,10 @@ const mockSearchResults = { description: 'Create dashboards', score: 0.85, type: 'docs' as const, - parents: [{ title: 'Docs' }, { title: 'Kibana' }], + parents: [ + { title: 'Docs', url: '/docs' }, + { title: 'Kibana', url: '/docs/kibana' }, + ], }, ], totalResults: 2, @@ -221,6 +228,8 @@ describe('Navigation Search Telemetry Integration', () => { describe('Navigation Search Result Click Tracking', () => { // Shared props for SearchResultsList - reduces duplication const createResultsListProps = () => ({ + results: navigableSearchResults(mockSearchResults.results), + isLoading: false, isKeyboardNavigating: { current: false }, onMouseMove: jest.fn(), onResultClick: jest.fn(), diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.test.tsx b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.test.tsx new file mode 100644 index 0000000000..70e7e72295 --- /dev/null +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.test.tsx @@ -0,0 +1,50 @@ +import { PropertyResultRow } from './PropertyResultRow' +import { EuiProvider } from '@elastic/eui' +import { render, screen } from '@testing-library/react' + +jest.mock('htmx.org', () => ({ process: jest.fn() })) + +it.each([ + ['search knn', 'retriever.knn', ['knn']], + ['_search KNN', 'retriever.knn', ['knn']], + ['search track_total', 'track_total_hits', ['track_total']], + [ + 'elasticsearch.remote_cluster', + '[].elasticsearch.remote_cluster', + ['elasticsearch', 'remote_cluster'], + ], + ['_search knn.field', 'knn.field', ['knn', 'field']], +])('highlights the property match for %s', (searchTerm, path, matches) => { + render( + + + + ) + const row = screen.getByRole('link') + expect( + Array.from(row.querySelectorAll('mark'), (mark) => mark.textContent) + ).toEqual(matches) + expect(row.querySelector('code')).toHaveTextContent(path) +}) diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.tsx b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.tsx new file mode 100644 index 0000000000..3ee4cdb8c8 --- /dev/null +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.tsx @@ -0,0 +1,147 @@ +import { useHtmxLink } from '../shared/htmx/useHtmxLink' +import type { ApiPropertyResult } from './apiPropertyResults' +import { EuiHighlight, useEuiTheme } from '@elastic/eui' +import { css } from '@emotion/react' + +export const PropertyResultRow = ({ + property, + searchTerm, + showLocation, + index, + isSelected, + isKeyboardNavigating, + onMouseEnter, + onMouseMove, + onClick, +}: { + property: ApiPropertyResult + searchTerm: string + showLocation: boolean + index: number + isSelected: boolean + isKeyboardNavigating: boolean + onMouseEnter: () => void + onMouseMove: () => void + onClick: () => void +}) => { + const { euiTheme } = useEuiTheme() + const { ref, href } = useHtmxLink(property.url) + const leafOffset = property.path.lastIndexOf('.') + 1 + const propertySearch = + searchTerm.trim().split(/\s+/).pop()?.split('.').filter(Boolean) ?? [] + return ( + code, + .property-description, + .property-path > span { + min-width: 0; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + color: ${euiTheme.colors.textSubdued}; + } + > code { + flex: 0 1 auto; + max-width: 28%; + font-size: inherit; + line-height: inherit; + } + > .property-path { + display: flex; + max-width: 55%; + color: inherit; + } + .property-path > strong { + flex-shrink: 0; + font-weight: ${euiTheme.font.weight.medium}; + } + .property-location { + order: 1; + flex-shrink: 0; + color: ${euiTheme.colors.textSubdued}; + } + .property-description { + flex: 1; + } + &:hover:not([data-keyboard-navigating='true']) { + background: ${euiTheme.colors.backgroundBaseHighlighted}; + } + &:focus-visible { + outline: 2px solid ${euiTheme.colors.primary}; + outline-offset: -2px; + } + `} + > + + + {property.path.slice(0, leafOffset)} + + + + {property.path.slice(leafOffset)} + + + + {property.type} + + {property.location} + + {property.description} + + ) +} diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.tsx b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.tsx index d609ea78c6..165eba11af 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.tsx +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.tsx @@ -1,16 +1,14 @@ import { config } from '../../config' import { useHtmxLink } from '../shared/htmx/useHtmxLink' +import { PropertyResultRow } from './PropertyResultRow' import { SanitizedHtmlContent } from './SanitizedHtmlContent' +import { type NavigableResult } from './apiPropertyResults' import { useSelectedIndex, useSearchActions, useSearchTerm, } from './navigationSearch.store' -import { - useNavigationSearchQuery, - SearchResultItem, - type TypeFilter, -} from './useNavigationSearchQuery' +import { SearchResultItem, type TypeFilter } from './useNavigationSearchQuery' import { useNavigationSearchTelemetry } from './useNavigationSearchTelemetry' import { EuiBadge, @@ -65,6 +63,8 @@ export const emptyStateCopy = (typeFilter: TypeFilter) => : "We couldn't find a page that matches your search" export interface SearchResultsListProps { + results: NavigableResult[] + isLoading: boolean isKeyboardNavigating: MutableRefObject onMouseMove: () => void onResultClick: () => void @@ -72,6 +72,8 @@ export interface SearchResultsListProps { } export const SearchResultsList = ({ + results, + isLoading, isKeyboardNavigating, onMouseMove, onResultClick, @@ -80,13 +82,11 @@ export const SearchResultsList = ({ const { euiTheme } = useEuiTheme() const selectedIndex = useSelectedIndex() const { setSelectedIndex } = useSearchActions() - const { isLoading, data } = useNavigationSearchQuery(typeFilter) const containerRef = useRef(null) const searchTerm = useSearchTerm() const { trackResultClicked } = useNavigationSearchTelemetry(typeFilter) - const results = data?.results ?? [] - const isInitialLoading = isLoading && !data + const isInitialLoading = isLoading && results.length === 0 // Scroll to top when search term changes useEffect(() => { @@ -156,19 +156,84 @@ export const SearchResultsList = ({ return (
- {results.map((result, index) => ( - handleMouseEnter(index)} - onMouseMove={() => handleItemMouseMove(index)} - onClick={() => handleResultClick(result, index)} - typeFilter={typeFilter} - /> - ))} + {results.map((entry, index) => { + if (entry.kind !== 'operation') return null + const propertyCount = + entry.result.type === 'api' + ? (entry.result.properties?.length ?? 0) + : 0 + const properties = results.slice( + index + 1, + index + 1 + propertyCount + ) + return ( +
+ handleMouseEnter(index)} + onMouseMove={() => handleItemMouseMove(index)} + onClick={() => + handleResultClick(entry.result, index) + } + typeFilter={typeFilter} + /> + {properties.map((child, offset) => { + if (child.kind !== 'property') return null + const propertyIndex = index + offset + 1 + return ( + + other.path === + child.property.path && + other.location !== + child.property.location + ) ?? false + } + isSelected={propertyIndex === selectedIndex} + isKeyboardNavigating={ + isKeyboardNavigating.current + } + onMouseEnter={() => + handleMouseEnter(propertyIndex) + } + onMouseMove={() => + handleItemMouseMove(propertyIndex) + } + onClick={() => { + trackResultClicked({ + query: searchTerm, + position: propertyIndex, + url: child.property.url, + score: child.result.score, + anchor: child.property.anchor, + }) + onResultClick() + }} + /> + ) + })} +
+ ) + })}
) } @@ -382,7 +447,11 @@ const Title = ({ text }: { text: string }) => { margin-bottom: calc(${euiTheme.size.xs} / 2); mark { - background-color: ${euiTheme.colors.backgroundLightPrimary}; + background-color: color-mix( + in srgb, + var(--color-yellow-40) 40%, + transparent + ); font-weight: ${euiTheme.font.weight.bold}; color: ${euiTheme.colors.textParagraph}; } @@ -407,7 +476,11 @@ const Description = ({ text }: { text: string }) => { text-overflow: ellipsis; mark { - background-color: ${euiTheme.colors.backgroundLightPrimary}; + background-color: color-mix( + in srgb, + var(--color-yellow-40) 40%, + transparent + ); font-weight: ${euiTheme.font.weight.bold}; } `} diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts new file mode 100644 index 0000000000..f9d8dfcc2d --- /dev/null +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts @@ -0,0 +1,36 @@ +import type { SearchResultItem } from './useNavigationSearchQuery' +import * as z from 'zod' + +export const ApiPropertyResult = z.object({ + name: z.string(), + path: z.string(), + type: z.string(), + description: z.string(), + anchor: z.string(), + location: z.enum(['path', 'query', 'header', 'request', 'response']), + url: z.string(), +}) + +export type ApiPropertyResult = z.infer + +export type NavigableResult = + | { kind: 'operation'; result: SearchResultItem } + | { + kind: 'property' + result: SearchResultItem + property: ApiPropertyResult + } + +export const navigableSearchResults = ( + results: SearchResultItem[] +): NavigableResult[] => + results.flatMap((result): NavigableResult[] => [ + { kind: 'operation', result }, + ...(result.type === 'api' ? (result.properties ?? []) : []).map( + (property): NavigableResult => ({ + kind: 'property', + result, + property, + }) + ), + ]) diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/useNavigationSearchQuery.ts b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/useNavigationSearchQuery.ts index d3ee170a06..e628fbba3e 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/useNavigationSearchQuery.ts +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/useNavigationSearchQuery.ts @@ -15,6 +15,7 @@ import { isRateLimitError, } from '../shared/errorHandling' import { ApiError } from '../shared/errorHandling' +import { ApiPropertyResult } from './apiPropertyResults' import { usePageNumber, useSearchTerm } from './navigationSearch.store' import { useIsNavigationSearchAwaitingNewInput, @@ -42,6 +43,7 @@ const SearchResultItem = z.object({ description: z.string(), score: z.number(), parents: z.array(SearchResultItemParent), + properties: z.array(ApiPropertyResult).optional(), }) export type SearchResultItem = z.infer diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/useNavigationSearchTelemetry.ts b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/useNavigationSearchTelemetry.ts index 37f951596e..8313289e8d 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/useNavigationSearchTelemetry.ts +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/useNavigationSearchTelemetry.ts @@ -33,6 +33,7 @@ export type NavigationMethod = 'keyboard' | 'mouse' export type NavigationDirection = 'up' | 'down' interface ResultClickParams { + anchor?: string query: string position: number url: string @@ -96,12 +97,15 @@ export const useNavigationSearchTelemetry = ( ) const trackResultClicked = useCallback( - ({ query, position, url, score }: ResultClickParams) => { + ({ query, position, url, score, anchor }: ResultClickParams) => { logInfo('navigation_search_result_clicked', { [ATTR_NAVIGATION_SEARCH_QUERY]: query, [ATTR_NAVIGATION_SEARCH_RESULT_POSITION]: position, [ATTR_NAVIGATION_SEARCH_RESULT_URL]: url, [ATTR_NAVIGATION_SEARCH_RESULT_SCORE]: score, + ...(anchor + ? { 'navigation_search.result.anchor': anchor } + : {}), ...(surface ? { [ATTR_NAVIGATION_SEARCH_SURFACE]: surface } : {}), diff --git a/src/api/Elastic.Documentation.Api/SerializationContext.cs b/src/api/Elastic.Documentation.Api/SerializationContext.cs index d1cbd2cfd1..81e55dbbf0 100644 --- a/src/api/Elastic.Documentation.Api/SerializationContext.cs +++ b/src/api/Elastic.Documentation.Api/SerializationContext.cs @@ -26,6 +26,7 @@ public record OutputMessage(string Role, MessagePart[] Parts, string FinishReaso [JsonSerializable(typeof(PageFeedbackReason))] [JsonSerializable(typeof(NavigationSearchRequest))] [JsonSerializable(typeof(NavigationSearchResponse))] +[JsonSerializable(typeof(NavigationSearchProperty))] [JsonSerializable(typeof(NavigationSearchAggregations))] [JsonSerializable(typeof(InputMessage))] [JsonSerializable(typeof(OutputMessage[]))] diff --git a/src/services/search/Elastic.Documentation.Search.Contract/Common/SourceGenerationContext.cs b/src/services/search/Elastic.Documentation.Search.Contract/Common/SourceGenerationContext.cs index 8ddb038b7f..50a7c13073 100644 --- a/src/services/search/Elastic.Documentation.Search.Contract/Common/SourceGenerationContext.cs +++ b/src/services/search/Elastic.Documentation.Search.Contract/Common/SourceGenerationContext.cs @@ -16,6 +16,8 @@ namespace Elastic.Documentation.Search.Contract; [JsonSerializable(typeof(DocumentationDocument))] [JsonSerializable(typeof(AppliesToEntry))] [JsonSerializable(typeof(ApiOperationMetadata))] +[JsonSerializable(typeof(ApiPropertyEntry))] +[JsonSerializable(typeof(ApiPropertyEntry[]))] [JsonSerializable(typeof(IndexedProduct))] [JsonSerializable(typeof(IndexedProduct[]))] [JsonSerializable(typeof(ParentDocument))] diff --git a/src/services/search/Elastic.Documentation.Search.Contract/Docs/ApiOperationMetadata.cs b/src/services/search/Elastic.Documentation.Search.Contract/Docs/ApiOperationMetadata.cs index c247e85c62..5c1fabece3 100644 --- a/src/services/search/Elastic.Documentation.Search.Contract/Docs/ApiOperationMetadata.cs +++ b/src/services/search/Elastic.Documentation.Search.Contract/Docs/ApiOperationMetadata.cs @@ -13,6 +13,10 @@ namespace Elastic.Documentation.Search.Contract; /// public record ApiOperationMetadata { + [Nested] + [JsonPropertyName("properties")] + public ApiPropertyEntry[] Properties { get; init; } = []; + /// /// Lowercased endpoint paths without the leading /, with and without leading and trailing /// parameters, each parameter stored as *, e.g. */_search and _search. diff --git a/src/services/search/Elastic.Documentation.Search.Contract/Docs/ApiPropertyEntry.cs b/src/services/search/Elastic.Documentation.Search.Contract/Docs/ApiPropertyEntry.cs new file mode 100644 index 0000000000..4ea40809ed --- /dev/null +++ b/src/services/search/Elastic.Documentation.Search.Contract/Docs/ApiPropertyEntry.cs @@ -0,0 +1,35 @@ +// Licensed to Elasticsearch B.V under one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + +using System.Text.Json.Serialization; +using Elastic.Mapping; + +namespace Elastic.Documentation.Search.Contract; + +public record ApiPropertyEntry +{ + [Keyword] + [JsonPropertyName("name")] + public required string Name { get; init; } + + [Keyword] + [JsonPropertyName("path")] + public required string Path { get; init; } + + [Keyword] + [JsonPropertyName("type")] + public required string Type { get; init; } + + [Keyword] + [JsonPropertyName("location")] + public required string Location { get; init; } + + [Keyword] + [JsonPropertyName("anchor")] + public required string Anchor { get; init; } + + [Text] + [JsonPropertyName("description")] + public required string Description { get; init; } +} diff --git a/src/services/search/Elastic.Documentation.Search.Contract/Docs/DocumentationMappingExtensions.cs b/src/services/search/Elastic.Documentation.Search.Contract/Docs/DocumentationMappingExtensions.cs index 01aadb0d09..93edc8b67b 100644 --- a/src/services/search/Elastic.Documentation.Search.Contract/Docs/DocumentationMappingExtensions.cs +++ b/src/services/search/Elastic.Documentation.Search.Contract/Docs/DocumentationMappingExtensions.cs @@ -29,5 +29,6 @@ public static MappingsBuilder AddDocumentationMappings(th .AddProperty("applies_to.type", f => f.Keyword().Normalizer(SharedMappingConfig.KeywordNormalizer)) .AddProperty("applies_to.sub_type", f => f.Keyword().Normalizer(SharedMappingConfig.KeywordNormalizer)) .AddProperty("applies_to.lifecycle", f => f.Keyword().Normalizer(SharedMappingConfig.KeywordNormalizer)) - .AddProperty("applies_to.version", f => f.Version()); + .AddProperty("applies_to.version", f => f.Version()) + .AddProperty("api.properties.path", f => f.Keyword().MultiField("match", mf => mf.Text())); } diff --git a/src/services/search/Elastic.Documentation.Search.Contract/Search/SearchResultItem.cs b/src/services/search/Elastic.Documentation.Search.Contract/Search/SearchResultItem.cs index 129a730c98..ddc668a3b4 100644 --- a/src/services/search/Elastic.Documentation.Search.Contract/Search/SearchResultItem.cs +++ b/src/services/search/Elastic.Documentation.Search.Contract/Search/SearchResultItem.cs @@ -20,4 +20,5 @@ public record SearchResultItem where TDocument : SearchDocumentBase public required string Description { get; init; } public float Score { get; init; } + public IReadOnlyList Properties { get; init; } = []; } diff --git a/src/services/search/Elastic.Documentation.Search/DefaultSearchService.cs b/src/services/search/Elastic.Documentation.Search/DefaultSearchService.cs index 514da91f39..bda4b84937 100644 --- a/src/services/search/Elastic.Documentation.Search/DefaultSearchService.cs +++ b/src/services/search/Elastic.Documentation.Search/DefaultSearchService.cs @@ -115,6 +115,7 @@ public async Task> AutocompleteAsync(Autocomplet postFilter = new TermQuery { Field = QueryFieldNames.ContentType, Value = request.TypeFilter }; var query = request.TypeFilter == ApiContentType ? SearchQueryBuilder.ApplyApiRanking(lexicalQuery, request.Query) : lexicalQuery; + query = SearchQueryBuilder.ApplyApiPropertyQuery(query, request.Query, request.TypeFilter); var response = await client.SearchAsync( s => diff --git a/src/services/search/Elastic.Documentation.Search/Highlighting/SearchResultProcessor.cs b/src/services/search/Elastic.Documentation.Search/Highlighting/SearchResultProcessor.cs index 458a67deb4..bef340b787 100644 --- a/src/services/search/Elastic.Documentation.Search/Highlighting/SearchResultProcessor.cs +++ b/src/services/search/Elastic.Documentation.Search/Highlighting/SearchResultProcessor.cs @@ -2,6 +2,7 @@ // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information +using System.Text.Json; using Elastic.Clients.Elasticsearch.Core.Search; using Elastic.Documentation.Search.Contract; @@ -55,10 +56,29 @@ public static SearchResultItem ProcessHit( Document = doc, Title = title, Description = description, - Score = (float)(hit.Score ?? 0.0) + Score = (float)(hit.Score ?? 0.0), + Properties = MatchedProperties(hit) }; } + private static IReadOnlyList MatchedProperties(Hit hit) + { + if (hit.InnerHits is null || !hit.InnerHits.TryGetValue(SearchQueryBuilder.ApiPropertyHits, out var matches)) + return []; + + return matches + .Hits + .Hits + .OrderByDescending(h => h.Score ?? 0) + .Select( + h => h.Source is JsonElement source ? source.Deserialize(Contract.SourceGenerationContext.Default.ApiPropertyEntry) : null + ) + .OfType() + .DistinctBy(p => p.Anchor) + .Take(3) + .ToArray(); + } + public static IReadOnlyDictionary ExtractTermsAggregation( Clients.Elasticsearch.SearchResponse response, string aggregationName diff --git a/src/services/search/Elastic.Documentation.Search/INavigationSearchService.cs b/src/services/search/Elastic.Documentation.Search/INavigationSearchService.cs index bc18e57b31..71683bef89 100644 --- a/src/services/search/Elastic.Documentation.Search/INavigationSearchService.cs +++ b/src/services/search/Elastic.Documentation.Search/INavigationSearchService.cs @@ -47,6 +47,7 @@ public record NavigationSearchResultItemParent public record NavigationSearchResultItem { + public NavigationSearchProperty[] Properties { get; init; } = []; public required string Type { get; init; } public required string Url { get; init; } public required string Title { get; init; } @@ -54,3 +55,14 @@ public record NavigationSearchResultItem public required NavigationSearchResultItemParent[] Parents { get; init; } public float Score { get; init; } } + +public record NavigationSearchProperty +{ + public required string Name { get; init; } + public required string Path { get; init; } + public required string Type { get; init; } + public required string Description { get; init; } + public required string Anchor { get; init; } + public required string Location { get; init; } + public required string Url { get; init; } +} diff --git a/src/services/search/Elastic.Documentation.Search/NavigationSearchService.cs b/src/services/search/Elastic.Documentation.Search/NavigationSearchService.cs index c7a03fa15d..829698ff61 100644 --- a/src/services/search/Elastic.Documentation.Search/NavigationSearchService.cs +++ b/src/services/search/Elastic.Documentation.Search/NavigationSearchService.cs @@ -52,6 +52,21 @@ public async Task NavigationSearchAsync(NavigationSear Url = item.Document.Path, Title = item.Title, Description = item.Description, + Properties = item + .Properties + .Select( + property => new NavigationSearchProperty + { + Name = property.Name, + Path = property.Path, + Type = property.Type, + Description = property.Description, + Anchor = property.Anchor, + Location = property.Location, + Url = $"{item.Document.Path}#{property.Anchor}" + } + ) + .ToArray(), Parents = (item.Document.Parents ?? []).Select( p => new NavigationSearchResultItemParent { Title = p.Title, Url = p.Path } ).ToArray(), diff --git a/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs b/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs index 43794aeed7..8899512386 100644 --- a/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs +++ b/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs @@ -5,6 +5,7 @@ using Elastic.Documentation.Search.Contract; using Elastic.Clients.Elasticsearch; using Elastic.Clients.Elasticsearch.QueryDsl; +using Elastic.Clients.Elasticsearch.Core.Search; #pragma warning disable IDE0130 // 'Query' subfolder would shadow the ES client's Query type namespace Elastic.Documentation.Search; @@ -16,6 +17,9 @@ namespace Elastic.Documentation.Search; /// public static class SearchQueryBuilder { + public const string ApiPropertyHits = "api_properties"; + private static readonly string[] ApiPropertySourceIncludes = ["api.properties.*"]; + /// /// Rank-feature and term boosts applied as should clauses on top of the base query. /// @@ -37,6 +41,90 @@ public static class SearchQueryBuilder ] }; + public static Query? BuildApiPropertyQuery(string searchQuery, string? typeFilter) + { + var input = searchQuery.Trim(); + if (input.Length == 0 || typeFilter is not (null or "" or "all" or "api")) + return null; + if (typeFilter != "api" && input.Any(char.IsWhiteSpace) && !input.Contains('.') && !input.Contains('_')) + return null; + + var (_, property) = SplitApiPropertyQuery(input); + return new NestedQuery + { + Path = "api.properties", + IgnoreUnmapped = true, + ScoreMode = ChildScoreMode.Max, + Query = BuildPropertyMatchQuery(property), + InnerHits = new InnerHits + { + Name = ApiPropertyHits, + Size = 5, + Source = new SourceConfig(new SourceFilter { Includes = ApiPropertySourceIncludes }) + } + }; + } + + public static Query ApplyApiPropertyQuery(Query query, string searchQuery, string? typeFilter) + { + var properties = BuildApiPropertyQuery(searchQuery, typeFilter); + if (properties is null) + return query; + + var (operation, _) = SplitApiPropertyQuery(searchQuery.Trim()); + if (operation.Length > 0 && (BuildBareWordEndpointQuery(operation) ?? BuildApiEndpointQuery(operation)) is { } endpoint) + properties = new BoolQuery { Must = [properties], Should = [endpoint] }; + + return new BoolQuery { Should = [query, properties], MinimumShouldMatch = 1, Filter = [DocumentFilter] }; + } + + private static (string Operation, string Property) SplitApiPropertyQuery(string input) + { + var separator = input.AsSpan().LastIndexOfAny(" \t\r\n"); + return separator < 0 ? ("", input) : (input[..separator].TrimEnd(), input[(separator + 1)..]); + } + + private static Query BuildPropertyMatchQuery(string input) + { + var name = BuildPropertyNameQuery(input); + var separator = input.LastIndexOf('.'); + if (separator < 0 || separator == input.Length - 1) + return name; + + return new DisMaxQuery + { + Queries = + [ + name, + new BoolQuery + { + Must = [BuildPropertyNameQuery(input[(separator + 1)..])], + Filter = [new MatchBoolPrefixQuery { Field = "api.properties.path.match", Query = input, Operator = Operator.And }] + } + ] + }; + } + + private static Query BuildPropertyNameQuery(string name) => + new DisMaxQuery + { + // Bound field scores below operation matches, regardless of term rarity in nested documents. + Queries = + [ + new ConstantScoreQuery + { + Filter = new TermQuery { Field = "api.properties.name", Value = name, CaseInsensitive = true }, + Boost = 1 + }, + new ConstantScoreQuery + { + // A keyword prefix preserves underscores and field names longer than the edge-ngram limit. + Filter = new PrefixQuery { Field = "api.properties.name", Value = name, CaseInsensitive = true }, + Boost = 0.6f + } + ] + }; + public static Query? BuildDiminishQuery(IReadOnlyCollection diminishTerms) { if (diminishTerms.Count == 0) diff --git a/src/services/search/Elastic.Documentation.Search/SourceGenerationContext.cs b/src/services/search/Elastic.Documentation.Search/SourceGenerationContext.cs index f284668ea1..efe1dadc2a 100644 --- a/src/services/search/Elastic.Documentation.Search/SourceGenerationContext.cs +++ b/src/services/search/Elastic.Documentation.Search/SourceGenerationContext.cs @@ -7,4 +7,6 @@ namespace Elastic.Documentation.Search; [JsonSerializable(typeof(RuleQueryMatchCriteria))] +// The Elasticsearch client reads nested inner-hit sources as object, yielding a JsonElement. +[JsonSerializable(typeof(object))] public sealed partial class SourceGenerationContext : JsonSerializerContext; diff --git a/tests/Elastic.ApiExplorer.Tests/ApiPropertyIndexTests.cs b/tests/Elastic.ApiExplorer.Tests/ApiPropertyIndexTests.cs new file mode 100644 index 0000000000..a5ddec96b2 --- /dev/null +++ b/tests/Elastic.ApiExplorer.Tests/ApiPropertyIndexTests.cs @@ -0,0 +1,121 @@ +// Licensed to Elasticsearch B.V under one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + +using System.IO.Abstractions.TestingHelpers; +using AwesomeAssertions; +using Elastic.ApiExplorer.Components.PropertyTree; +using Elastic.ApiExplorer.Components.PropertyTree._Partials; +using Elastic.ApiExplorer.Export; +using Elastic.ApiExplorer.Infrastructure; +using Elastic.ApiExplorer.Model; +using Elastic.ApiExplorer.Operations; +using Elastic.Documentation; +using Elastic.Documentation.Configuration.Versions; +using Elastic.Documentation.Site.FileProviders; +using Elastic.Documentation.Versions; +using RazorSlices; + +namespace Elastic.ApiExplorer.Tests; + +[ClassDataSource(Shared = SharedType.PerClass)] +public class ApiPropertyIndexTests(ApiExplorerFixture fixture) +{ + [Test] + public async Task Export_NestedDictionaryAndUnion_IndexesRenderedFields() + { + var spec = await TestSpecs.LoadSpecAsync( + """ + { + "openapi":"3.0.3", "info":{"title":"Fields","version":"1"}, + "paths":{"/thing":{"post":{"operationId":"thing","responses":{"200":{"description":"OK"}}, + "requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{ + "flight":{"type":"object","properties":{"travel_agency":{"type":"string","description":"The **agency** name."}}}, + "labels":{"type":"object","additionalProperties":{"type":"object","properties":{"value":{"type":"string"}}}}, + "choice":{"oneOf":[ + {"type":"object","properties":{"code":{"type":"string"}}}, + {"type":"object","properties":{"number":{"type":"integer"}}} + ]} + }}}}}}}} + } + """ + ); + var path = spec.Paths["/thing"]; + var operation = new ApiOperation(HttpMethod.Post, path.Operations![HttpMethod.Post], "/thing", path, "fields"); + var trees = OperationPageModel.BuildPropertyTrees( + operation, + new SchemaAnalyzer(spec), + new ParameterRowSource(TestSpecs.BuilderFor(spec), null, OperationEndpoint.Build(operation, null, [])) + ); + var entries = trees.IndexEntries(); + + entries.Should().Contain( + p => p.Path == "flight.travel_agency" && p.Anchor == "req-flight-travel_agency" && p.Type == "string" && p.Description == + "The agency name." + ); + entries.Should().Contain(p => p.Path == "labels..value" && p.Anchor == "req-labels-string-value"); + entries.Should().Contain(p => p.Path == "choice.code"); + entries.Should().Contain(p => p.Path == "choice.number"); + var html = await _PropertyList.Create(trees.Request[0].Properties!).RenderAsync( + cancellationToken: TestContext.Current!.Execution.CancellationToken + ); + foreach (var entry in entries) + html.Should().Contain($"id=\"{entry.Anchor}\""); + } + + [Test] + public async Task Export_FixtureOperations_EveryPropertyAnchorExistsInRenderedPage() + { + var versions = new VersionsConfiguration + { + VersioningSystems = new Dictionary + { + [VersioningSystemId.Stack] = new VersioningSystem + { + Id = VersioningSystemId.Stack, + Base = new SemVersion(8, 0, 0), + Current = new SemVersion(99, 0, 0) + } + } + }; + var documents = new OpenApiDocumentExporter(versions).ConvertToDocuments(fixture.Document, "fixture").ToArray(); + var propertyCount = 0; + foreach (var document in documents) + { + var navigation = fixture + .Walk() + .OfType() + .First( + n => n.Model.Route == document.Api!.Path && string.Equals( + n.Model.OperationType.Method, + document.Api.Method, + StringComparison.OrdinalIgnoreCase + ) + ); + var context = new ApiRenderContext( + fixture.Context, + fixture.Document, + new StaticFileContentHashProvider(new EmbeddedOrPhysicalFileProvider(fixture.Context)) + ) + { NavigationHtml = "", CurrentNavigation = navigation, MarkdownRenderer = PassthroughMarkdownRenderer.Instance }; + var fs = new MockFileSystem(); + await using (var stream = fs.FileStream.New("/out.html", FileMode.Create, FileAccess.Write)) + await navigation.Model.RenderAsync(stream, context, null, TestContext.Current!.Execution.CancellationToken); + var html = fs.File.ReadAllText("/out.html"); + foreach (var property in document.Api!.Properties) + { + html.Should().Contain($"id=\"{property.Anchor}\"", $"{property.Path} must link to a rendered row"); + property.Path.Should().NotBeNullOrEmpty(); + property.Type.Should().NotBeNullOrEmpty(); + propertyCount++; + } + } + propertyCount.Should().BeGreaterThan(20); + var search = documents.Single(d => d.Api!.OperationId == "search"); + search.Body.Should().Contain("**pretty**").And.Contain("Pretty-print the response body."); + search.Api!.Properties.Should().Contain(p => p.Path == "fields" && p.Anchor == "req-fields" && p.Type == "union string | string[]"); + search.Api.Properties.Should().Contain(p => p.Location == "response"); + search.Api.Properties.Should().Contain(p => p.Location == "query" && p.Name == "pretty"); + search.Api.Properties.Should().Contain(p => p.Path == "pit.id" && p.Anchor == "req-pit-id" && p.Type == "string"); + } +} diff --git a/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs b/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs new file mode 100644 index 0000000000..664d27fcfe --- /dev/null +++ b/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs @@ -0,0 +1,168 @@ +// Licensed to Elasticsearch B.V under one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + +using System.Text.Json; +using AwesomeAssertions; +using Elastic.Clients.Elasticsearch; +using Elastic.Documentation.Configuration; +using Elastic.Documentation.Configuration.Search; +using Elastic.Documentation.Search; +using Elastic.Documentation.Search.Common; +using Elastic.Documentation.Search.Contract; +using Elastic.Documentation.Search.Highlighting; +using Elastic.Transport; +using Elastic.Transport.Extensions; + +namespace Elastic.Documentation.Api.Tests; + +public class ApiPropertySearchTests +{ + private static readonly ElasticsearchClient Client = new(new ElasticsearchClientSettings(new InMemoryRequestInvoker())); + + [Test] + [Arguments("travel_agency", "api")] + [Arguments("trav", "api")] + [Arguments("flight.travel", "api")] + [Arguments("trav", null)] + public void BuildApiPropertyQuery_Identifier_ReturnsNestedInnerHits(string input, string? filter) + { + using var json = JsonDocument.Parse( + Client.RequestResponseSerializer.SerializeToString(SearchQueryBuilder.BuildApiPropertyQuery(input, filter)) + ); + var nested = json.RootElement.GetProperty("nested"); + nested.GetProperty("path").GetString().Should().Be("api.properties"); + nested.GetProperty("inner_hits").GetProperty("size").GetInt32().Should().Be(5); + } + + [Test] + [Arguments("knn", "knn")] + [Arguments("_search knn", "knn")] + [Arguments("GET /_search knn", "knn")] + [Arguments("track_total", "track_total")] + [Arguments("trav", "trav")] + public void BuildApiPropertyQuery_FieldTerm_MatchesOnlyItsOwnNameWithBoundedScores(string input, string name) + { + using var json = JsonDocument.Parse( + Client.RequestResponseSerializer.SerializeToString(SearchQueryBuilder.BuildApiPropertyQuery(input, "api")) + ); + var query = json.RootElement.GetProperty("nested").GetProperty("query"); + var matches = query.GetProperty("dis_max").GetProperty("queries"); + var exact = matches[0].GetProperty("constant_score"); + exact + .GetProperty("filter") + .GetProperty("term") + .GetProperty("api.properties.name") + .GetProperty("value") + .GetString() + .Should() + .Be(name); + query.GetRawText().Should().NotContain("api.properties.description").And.NotContain("api.properties.path"); + matches.GetArrayLength().Should().Be(2); + matches[1] + .GetProperty("constant_score") + .GetProperty("filter") + .GetProperty("prefix") + .GetProperty("api.properties.name") + .GetProperty("value") + .GetString() + .Should() + .Be(name); + var scores = matches.EnumerateArray().Select(q => q.GetProperty("constant_score").GetProperty("boost").GetSingle()).ToArray(); + scores.Should().OnlyContain(score => score > 0 && score <= 1); + scores[0].Should().BeGreaterThan(scores[1], "an exact field name ranks ahead of a prefix"); + } + + [Test] + public void BuildApiPropertyQuery_QualifiedPath_RequiresMatchingLeafAndPath() + { + using var json = JsonDocument.Parse( + Client.RequestResponseSerializer.SerializeToString(SearchQueryBuilder.BuildApiPropertyQuery("_search knn.field", "api")) + ); + var qualified = json + .RootElement + .GetProperty("nested") + .GetProperty("query") + .GetProperty("dis_max") + .GetProperty("queries")[1] + .GetProperty("bool"); + var leaf = qualified + .GetProperty("must") + .GetProperty("dis_max") + .GetProperty("queries")[0] + .GetProperty("constant_score") + .GetProperty("filter"); + leaf.GetProperty("term").GetProperty("api.properties.name").GetProperty("value").GetString().Should().Be("field"); + var path = qualified.GetProperty("filter").GetProperty("match_bool_prefix").GetProperty("api.properties.path.match"); + path.GetProperty("query").GetString().Should().Be("knn.field"); + path.GetProperty("operator").GetString().Should().Be("and"); + } + + [Test] + [Arguments("_search knn")] + [Arguments("GET /_search knn")] + [Arguments("search knn")] + public void ApplyApiPropertyQuery_OperationAndField_RequiresFieldMatchBeforeEndpointBoost(string input) + { + using var json = JsonDocument.Parse( + Client.RequestResponseSerializer.SerializeToString( + SearchQueryBuilder.ApplyApiPropertyQuery(new Elastic.Clients.Elasticsearch.QueryDsl.MatchNoneQuery(), input, "api") + ) + ); + var fieldBranch = json.RootElement.GetProperty("bool").GetProperty("should")[1].GetProperty("bool"); + fieldBranch.GetProperty("must").GetProperty("nested").GetProperty("query").GetRawText().Should().Contain("\"value\":\"knn\""); + var endpoint = fieldBranch.GetProperty("should").GetProperty("dis_max").GetProperty("queries")[0].GetProperty("constant_score"); + endpoint.GetProperty("filter").GetProperty("terms").GetProperty("api.endpoints")[0].GetString().Should().Be("_search"); + } + + [Test] + [Arguments("how to search", null)] + [Arguments("trav", "docs")] + [Arguments("", "api")] + public void BuildApiPropertyQuery_ExcludedQuery_ReturnsNull(string input, string? filter) => + SearchQueryBuilder.BuildApiPropertyQuery(input, filter).Should().BeNull(); + + [Test] + [Arguments(false)] + [Arguments(true)] + public void Mapping_ApiProperties_IsNestedWithKeywordNames(bool semantic) + { + var context = semantic + ? DocumentationMappingContext.DocumentationDocumentSemantic.CreateContext(type: "assembler", env: "test") + : DocumentationMappingContext.DocumentationDocument.CreateContext(type: "assembler", env: "test"); + using var json = JsonDocument.Parse(context.GetMappingsJson()); + var field = json.RootElement.GetProperty("properties").GetProperty("api").GetProperty("properties").GetProperty("properties"); + field.GetProperty("type").GetString().Should().Be("nested"); + var fields = field.GetProperty("properties"); + fields.GetProperty("name").GetProperty("type").GetString().Should().Be("keyword"); + fields.GetProperty("anchor").GetProperty("type").GetString().Should().Be("keyword"); + } + + [Test] + public void ProcessHit_NestedPropertySource_ReturnsMatchingProperty() + { + const string json = + """ + {"took":1,"timed_out":false,"_shards":{"total":1,"successful":1,"failed":0},"hits":{"total":{"value":1,"relation":"eq"},"hits":[ + {"_index":"test","_id":"search","_score":1,"_source":{"title":"Search","search_title":"Search","path":"/search"}, + "inner_hits":{"api_properties":{"hits":{"total":{"value":1,"relation":"eq"},"max_score":5,"hits":[ + {"_index":"test","_id":"search","_score":5,"_nested":{"field":"api.properties","offset":0}, + "_source":{"name":"track_total_hits","path":"track_total_hits","type":"boolean","anchor":"req-track_total_hits","location":"request","description":"Count hits"}} + ]}}}}]}} + """; + using var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json)); + using var accessor = new ElasticsearchClientAccessor( + new DocumentationEndpoints + { + Elasticsearch = new ElasticsearchEndpoint { Uri = new Uri("https://localhost:9200"), ApiKey = "test" } + }, + new SearchConfiguration { Synonyms = [], Rules = [], DiminishTerms = [] } + ); + var response = accessor + .Client + .RequestResponseSerializer + .Deserialize>(stream); + var result = SearchResultProcessor.ProcessHit(response.Hits.Single(), "track_total", new Dictionary()); + result.Properties.Should().ContainSingle().Which.Anchor.Should().Be("req-track_total_hits"); + } +} From 8fe995a794d70fe753746a90764bb8d3549c31e9 Mon Sep 17 00:00:00 2001 From: Jan Calanog Date: Tue, 3 Nov 2026 10:09:45 +0100 Subject: [PATCH 02/23] Move the API property search tests to Vitest Main replaced Jest with Vitest in [#4588](https://github.com/elastic/docs-builder/pull/4588) while this branch was open, so `tsc` no longer knows the `jest` global and the `npm` CI job failed. The tests now use `vi.fn`, and the file-level `htmx.org` mock goes away because `setupTests.ts` already mocks it for every file. The property navigation test also looks for the "Explore APIs" placeholder that [#4565](https://github.com/elastic/docs-builder/pull/4565) introduced. Co-Authored-By: Claude Fable 5.1 --- .../NavigationSearch/NavigationSearchComponent.test.tsx | 8 +++----- .../NavigationSearch/PropertyResultRow.test.tsx | 8 +++----- 2 files changed, 6 insertions(+), 10 deletions(-) diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearchComponent.test.tsx b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearchComponent.test.tsx index 8b8cb27189..a94688d857 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearchComponent.test.tsx +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearchComponent.test.tsx @@ -59,7 +59,7 @@ describe('NavigationSearchWrapper type attribute', () => { it('navigates into a matching property and records its anchor on Enter', async () => { const url = '/docs/api/doc/elasticsearch/operation/operation-search#req-track_total_hits' - global.fetch = jest.fn().mockResolvedValue({ + global.fetch = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ ...emptySearch, @@ -88,15 +88,13 @@ describe('NavigationSearchWrapper type attribute', () => { }), }) render() - const input = await screen.findByPlaceholderText( - 'Type ❲/❳ to explore API' - ) + const input = await screen.findByPlaceholderText('Explore APIs') await userEvent.type(input, 'track_total') const child = await screen.findByRole('link', { name: /track_total_hits boolean request Count hits accurately/, }) expect(child).toHaveAttribute('href', url) - const clicked = jest.fn((event: Event) => event.preventDefault()) + const clicked = vi.fn((event: Event) => event.preventDefault()) child.addEventListener('click', clicked) await userEvent.click(input) expect(input).toHaveFocus() diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.test.tsx b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.test.tsx index 70e7e72295..09aa2a1406 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.test.tsx +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.test.tsx @@ -2,8 +2,6 @@ import { PropertyResultRow } from './PropertyResultRow' import { EuiProvider } from '@elastic/eui' import { render, screen } from '@testing-library/react' -jest.mock('htmx.org', () => ({ process: jest.fn() })) - it.each([ ['search knn', 'retriever.knn', ['knn']], ['_search KNN', 'retriever.knn', ['knn']], @@ -36,9 +34,9 @@ it.each([ index={1} isSelected={false} isKeyboardNavigating={false} - onMouseEnter={jest.fn()} - onMouseMove={jest.fn()} - onClick={jest.fn()} + onMouseEnter={vi.fn()} + onMouseMove={vi.fn()} + onClick={vi.fn()} /> ) From 717693ea53b95c1f86fe70738aad24f485613ff3 Mon Sep 17 00:00:00 2001 From: Jan Calanog Date: Tue, 3 Nov 2026 10:50:05 +0100 Subject: [PATCH 03/23] Name the Enter action after its destination in API search "Jump to API" no longer says where Enter leads once a result box holds an operation and its matching fields. An operation row now says "Go to operation", a property row says "Go to property", and a docs page keeps "Jump to". The dropdown footer shows the label of the selected row, so the hint changes as the arrow keys move between an operation and its properties. Co-Authored-By: Claude Fable 5.1 --- .../NavigationSearch/JumpToIndicator.tsx | 22 +++++++ .../NavigationSearch/NavigationSearch.tsx | 25 ++++---- .../NavigationSearchComponent.test.tsx | 4 ++ .../PropertyResultRow.test.tsx | 30 +++++---- .../NavigationSearch/PropertyResultRow.tsx | 21 ++++++- .../NavigationSearch/SearchResultsList.tsx | 27 +------- .../apiPropertyResults.test.ts | 62 +++++++++++++++++++ .../NavigationSearch/apiPropertyResults.ts | 13 ++++ 8 files changed, 155 insertions(+), 49 deletions(-) create mode 100644 src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/JumpToIndicator.tsx create mode 100644 src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.test.ts diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/JumpToIndicator.tsx b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/JumpToIndicator.tsx new file mode 100644 index 0000000000..4431717483 --- /dev/null +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/JumpToIndicator.tsx @@ -0,0 +1,22 @@ +import { EuiBadge, EuiIcon, useEuiTheme } from '@elastic/eui' +import { css } from '@emotion/react' + +export const JumpToIndicator = ({ label }: { label: string }) => { + const { euiTheme } = useEuiTheme() + + return ( +
+ + {label} + +
+ ) +} diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearch.tsx b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearch.tsx index 67ee71b36a..1be724e647 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearch.tsx +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearch.tsx @@ -2,6 +2,8 @@ import { availableIcons } from '../../eui-icons-cache' import { SearchInput } from './SearchInput' import { SearchResultsList } from './SearchResultsList' import { + GO_TO_LABELS, + goToLabel, navigableSearchResults, type NavigableResult, } from './apiPropertyResults' @@ -211,14 +213,8 @@ export const NavigationSearch = ({ ) } -const KEYBOARD_SHORTCUTS = [ - { keys: ['returnKey'], label: 'Jump to' }, - { keys: ['sortUp', 'sortDown'], label: 'Navigate' }, - { keys: ['Esc'], label: 'Close' }, -] - -const API_KEYBOARD_SHORTCUTS = [ - { keys: ['returnKey'], label: 'Jump to API' }, +const keyboardShortcuts = (enterLabel: string) => [ + { keys: ['returnKey'], label: enterLabel }, { keys: ['sortUp', 'sortDown'], label: 'Navigate' }, { keys: ['Esc'], label: 'Close' }, ] @@ -240,6 +236,12 @@ const SearchDropdownContent = ({ onResultClick, typeFilter, }: SearchDropdownContentProps) => { + const selected = results[useSelectedIndex()] + const enterLabel = selected + ? goToLabel(selected) + : typeFilter === 'api' + ? GO_TO_LABELS.operation + : GO_TO_LABELS.page return ( <> - + ) } -const SearchDropdownFooter = ({ typeFilter }: { typeFilter: TypeFilter }) => { +const SearchDropdownFooter = ({ enterLabel }: { enterLabel: string }) => { const { euiTheme } = useEuiTheme() const isMobile = useIsWithinMaxBreakpoint('s') - const shortcuts = - typeFilter === 'api' ? API_KEYBOARD_SHORTCUTS : KEYBOARD_SHORTCUTS + const shortcuts = keyboardShortcuts(enterLabel) if (isMobile) { return null diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearchComponent.test.tsx b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearchComponent.test.tsx index a94688d857..ebba0c30ae 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearchComponent.test.tsx +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearchComponent.test.tsx @@ -99,11 +99,15 @@ describe('NavigationSearchWrapper type attribute', () => { await userEvent.click(input) expect(input).toHaveFocus() expect(navigationSearchStore.getState().selectedIndex).toBe(0) + expect(screen.getAllByText('Go to operation')).toHaveLength(2) + expect(screen.getAllByText('Go to property')).toHaveLength(1) await userEvent.keyboard('{ArrowDown}') expect(navigationSearchStore.getState().selectedIndex).toBe(1) await waitFor(() => expect(child).toHaveAttribute('data-selected', 'true') ) + expect(screen.getAllByText('Go to property')).toHaveLength(2) + expect(screen.getAllByText('Go to operation')).toHaveLength(1) await userEvent.keyboard('{Enter}') expect(clicked).toHaveBeenCalledTimes(1) expect(logInfo).toHaveBeenCalledWith( diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.test.tsx b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.test.tsx index 09aa2a1406..816b9dd02c 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.test.tsx +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.test.tsx @@ -2,17 +2,7 @@ import { PropertyResultRow } from './PropertyResultRow' import { EuiProvider } from '@elastic/eui' import { render, screen } from '@testing-library/react' -it.each([ - ['search knn', 'retriever.knn', ['knn']], - ['_search KNN', 'retriever.knn', ['knn']], - ['search track_total', 'track_total_hits', ['track_total']], - [ - 'elasticsearch.remote_cluster', - '[].elasticsearch.remote_cluster', - ['elasticsearch', 'remote_cluster'], - ], - ['_search knn.field', 'knn.field', ['knn', 'field']], -])('highlights the property match for %s', (searchTerm, path, matches) => { +const renderRow = (searchTerm: string, path: string) => render( ) + +it.each([ + ['search knn', 'retriever.knn', ['knn']], + ['_search KNN', 'retriever.knn', ['knn']], + ['search track_total', 'track_total_hits', ['track_total']], + [ + 'elasticsearch.remote_cluster', + '[].elasticsearch.remote_cluster', + ['elasticsearch', 'remote_cluster'], + ], + ['_search knn.field', 'knn.field', ['knn', 'field']], +])('highlights the property match for %s', (searchTerm, path, matches) => { + renderRow(searchTerm, path) const row = screen.getByRole('link') expect( Array.from(row.querySelectorAll('mark'), (mark) => mark.textContent) ).toEqual(matches) expect(row.querySelector('code')).toHaveTextContent(path) }) + +it('offers "Go to property" as the Enter action', () => { + renderRow('knn', 'retriever.knn') + expect(screen.getByText('Go to property')).toBeInTheDocument() +}) diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.tsx b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.tsx index 3ee4cdb8c8..642aef20c5 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.tsx +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.tsx @@ -1,6 +1,11 @@ import { useHtmxLink } from '../shared/htmx/useHtmxLink' -import type { ApiPropertyResult } from './apiPropertyResults' -import { EuiHighlight, useEuiTheme } from '@elastic/eui' +import { JumpToIndicator } from './JumpToIndicator' +import { GO_TO_LABELS, type ApiPropertyResult } from './apiPropertyResults' +import { + EuiHighlight, + useEuiTheme, + useIsWithinMaxBreakpoint, +} from '@elastic/eui' import { css } from '@emotion/react' export const PropertyResultRow = ({ @@ -25,6 +30,7 @@ export const PropertyResultRow = ({ onClick: () => void }) => { const { euiTheme } = useEuiTheme() + const isMobile = useIsWithinMaxBreakpoint('s') const { ref, href } = useHtmxLink(property.url) const leafOffset = property.path.lastIndexOf('.') + 1 const propertySearch = @@ -110,8 +116,18 @@ export const PropertyResultRow = ({ .property-description { flex: 1; } + .jump-to-indicator { + order: 2; + margin-left: ${euiTheme.size.s}; + } &:hover:not([data-keyboard-navigating='true']) { background: ${euiTheme.colors.backgroundBaseHighlighted}; + .jump-to-indicator { + visibility: visible; + } + } + &[data-selected='true'] .jump-to-indicator { + visibility: visible; } &:focus-visible { outline: 2px solid ${euiTheme.colors.primary}; @@ -142,6 +158,7 @@ export const PropertyResultRow = ({ {property.location} {property.description} + {!isMobile && } ) } diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.tsx b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.tsx index 165eba11af..c1bdafa7b2 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.tsx +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.tsx @@ -1,8 +1,9 @@ import { config } from '../../config' import { useHtmxLink } from '../shared/htmx/useHtmxLink' +import { JumpToIndicator } from './JumpToIndicator' import { PropertyResultRow } from './PropertyResultRow' import { SanitizedHtmlContent } from './SanitizedHtmlContent' -import { type NavigableResult } from './apiPropertyResults' +import { goToLabel, type NavigableResult } from './apiPropertyResults' import { useSelectedIndex, useSearchActions, @@ -11,8 +12,6 @@ import { import { SearchResultItem, type TypeFilter } from './useNavigationSearchQuery' import { useNavigationSearchTelemetry } from './useNavigationSearchTelemetry' import { - EuiBadge, - EuiIcon, EuiLoadingSpinner, useEuiTheme, useEuiOverflowScroll, @@ -355,7 +354,7 @@ const SearchResultRow = ({
{!isMobile && ( )} @@ -489,23 +488,3 @@ const Description = ({ text }: { text: string }) => { ) } - -const JumpToIndicator = ({ label }: { label: string }) => { - const { euiTheme } = useEuiTheme() - - return ( -
- - {label} - -
- ) -} diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.test.ts b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.test.ts new file mode 100644 index 0000000000..a2164cb3dd --- /dev/null +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.test.ts @@ -0,0 +1,62 @@ +import { + goToLabel, + navigableSearchResults, + type ApiPropertyResult, + type NavigableResult, +} from './apiPropertyResults' +import type { SearchResultItem } from './useNavigationSearchQuery' + +const property: ApiPropertyResult = { + name: 'knn', + path: 'knn', + type: 'object', + description: 'Nearest neighbours', + anchor: 'req-knn', + location: 'request', + url: '/docs/api/doc/elasticsearch/operation/operation-search#req-knn', +} + +const operation: SearchResultItem = { + type: 'api', + url: '/docs/api/doc/elasticsearch/operation/operation-search', + title: 'Search', + description: 'Search documents', + score: 5, + parents: [], + properties: [property], +} + +const page: SearchResultItem = { + type: 'docs', + url: '/docs/elasticsearch', + title: 'Elasticsearch', + description: 'Learn about Elasticsearch', + score: 1, + parents: [], +} + +const cases: Array<[string, NavigableResult, string]> = [ + [ + 'an API operation', + { kind: 'operation', result: operation }, + 'Go to operation', + ], + ['a docs page', { kind: 'operation', result: page }, 'Jump to'], + [ + 'a property', + { kind: 'property', result: operation, property }, + 'Go to property', + ], +] + +it.each(cases)('labels the Enter action for %s', (_, entry, label) => { + expect(goToLabel(entry)).toBe(label) +}) + +it('labels the operation and each of its properties in order', () => { + expect(navigableSearchResults([operation, page]).map(goToLabel)).toEqual([ + 'Go to operation', + 'Go to property', + 'Jump to', + ]) +}) diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts index f9d8dfcc2d..fa7703cc65 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts @@ -21,6 +21,19 @@ export type NavigableResult = property: ApiPropertyResult } +export const GO_TO_LABELS = { + page: 'Jump to', + operation: 'Go to operation', + property: 'Go to property', +} as const + +export const goToLabel = (entry: NavigableResult): string => { + if (entry.kind === 'property') return GO_TO_LABELS.property + return entry.result.type === 'api' + ? GO_TO_LABELS.operation + : GO_TO_LABELS.page +} + export const navigableSearchResults = ( results: SearchResultItem[] ): NavigableResult[] => From 6940c5153bc97c76d409144df8f4798e8840f12e Mon Sep 17 00:00:00 2001 From: Jan Calanog Date: Tue, 3 Nov 2026 10:58:25 +0100 Subject: [PATCH 04/23] Keep the footer's Enter hint static as "Go to page" A footer label that changes with the selected row draws the eye on every arrow press. The footer now always says "Go to page", and a docs page row uses the same words so one action has one name. Operation and property rows keep "Go to operation" and "Go to property". Co-Authored-By: Claude Fable 5.1 --- .../NavigationSearch/NavigationSearch.tsx | 17 +++++------------ .../NavigationSearchComponent.test.tsx | 8 ++++---- .../NavigationSearch/apiPropertyResults.test.ts | 4 ++-- .../NavigationSearch/apiPropertyResults.ts | 2 +- 4 files changed, 12 insertions(+), 19 deletions(-) diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearch.tsx b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearch.tsx index 1be724e647..6de25f9300 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearch.tsx +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearch.tsx @@ -3,7 +3,6 @@ import { SearchInput } from './SearchInput' import { SearchResultsList } from './SearchResultsList' import { GO_TO_LABELS, - goToLabel, navigableSearchResults, type NavigableResult, } from './apiPropertyResults' @@ -213,8 +212,8 @@ export const NavigationSearch = ({ ) } -const keyboardShortcuts = (enterLabel: string) => [ - { keys: ['returnKey'], label: enterLabel }, +const KEYBOARD_SHORTCUTS = [ + { keys: ['returnKey'], label: GO_TO_LABELS.page }, { keys: ['sortUp', 'sortDown'], label: 'Navigate' }, { keys: ['Esc'], label: 'Close' }, ] @@ -236,12 +235,6 @@ const SearchDropdownContent = ({ onResultClick, typeFilter, }: SearchDropdownContentProps) => { - const selected = results[useSelectedIndex()] - const enterLabel = selected - ? goToLabel(selected) - : typeFilter === 'api' - ? GO_TO_LABELS.operation - : GO_TO_LABELS.page return ( <> - + ) } -const SearchDropdownFooter = ({ enterLabel }: { enterLabel: string }) => { +const SearchDropdownFooter = () => { const { euiTheme } = useEuiTheme() const isMobile = useIsWithinMaxBreakpoint('s') - const shortcuts = keyboardShortcuts(enterLabel) + const shortcuts = KEYBOARD_SHORTCUTS if (isMobile) { return null diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearchComponent.test.tsx b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearchComponent.test.tsx index ebba0c30ae..5bc063533d 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearchComponent.test.tsx +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearchComponent.test.tsx @@ -99,15 +99,15 @@ describe('NavigationSearchWrapper type attribute', () => { await userEvent.click(input) expect(input).toHaveFocus() expect(navigationSearchStore.getState().selectedIndex).toBe(0) - expect(screen.getAllByText('Go to operation')).toHaveLength(2) - expect(screen.getAllByText('Go to property')).toHaveLength(1) + expect(screen.getByText('Go to operation')).toBeInTheDocument() + expect(screen.getByText('Go to property')).toBeInTheDocument() + expect(screen.getByText('Go to page')).toBeInTheDocument() await userEvent.keyboard('{ArrowDown}') expect(navigationSearchStore.getState().selectedIndex).toBe(1) await waitFor(() => expect(child).toHaveAttribute('data-selected', 'true') ) - expect(screen.getAllByText('Go to property')).toHaveLength(2) - expect(screen.getAllByText('Go to operation')).toHaveLength(1) + expect(screen.getByText('Go to page')).toBeInTheDocument() await userEvent.keyboard('{Enter}') expect(clicked).toHaveBeenCalledTimes(1) expect(logInfo).toHaveBeenCalledWith( diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.test.ts b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.test.ts index a2164cb3dd..752fa3c7bb 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.test.ts +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.test.ts @@ -41,7 +41,7 @@ const cases: Array<[string, NavigableResult, string]> = [ { kind: 'operation', result: operation }, 'Go to operation', ], - ['a docs page', { kind: 'operation', result: page }, 'Jump to'], + ['a docs page', { kind: 'operation', result: page }, 'Go to page'], [ 'a property', { kind: 'property', result: operation, property }, @@ -57,6 +57,6 @@ it('labels the operation and each of its properties in order', () => { expect(navigableSearchResults([operation, page]).map(goToLabel)).toEqual([ 'Go to operation', 'Go to property', - 'Jump to', + 'Go to page', ]) }) diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts index fa7703cc65..749daefa31 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts @@ -22,7 +22,7 @@ export type NavigableResult = } export const GO_TO_LABELS = { - page: 'Jump to', + page: 'Go to page', operation: 'Go to operation', property: 'Go to property', } as const From 3486146ccd71ec32ba3de118f658573149e31160 Mon Sep 17 00:00:00 2001 From: Jan Calanog Date: Tue, 3 Nov 2026 11:02:17 +0100 Subject: [PATCH 05/23] Align the property row's Enter badge with the operation row's The operation row insets its "Go to operation" badge 24px from the box edge while the property row insets "Go to property" 16px, so the two badges did not line up. The property row now uses the same right padding as the operation row. Co-Authored-By: Claude Fable 5.1 --- .../web-components/NavigationSearch/PropertyResultRow.tsx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.tsx b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.tsx index 642aef20c5..53ad51b02a 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.tsx +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.tsx @@ -56,6 +56,8 @@ export const PropertyResultRow = ({ min-height: ${euiTheme.size.xl}; padding: ${euiTheme.size.xs} ${euiTheme.size.base}; padding-left: calc(${euiTheme.size.xl} + ${euiTheme.size.base}); + /* the Enter badge lines up with the operation row's, which insets it by size.l */ + padding-right: ${euiTheme.size.l}; border-bottom: 1px solid ${euiTheme.colors.borderBaseSubdued}; &:last-child { border-bottom: none; From 486e2ab88efaad82177290a7a9f569f812645448 Mon Sep 17 00:00:00 2001 From: Jan Calanog Date: Tue, 3 Nov 2026 11:16:44 +0100 Subject: [PATCH 06/23] Pin property search behaviours before simplifying These tests hold the contract steady for a refactor. The result processor keeps the three best-scoring properties with distinct anchors in score order. The navigation service links a property to its anchor on the operation page. The document hash changes when a property is added or its path changes, through a pure `DocumentHash` split out of `AssignDocumentMetadata`. A property row shows its location only when the same path appears in two locations, and the mouse selects a property row unless the keyboard is driving. Co-Authored-By: Claude Fable 5.1 --- .../ElasticsearchMarkdownExporter.Export.cs | 18 ++-- .../SearchResultsList.test.tsx | 97 +++++++++++++++++++ .../ApiPropertySearchTests.cs | 48 +++++++++ .../NavigationSearchServiceTests.cs | 75 ++++++++++++++ .../DocumentHashTests.cs | 54 +++++++++++ 5 files changed, 281 insertions(+), 11 deletions(-) create mode 100644 tests/Elastic.Documentation.Api.Tests/NavigationSearchServiceTests.cs create mode 100644 tests/Elastic.Documentation.Indexing.Tests/DocumentHashTests.cs diff --git a/src/Elastic.Documentation.Indexing/Exporters/Elasticsearch/ElasticsearchMarkdownExporter.Export.cs b/src/Elastic.Documentation.Indexing/Exporters/Elasticsearch/ElasticsearchMarkdownExporter.Export.cs index d08b186a15..fe73ca8bad 100644 --- a/src/Elastic.Documentation.Indexing/Exporters/Elasticsearch/ElasticsearchMarkdownExporter.Export.cs +++ b/src/Elastic.Documentation.Indexing/Exporters/Elasticsearch/ElasticsearchMarkdownExporter.Export.cs @@ -36,14 +36,12 @@ public partial class ElasticsearchMarkdownExporter // Keyed by reference: BuildContext is a record whose value hash recurses until the stack overflows. private readonly ConcurrentDictionary _apiDocsets = new(ReferenceEqualityComparer.Instance); - /// - /// Assigns hash, last updated, and batch index date to a documentation document. - /// - private void AssignDocumentMetadata(DocumentationDocument doc) - { - var semanticHash = _semanticTypeContext?.Hash ?? string.Empty; - var lexicalHash = _lexicalTypeContext.Hash; - var hash = HashedBulkUpdate.CreateHash( + private void AssignDocumentMetadata(DocumentationDocument doc) => + doc.Hash = DocumentHash(doc, _semanticTypeContext?.Hash ?? string.Empty, _lexicalTypeContext.Hash, _fixedSynonymsHash); + + /// The change-detection hash. Everything the index stores for a page takes part, so a metadata-only edit still syncs. + internal static string DocumentHash(DocumentationDocument doc, string semanticHash, string lexicalHash, string synonymsHash) => + HashedBulkUpdate.CreateHash( semanticHash, lexicalHash, doc.Path, @@ -55,14 +53,12 @@ private void AssignDocumentMetadata(DocumentationDocument doc) doc.Navigation.Depth.ToString("N0"), doc.Navigation.TableOfContents.ToString("N0"), doc.ContentTier, - _fixedSynonymsHash, + synonymsHash, string.Join(",", doc.Parents?.Select(p => $"{p.Path}:{p.Title}") ?? []), doc.Api is null ? string.Empty : JsonSerializer.Serialize(doc.Api, Documentation.Search.Contract.SourceGenerationContext.Default.ApiOperationMetadata) ); - doc.Hash = hash; - } /// Computes and assigns the whitespace-normalized content hash for change detection. private static void AssignContentHash(DocumentationDocument doc) => diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.test.tsx b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.test.tsx index 3858ac91dd..67095b55de 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.test.tsx +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.test.tsx @@ -1,8 +1,19 @@ +import { renderWithProviders } from '../../test-utils/render' import { + SearchResultsList, emptyStateCopy, formatApiProductCrumb, navigationSearchBreadcrumbs, } from './SearchResultsList' +import { navigableSearchResults } from './apiPropertyResults' +import { navigationSearchStore } from './navigationSearch.store' +import type { SearchResultItem } from './useNavigationSearchQuery' +import { screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' + +vi.mock('../../telemetry/logging', async () => + (await import('../../test-utils/mocks')).logging() +) describe('navigationSearchBreadcrumbs', () => { it('uses API plus the product label, not the product key', () => { @@ -66,3 +77,89 @@ describe('emptyStateCopy', () => { ) }) }) + +const property = (path: string, location: 'query' | 'request') => ({ + name: path.split('.').pop() ?? path, + path, + type: 'boolean', + location, + description: 'Count hits', + anchor: `${location}-${path}`, + url: `/docs/api/doc/elasticsearch/operation/operation-search#${location}-${path}`, +}) + +const operation: SearchResultItem = { + type: 'api', + url: '/docs/api/doc/elasticsearch/operation/operation-search', + title: 'Search', + description: 'Run a search', + score: 5, + parents: [], + properties: [ + property('track_total_hits', 'query'), + property('track_total_hits', 'request'), + property('size', 'request'), + ], +} + +const renderList = (isKeyboardNavigating = false) => { + const onMouseMove = vi.fn() + renderWithProviders( + + ) + return { onMouseMove } +} + +describe('property rows', () => { + beforeEach(() => { + navigationSearchStore.getState().actions.setSearchTerm('track_total') + }) + + it('shows the location only when the same path appears in two locations', () => { + renderList() + const query = screen.getByRole('link', { + name: 'track_total_hits boolean query Count hits', + }) + const request = screen.getByRole('link', { + name: 'track_total_hits boolean request Count hits', + }) + const size = screen.getByRole('link', { + name: 'size boolean request Count hits', + }) + expect(query.querySelector('.property-location')).toHaveTextContent( + 'query' + ) + expect(request.querySelector('.property-location')).toHaveTextContent( + 'request' + ) + expect(size.querySelector('.property-location')).toBeNull() + expect(size.querySelector('.sr-only')).toHaveTextContent('request') + }) + + it('selects the property row under the mouse', async () => { + renderList() + const row = screen.getByRole('link', { + name: 'size boolean request Count hits', + }) + await userEvent.hover(row) + expect(navigationSearchStore.getState().selectedIndex).toBe(3) + expect(row).toHaveAttribute('data-selected', 'true') + }) + + it('hands a mouse move back to the parent while the keyboard is driving', async () => { + const { onMouseMove } = renderList(true) + const row = screen.getByRole('link', { + name: 'size boolean request Count hits', + }) + await userEvent.hover(row) + expect(onMouseMove).toHaveBeenCalled() + expect(navigationSearchStore.getState().selectedIndex).toBe(3) + }) +}) diff --git a/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs b/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs index 664d27fcfe..9d1337586d 100644 --- a/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs +++ b/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs @@ -138,6 +138,54 @@ public void Mapping_ApiProperties_IsNestedWithKeywordNames(bool semantic) fields.GetProperty("anchor").GetProperty("type").GetString().Should().Be("keyword"); } + [Test] + public void ProcessHit_ManyInnerHits_KeepsTheThreeBestDistinctAnchorsInScoreOrder() + { + var innerHits = string.Join( + ",", + InnerHit("req-b", 4, "b"), + InnerHit("req-a", 5, "a"), + InnerHit("req-d", 2, "d"), + InnerHit("req-a", 4.5, "other.a"), + InnerHit("req-c", 3, "c") + ); + var json = """ + {"took":1,"timed_out":false,"_shards":{"total":1,"successful":1,"failed":0},"hits":{"total":{"value":1,"relation":"eq"},"hits":[ + {"_index":"test","_id":"search","_score":1,"_source":{"title":"Search","search_title":"Search","path":"/search"}, + "inner_hits":{"api_properties":{"hits":{"total":{"value":5,"relation":"eq"},"max_score":5,"hits":[__INNER_HITS__]}}}}]}} + """.Replace( + "__INNER_HITS__", + innerHits + ); + + var result = SearchResultProcessor.ProcessHit(ParseResponse(json).Hits.Single(), "a", new Dictionary()); + + result.Properties.Select(p => p.Anchor).Should().Equal("req-a", "req-b", "req-c"); + result.Properties.Select(p => p.Path).Should().Equal("a", "b", "c"); + } + + private static string InnerHit(string anchor, double score, string path) => + $$$""" + {"_index":"test","_id":"search","_score":{{{score.ToString(System.Globalization.CultureInfo.InvariantCulture)}}},"_nested":{"field":"api.properties","offset":0}, + "_source":{"name":"{{{path.Split('.')[^1]}}}","path":"{{{path}}}","type":"boolean","anchor":"{{{anchor}}}","location":"request","description":"Count hits"}} + """; + + private static Elastic.Clients.Elasticsearch.SearchResponse ParseResponse(string json) + { + using var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json)); + using var accessor = new ElasticsearchClientAccessor( + new DocumentationEndpoints + { + Elasticsearch = new ElasticsearchEndpoint { Uri = new Uri("https://localhost:9200"), ApiKey = "test" } + }, + new SearchConfiguration { Synonyms = [], Rules = [], DiminishTerms = [] } + ); + return accessor + .Client + .RequestResponseSerializer + .Deserialize>(stream); + } + [Test] public void ProcessHit_NestedPropertySource_ReturnsMatchingProperty() { diff --git a/tests/Elastic.Documentation.Api.Tests/NavigationSearchServiceTests.cs b/tests/Elastic.Documentation.Api.Tests/NavigationSearchServiceTests.cs new file mode 100644 index 0000000000..64f16badfa --- /dev/null +++ b/tests/Elastic.Documentation.Api.Tests/NavigationSearchServiceTests.cs @@ -0,0 +1,75 @@ +// Licensed to Elasticsearch B.V under one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + +using AwesomeAssertions; +using Elastic.Documentation.Configuration; +using Elastic.Documentation.Configuration.Search; +using Elastic.Documentation.Search; +using Elastic.Documentation.Search.Common; +using Elastic.Documentation.Search.Contract; +using FakeItEasy; +using Microsoft.Extensions.Logging.Abstractions; + +namespace Elastic.Documentation.Api.Tests; + +public class NavigationSearchServiceTests +{ + [Test] + public async Task NavigationSearchAsync_PropertyHit_LinksToTheAnchorOnTheOperationPage() + { + var inner = A.Fake>(); + var document = new DocumentationDocument + { + Title = "Search", + SearchTitle = "Search", + Path = "/docs/api/doc/elasticsearch/operation/operation-search" + }; + var property = new ApiPropertyEntry + { + Name = "knn", + Path = "knn", + Type = "object", + Location = "request", + Anchor = "req-knn", + Description = "Approximate kNN" + }; + _ = A.CallTo( + () => inner.AutocompleteAsync(A._, A._) + ).Returns(new AutocompleteResponse + { + Results = + [ + new SearchResultItem + { + Document = document, + Title = "Search", + Description = "Run a search", + Score = 5, + Properties = [property] + } + ], + TotalResults = 1, + PageNumber = 1, + PageSize = 20, + Aggregations = new AutocompleteAggregations() + }); + using var accessor = new ElasticsearchClientAccessor( + new DocumentationEndpoints + { + Elasticsearch = new ElasticsearchEndpoint { Uri = new Uri("https://localhost:9200"), ApiKey = "test" } + }, + new SearchConfiguration { Synonyms = [], Rules = [], DiminishTerms = [] } + ); + using var service = new NavigationSearchService(inner, accessor, NullLogger.Instance); + + var response = await service.NavigationSearchAsync(new NavigationSearchRequest { Query = "knn", TypeFilter = "api" }); + + var result = response.Results.Single(); + result.Url.Should().Be("/docs/api/doc/elasticsearch/operation/operation-search"); + var linked = result.Properties.Single(); + linked.Url.Should().Be("/docs/api/doc/elasticsearch/operation/operation-search#req-knn"); + linked.Anchor.Should().Be("req-knn"); + linked.Location.Should().Be("request"); + } +} diff --git a/tests/Elastic.Documentation.Indexing.Tests/DocumentHashTests.cs b/tests/Elastic.Documentation.Indexing.Tests/DocumentHashTests.cs new file mode 100644 index 0000000000..1fa4f6909f --- /dev/null +++ b/tests/Elastic.Documentation.Indexing.Tests/DocumentHashTests.cs @@ -0,0 +1,54 @@ +// Licensed to Elasticsearch B.V under one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + +using AwesomeAssertions; +using Elastic.Documentation.Indexing.Exporters.Elasticsearch; +using Elastic.Documentation.Search.Contract; + +namespace Elastic.Documentation.Indexing.Tests; + +public class DocumentHashTests +{ + private static DocumentationDocument Operation(params ApiPropertyEntry[] properties) => + new() + { + Title = "Search", + SearchTitle = "Search", + Path = "/docs/api/doc/elasticsearch/operation/operation-search", + Body = "Run a search.", + Api = new ApiOperationMetadata + { + Endpoints = ["/_search"], + Method = "POST", + Path = "/_search", + OperationId = "search", + Properties = properties + } + }; + + private static ApiPropertyEntry Property(string path) => + new() + { + Name = path.Split('.')[^1], + Path = path, + Type = "boolean", + Location = "request", + Anchor = $"req-{path.Replace('.', '-')}", + Description = "Count hits" + }; + + private static string Hash(DocumentationDocument doc) => + ElasticsearchMarkdownExporter.DocumentHash(doc, "semantic", "lexical", "synonyms"); + + [Test] + public void DocumentHash_SameProperties_IsStable() => Hash(Operation(Property("knn"))).Should().Be(Hash(Operation(Property("knn")))); + + [Test] + public void DocumentHash_PropertyPathChanges_ChangesTheHash() => + Hash(Operation(Property("track_total_hits"))).Should().NotBe(Hash(Operation(Property("knn.field")))); + + [Test] + public void DocumentHash_PropertyAdded_ChangesTheHash() => + Hash(Operation(Property("knn"))).Should().NotBe(Hash(Operation(Property("knn"), Property("size")))); +} From 8255e41332910a192e3ac9c2e5834f873d4bc52d Mon Sep 17 00:00:00 2001 From: Jan Calanog Date: Tue, 3 Nov 2026 11:35:17 +0100 Subject: [PATCH 07/23] Simplify property search without changing what it does Results are grouped once, in `groupSearchResults`, which numbers the operation and its properties in keyboard order and decides where a location chip is needed. The list only renders those groups, the dropdown loses a one-caller wrapper, both row kinds share one click telemetry path, and the Enter badge owns its own show-on-select rule. The match tint lives in one `--search-highlight-tint` token that the two result lists and the property flash all read. The anchor telemetry attribute joins its siblings in `semconv.ts`, and the modal search drops a `properties` field it never read. On the server, the query builder parses the input once and reads the nested field names from `QueryFieldNames`, the property walk is a single pre-order `SelectMany`, and plain-text descriptions are cached per spec so shared schemas are converted once per indexing run instead of once per operation. Verified against the same cluster: all 18 captured navigation-search responses are byte-identical before and after, and the headless run on localhost:4001 passes every functional check. Co-Authored-By: Claude Fable 5.1 --- .../PropertyTree/ApiPropertyIndex.cs | 42 +++-- .../Export/OpenApiDocumentExporter.cs | 3 +- .../OperationPageModel.Properties.cs | 23 ++- .../Assets/api-docs.css | 6 +- .../Assets/telemetry/semconv.ts | 7 + .../Assets/theme.css | 6 + .../ModalSearch/ModalSearchResultsList.tsx | 12 +- .../ModalSearch/useModalSearchQuery.ts | 2 - .../NavigationSearch/JumpToIndicator.tsx | 4 + .../NavigationSearch/NavigationSearch.tsx | 60 ++---- .../NavigationSearchComponent.test.tsx | 3 +- .../NavigationSearchTelemetry.test.tsx | 4 +- .../PropertyResultRow.test.tsx | 50 +++-- .../NavigationSearch/PropertyResultRow.tsx | 43 ++--- .../SearchResultsList.test.tsx | 39 +++- .../NavigationSearch/SearchResultsList.tsx | 171 +++++++----------- .../apiPropertyResults.test.ts | 86 +++++---- .../NavigationSearch/apiPropertyResults.ts | 60 +++--- .../useNavigationSearchTelemetry.ts | 3 +- .../Query/QueryFieldNames.cs | 3 + .../Query/SearchQueryBuilder.cs | 59 +++--- .../ApiPropertyIndexTests.cs | 2 +- .../ApiPropertySearchTests.cs | 49 ++--- 23 files changed, 353 insertions(+), 384 deletions(-) diff --git a/src/Elastic.ApiExplorer/Components/PropertyTree/ApiPropertyIndex.cs b/src/Elastic.ApiExplorer/Components/PropertyTree/ApiPropertyIndex.cs index 71bcf901d8..1fcb716395 100644 --- a/src/Elastic.ApiExplorer/Components/PropertyTree/ApiPropertyIndex.cs +++ b/src/Elastic.ApiExplorer/Components/PropertyTree/ApiPropertyIndex.cs @@ -9,7 +9,12 @@ namespace Elastic.ApiExplorer.Components.PropertyTree; internal static class ApiPropertyIndex { - public static IEnumerable Entries(IEnumerable properties, string location) => + /// Plain text per description markdown, shared across a spec: shared schemas repeat the same text on every operation. + public static IEnumerable Entries( + IEnumerable properties, + string location, + Dictionary plainDescriptions + ) => properties.Select( property => new ApiPropertyEntry { @@ -18,30 +23,27 @@ public static IEnumerable Entries(IEnumerable pro Type = property.Type.Text, Location = location, Anchor = property.AnchorId, - Description = ApiMarkdown.StripHtml(ApiSeoDescription.ToPlainText(property.DescriptionMarkdown ?? "")) + Description = PlainText(property.DescriptionMarkdown ?? "", plainDescriptions) } ); - public static IEnumerable Flatten(ApiPropertyList properties) + private static string PlainText(string markdown, Dictionary plainDescriptions) { - foreach (var property in properties.Items) - { - yield return property; - if (property.Children.Properties is { } children) - { - foreach (var child in Flatten(children)) - yield return child; - } - if (property.Children.Dictionary is { } dictionary) - { - foreach (var child in Flatten(dictionary.Properties)) - yield return child; - } - foreach (var child in Flatten(property.Children.Variants)) - yield return child; - } + if (!plainDescriptions.TryGetValue(markdown, out var text)) + plainDescriptions[markdown] = text = ApiMarkdown.StripHtml(ApiSeoDescription.ToPlainText(markdown)); + return text; } + /// Every property in page order: each property, then its nested, dictionary and variant children. + public static IEnumerable Flatten(ApiPropertyList? properties) => + properties?.Items.SelectMany( + property => Flatten(property.Children.Properties) + .Concat(Flatten(property.Children.Dictionary?.Properties)) + .Concat(Flatten(property.Children.Variants)) + .Prepend(property) + ) + ?? []; + public static IEnumerable Flatten(ApiUnionVariants? variants) => - variants?.Variants.Where(v => v.ShowProperties && v.Properties is not null).SelectMany(v => Flatten(v.Properties!)) ?? []; + variants?.Variants.Where(v => v.ShowProperties && v.Properties is not null).SelectMany(v => Flatten(v.Properties)) ?? []; } diff --git a/src/Elastic.ApiExplorer/Export/OpenApiDocumentExporter.cs b/src/Elastic.ApiExplorer/Export/OpenApiDocumentExporter.cs index 62c3a499f0..c9f7bebd98 100644 --- a/src/Elastic.ApiExplorer/Export/OpenApiDocumentExporter.cs +++ b/src/Elastic.ApiExplorer/Export/OpenApiDocumentExporter.cs @@ -68,6 +68,7 @@ public IEnumerable ConvertToDocuments(OpenApiDocument ope // All API products currently version against Stack var currentStack = versionsConfiguration.GetVersioningSystem(VersioningSystemId.Stack).Current; + var plainDescriptions = new Dictionary(); foreach (var path in openApiDocument.Paths) { if (path.Value.Operations == null) @@ -160,7 +161,7 @@ public IEnumerable ConvertToDocuments(OpenApiDocument ope ], Api = new ApiOperationMetadata { - Properties = trees.IndexEntries(), + Properties = trees.IndexEntries(plainDescriptions), Endpoints = ApiEndpointPath.IndexKeys([path.Key, .. AlternatePaths(operation.Value.Description)]), Method = method, Path = path.Key, diff --git a/src/Elastic.ApiExplorer/Operations/OperationPageModel.Properties.cs b/src/Elastic.ApiExplorer/Operations/OperationPageModel.Properties.cs index f745bbf212..2dbdebe28a 100644 --- a/src/Elastic.ApiExplorer/Operations/OperationPageModel.Properties.cs +++ b/src/Elastic.ApiExplorer/Operations/OperationPageModel.Properties.cs @@ -17,19 +17,22 @@ internal record OperationPropertyTrees( IReadOnlyList Responses ) { - public ApiPropertyEntry[] IndexEntries() => - [ - .. ApiPropertyIndex.Entries(ApiPropertyIndex.Flatten(Path), "path"), - .. ApiPropertyIndex.Entries(ApiPropertyIndex.Flatten(Query), "query"), - .. ApiPropertyIndex.Entries(ApiPropertyIndex.Flatten(Header), "header"), - .. ApiPropertyIndex.Entries(Request.SelectMany(Rows), "request"), - .. Responses.SelectMany(response => ApiPropertyIndex.Entries(response.Contents.SelectMany(Rows), "response")) + public ApiPropertyEntry[] IndexEntries(Dictionary plainDescriptions) + { + IEnumerable Entries(IEnumerable rows, string location) => + ApiPropertyIndex.Entries(rows, location, plainDescriptions); + + return [ + .. Entries(ApiPropertyIndex.Flatten(Path), "path"), + .. Entries(ApiPropertyIndex.Flatten(Query), "query"), + .. Entries(ApiPropertyIndex.Flatten(Header), "header"), + .. Entries(Request.SelectMany(Rows), "request"), + .. Entries(Responses.SelectMany(response => response.Contents).SelectMany(Rows), "response") ]; + } private static IEnumerable Rows(ApiMediaContent content) => - (content.Properties is { } properties ? ApiPropertyIndex.Flatten(properties) : []).Concat( - ApiPropertyIndex.Flatten(content.UnionVariants) - ); + ApiPropertyIndex.Flatten(content.Properties).Concat(ApiPropertyIndex.Flatten(content.UnionVariants)); } public partial record OperationPageModel diff --git a/src/Elastic.Documentation.Site/Assets/api-docs.css b/src/Elastic.Documentation.Site/Assets/api-docs.css index b492b778c8..73e1457b1b 100644 --- a/src/Elastic.Documentation.Site/Assets/api-docs.css +++ b/src/Elastic.Documentation.Site/Assets/api-docs.css @@ -4158,11 +4158,7 @@ html:has(.api-page-shell) { /* Marks what a link points at: one soft pulse. A property row pulses on its name; the padding with a matching negative margin gives the tint room around the text without moving anything. */ .api-link-target-flash { - --api-link-flash-tint: color-mix( - in srgb, - var(--color-yellow-40, #facb3d) 40%, - transparent - ); + --api-link-flash-tint: var(--search-highlight-tint); animation: api-link-target-flash 2.4s ease-in-out; } diff --git a/src/Elastic.Documentation.Site/Assets/telemetry/semconv.ts b/src/Elastic.Documentation.Site/Assets/telemetry/semconv.ts index 27b7ff6a2e..4fe39d3a2b 100644 --- a/src/Elastic.Documentation.Site/Assets/telemetry/semconv.ts +++ b/src/Elastic.Documentation.Site/Assets/telemetry/semconv.ts @@ -200,6 +200,13 @@ export const ATTR_NAVIGATION_SEARCH_RESULT_POSITION = export const ATTR_NAVIGATION_SEARCH_RESULT_SCORE = 'navigation_search.result.score' +/** + * Anchor of the clicked property on its operation page + * @example "req-track_total_hits" + */ +export const ATTR_NAVIGATION_SEARCH_RESULT_ANCHOR = + 'navigation_search.result.anchor' + /** * Retry-After header value in seconds (for rate limiting) * @example 30 diff --git a/src/Elastic.Documentation.Site/Assets/theme.css b/src/Elastic.Documentation.Site/Assets/theme.css index a898d13bbf..6e02b64f87 100644 --- a/src/Elastic.Documentation.Site/Assets/theme.css +++ b/src/Elastic.Documentation.Site/Assets/theme.css @@ -82,6 +82,12 @@ --color-yellow-20: #fde9b5; --color-yellow-30: #fcd883; --color-yellow-40: #facb3d; + /* search matches and the flash of a linked property share one tint */ + --search-highlight-tint: color-mix( + in srgb, + var(--color-yellow-40) 40%, + transparent + ); --color-yellow-50: #f5bc00; --color-yellow-60: #eaae01; --color-yellow-70: #ca9601; diff --git a/src/Elastic.Documentation.Site/Assets/web-components/ModalSearch/ModalSearchResultsList.tsx b/src/Elastic.Documentation.Site/Assets/web-components/ModalSearch/ModalSearchResultsList.tsx index 8ab274d1a2..c0c47e3d1d 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/ModalSearch/ModalSearchResultsList.tsx +++ b/src/Elastic.Documentation.Site/Assets/web-components/ModalSearch/ModalSearchResultsList.tsx @@ -351,11 +351,7 @@ const Title = ({ text }: { text: string }) => { margin-bottom: calc(${euiTheme.size.xs} / 2); mark { - background-color: color-mix( - in srgb, - var(--color-yellow-40) 40%, - transparent - ); + background-color: var(--search-highlight-tint); font-weight: ${euiTheme.font.weight.bold}; color: ${euiTheme.colors.textParagraph}; } @@ -380,11 +376,7 @@ const Description = ({ text }: { text: string }) => { text-overflow: ellipsis; mark { - background-color: color-mix( - in srgb, - var(--color-yellow-40) 40%, - transparent - ); + background-color: var(--search-highlight-tint); font-weight: ${euiTheme.font.weight.bold}; } `} diff --git a/src/Elastic.Documentation.Site/Assets/web-components/ModalSearch/useModalSearchQuery.ts b/src/Elastic.Documentation.Site/Assets/web-components/ModalSearch/useModalSearchQuery.ts index ffedcd35cc..1e830332c6 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/ModalSearch/useModalSearchQuery.ts +++ b/src/Elastic.Documentation.Site/Assets/web-components/ModalSearch/useModalSearchQuery.ts @@ -8,7 +8,6 @@ import { ATTR_ERROR_TYPE, } from '../../telemetry/semconv' import { traceSpan } from '../../telemetry/tracing' -import { ApiPropertyResult } from '../NavigationSearch/apiPropertyResults' import { useIsNavigationSearchAwaitingNewInput, useNavigationSearchCooldownActions, @@ -44,7 +43,6 @@ const SearchResultItem = z.object({ description: z.string(), score: z.number(), parents: z.array(SearchResultItemParent), - properties: z.array(ApiPropertyResult).optional(), }) export type SearchResultItem = z.infer diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/JumpToIndicator.tsx b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/JumpToIndicator.tsx index 4431717483..bf4f43cd3c 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/JumpToIndicator.tsx +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/JumpToIndicator.tsx @@ -12,6 +12,10 @@ export const JumpToIndicator = ({ label }: { label: string }) => { color: ${euiTheme.colors.textSubdued}; margin-left: ${euiTheme.size.xxxxl}; visibility: hidden; + a[data-selected='true'] &, + a:hover:not([data-keyboard-navigating='true']) & { + visibility: visible; + } `} > diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearch.tsx b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearch.tsx index 6de25f9300..10c65e2e7b 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearch.tsx +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearch.tsx @@ -3,8 +3,8 @@ import { SearchInput } from './SearchInput' import { SearchResultsList } from './SearchResultsList' import { GO_TO_LABELS, - navigableSearchResults, - type NavigableResult, + groupSearchResults, + navigableRowCount, } from './apiPropertyResults' import { useSearchTerm, @@ -27,7 +27,7 @@ import { useIsWithinMaxBreakpoint, } from '@elastic/eui' import { css } from '@emotion/react' -import { useRef, useState, useEffect } from 'react' +import { useRef, useState, useEffect, useMemo } from 'react' interface Props { placeholder?: string @@ -52,8 +52,10 @@ export const NavigationSearch = ({ const { trackOpened, trackClosed } = useNavigationSearchTelemetry(typeFilter) - const results = data?.results ?? [] - const navigableResults = navigableSearchResults(results) + const groups = useMemo( + () => groupSearchResults(data?.results ?? []), + [data] + ) const hasContent = !!searchTerm.trim() const isSearching = isLoading || isFetching @@ -62,7 +64,7 @@ export const NavigationSearch = ({ trackClosed({ reason: 'navigate', query: searchTerm, - hadResults: results.length > 0, + hadResults: groups.length > 0, hadSelection: selectedIndex >= 0, }) } @@ -73,7 +75,7 @@ export const NavigationSearch = ({ handleInputKeyDown, handleMouseMove, } = useNavigationSearchKeyboardNavigation({ - resultsCount: navigableResults.length, + resultsCount: navigableRowCount(groups), isLoading: isSearching, onClose: () => setIsPopoverOpen(false), onNavigate: handleResultClick, @@ -97,7 +99,7 @@ export const NavigationSearch = ({ trackClosed({ reason: 'escape', query: searchTerm, - hadResults: results.length > 0, + hadResults: groups.length > 0, hadSelection: selectedIndex >= 0, }) setSearchTerm('') @@ -125,7 +127,7 @@ export const NavigationSearch = ({ trackClosed({ reason: 'blur', query: searchTerm, - hadResults: results.length > 0, + hadResults: groups.length > 0, hadSelection: selectedIndex >= 0, }) } @@ -198,14 +200,15 @@ export const NavigationSearch = ({ > {hasContent && (
- +
)} @@ -218,42 +221,9 @@ const KEYBOARD_SHORTCUTS = [ { keys: ['Esc'], label: 'Close' }, ] -interface SearchDropdownContentProps { - results: NavigableResult[] - isLoading: boolean - isKeyboardNavigating: React.MutableRefObject - onMouseMove: () => void - onResultClick: () => void - typeFilter: TypeFilter -} - -const SearchDropdownContent = ({ - results, - isLoading, - isKeyboardNavigating, - onMouseMove, - onResultClick, - typeFilter, -}: SearchDropdownContentProps) => { - return ( - <> - - - - ) -} - const SearchDropdownFooter = () => { const { euiTheme } = useEuiTheme() const isMobile = useIsWithinMaxBreakpoint('s') - const shortcuts = KEYBOARD_SHORTCUTS if (isMobile) { return null @@ -276,7 +246,7 @@ const SearchDropdownFooter = () => { gap: ${euiTheme.size.base}; `} > - {shortcuts.map((shortcut, index) => ( + {KEYBOARD_SHORTCUTS.map((shortcut, index) => ( { expect(logInfo).toHaveBeenCalledWith( 'navigation_search_result_clicked', expect.objectContaining({ - 'navigation_search.result.anchor': 'req-track_total_hits', + [ATTR_NAVIGATION_SEARCH_RESULT_ANCHOR]: 'req-track_total_hits', }) ) }) diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearchTelemetry.test.tsx b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearchTelemetry.test.tsx index 95f0eafdbd..2bbb36ed60 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearchTelemetry.test.tsx +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearchTelemetry.test.tsx @@ -3,7 +3,7 @@ import { renderWithProviders } from '../../test-utils/render' import { resetCooldownStore } from '../../test-utils/stores' import { NavigationSearch } from './NavigationSearch' import { SearchResultsList } from './SearchResultsList' -import { navigableSearchResults } from './apiPropertyResults' +import { groupSearchResults } from './apiPropertyResults' import { navigationSearchStore } from './navigationSearch.store' import * as queryHook from './useNavigationSearchQuery' import { screen, waitFor } from '@testing-library/react' @@ -188,7 +188,7 @@ describe('Navigation Search Telemetry Integration', () => { describe('Navigation Search Result Click Tracking', () => { // Shared props for SearchResultsList - reduces duplication const createResultsListProps = () => ({ - results: navigableSearchResults(mockSearchResults.results), + results: groupSearchResults(mockSearchResults.results), isLoading: false, isKeyboardNavigating: { current: false }, onMouseMove: vi.fn(), diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.test.tsx b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.test.tsx index 816b9dd02c..e29bf1ddc8 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.test.tsx +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.test.tsx @@ -1,34 +1,28 @@ +import { renderWithProviders } from '../../test-utils/render' import { PropertyResultRow } from './PropertyResultRow' -import { EuiProvider } from '@elastic/eui' -import { render, screen } from '@testing-library/react' +import { screen } from '@testing-library/react' const renderRow = (searchTerm: string, path: string) => - render( - - - + renderWithProviders( + ) it.each([ diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.tsx b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.tsx index 53ad51b02a..0e43f438b4 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.tsx +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.tsx @@ -33,8 +33,17 @@ export const PropertyResultRow = ({ const isMobile = useIsWithinMaxBreakpoint('s') const { ref, href } = useHtmxLink(property.url) const leafOffset = property.path.lastIndexOf('.') + 1 - const propertySearch = - searchTerm.trim().split(/\s+/).pop()?.split('.').filter(Boolean) ?? [] + const [lastWord = ''] = searchTerm.trim().split(/\s+/).slice(-1) + const propertySearch = lastWord.split('.').filter(Boolean) + const highlight = (text: string) => ( + + {text} + + ) return ( - - {property.path.slice(0, leafOffset)} - - - - {property.path.slice(leafOffset)} - - + {highlight(property.path.slice(0, leafOffset))} + {highlight(property.path.slice(leafOffset))} {property.type} diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.test.tsx b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.test.tsx index 67095b55de..0d590804eb 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.test.tsx +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.test.tsx @@ -5,9 +5,9 @@ import { formatApiProductCrumb, navigationSearchBreadcrumbs, } from './SearchResultsList' -import { navigableSearchResults } from './apiPropertyResults' +import { groupSearchResults, type ResultGroup } from './apiPropertyResults' import { navigationSearchStore } from './navigationSearch.store' -import type { SearchResultItem } from './useNavigationSearchQuery' +import type { SearchResultItem, TypeFilter } from './useNavigationSearchQuery' import { screen } from '@testing-library/react' import userEvent from '@testing-library/user-event' @@ -102,16 +102,33 @@ const operation: SearchResultItem = { ], } -const renderList = (isKeyboardNavigating = false) => { +const page: SearchResultItem = { + type: 'docs', + url: '/docs/elasticsearch', + title: 'Elasticsearch', + description: 'Learn about Elasticsearch', + score: 1, + parents: [], +} + +const renderList = ({ + groups = groupSearchResults([operation]), + isKeyboardNavigating = false, + typeFilter = 'api', +}: { + groups?: ResultGroup[] + isKeyboardNavigating?: boolean + typeFilter?: TypeFilter +} = {}) => { const onMouseMove = vi.fn() renderWithProviders( ) return { onMouseMove } @@ -122,6 +139,16 @@ describe('property rows', () => { navigationSearchStore.getState().actions.setSearchTerm('track_total') }) + it('names the Enter action after each row destination', () => { + renderList({ + groups: groupSearchResults([operation, page]), + typeFilter: 'all', + }) + expect(screen.getAllByText('Go to operation')).toHaveLength(1) + expect(screen.getAllByText('Go to property')).toHaveLength(3) + expect(screen.getAllByText('Go to page')).toHaveLength(1) + }) + it('shows the location only when the same path appears in two locations', () => { renderList() const query = screen.getByRole('link', { @@ -154,7 +181,7 @@ describe('property rows', () => { }) it('hands a mouse move back to the parent while the keyboard is driving', async () => { - const { onMouseMove } = renderList(true) + const { onMouseMove } = renderList({ isKeyboardNavigating: true }) const row = screen.getByRole('link', { name: 'size boolean request Count hits', }) diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.tsx b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.tsx index c1bdafa7b2..a7f984db51 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.tsx +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.tsx @@ -3,7 +3,11 @@ import { useHtmxLink } from '../shared/htmx/useHtmxLink' import { JumpToIndicator } from './JumpToIndicator' import { PropertyResultRow } from './PropertyResultRow' import { SanitizedHtmlContent } from './SanitizedHtmlContent' -import { goToLabel, type NavigableResult } from './apiPropertyResults' +import { + GO_TO_LABELS, + type ApiPropertyResult, + type ResultGroup, +} from './apiPropertyResults' import { useSelectedIndex, useSearchActions, @@ -62,7 +66,7 @@ export const emptyStateCopy = (typeFilter: TypeFilter) => : "We couldn't find a page that matches your search" export interface SearchResultsListProps { - results: NavigableResult[] + results: ResultGroup[] isLoading: boolean isKeyboardNavigating: MutableRefObject onMouseMove: () => void @@ -143,96 +147,73 @@ export const SearchResultsList = ({ } } - const handleResultClick = (result: SearchResultItem, index: number) => { + const handleResultClick = ( + result: SearchResultItem, + index: number, + property?: ApiPropertyResult + ) => { trackResultClicked({ query: searchTerm, position: index, - url: result.url, + url: property?.url ?? result.url, score: result.score, + anchor: property?.anchor, }) onResultClick() } return (
- {results.map((entry, index) => { - if (entry.kind !== 'operation') return null - const propertyCount = - entry.result.type === 'api' - ? (entry.result.properties?.length ?? 0) - : 0 - const properties = results.slice( - index + 1, - index + 1 + propertyCount - ) - return ( -
- handleMouseEnter(index)} - onMouseMove={() => handleItemMouseMove(index)} - onClick={() => - handleResultClick(entry.result, index) - } - typeFilter={typeFilter} - /> - {properties.map((child, offset) => { - if (child.kind !== 'property') return null - const propertyIndex = index + offset + 1 - return ( - - other.path === - child.property.path && - other.location !== - child.property.location - ) ?? false - } - isSelected={propertyIndex === selectedIndex} - isKeyboardNavigating={ - isKeyboardNavigating.current - } - onMouseEnter={() => - handleMouseEnter(propertyIndex) - } - onMouseMove={() => - handleItemMouseMove(propertyIndex) - } - onClick={() => { - trackResultClicked({ - query: searchTerm, - position: propertyIndex, - url: child.property.url, - score: child.result.score, - anchor: child.property.anchor, - }) - onResultClick() - }} - /> - ) - })} -
- ) - })} + {results.map(({ result, index, properties }) => ( +
+ handleMouseEnter(index)} + onMouseMove={() => handleItemMouseMove(index)} + onClick={() => handleResultClick(result, index)} + typeFilter={typeFilter} + /> + {properties.map( + ({ property, index: propertyIndex, showLocation }) => ( + + handleMouseEnter(propertyIndex) + } + onMouseMove={() => + handleItemMouseMove(propertyIndex) + } + onClick={() => + handleResultClick( + result, + propertyIndex, + property + ) + } + /> + ) + )} +
+ ))}
) } @@ -316,10 +297,6 @@ const SearchResultRow = ({ text-decoration: underline; } } - - .jump-to-indicator { - visibility: visible; - } } &[data-selected='true'] { @@ -332,10 +309,6 @@ const SearchResultRow = ({ text-decoration: underline; } } - - .jump-to-indicator { - visibility: visible; - } } `} > @@ -354,7 +327,11 @@ const SearchResultRow = ({ {!isMobile && ( )}
@@ -446,11 +423,7 @@ const Title = ({ text }: { text: string }) => { margin-bottom: calc(${euiTheme.size.xs} / 2); mark { - background-color: color-mix( - in srgb, - var(--color-yellow-40) 40%, - transparent - ); + background-color: var(--search-highlight-tint); font-weight: ${euiTheme.font.weight.bold}; color: ${euiTheme.colors.textParagraph}; } @@ -475,11 +448,7 @@ const Description = ({ text }: { text: string }) => { text-overflow: ellipsis; mark { - background-color: color-mix( - in srgb, - var(--color-yellow-40) 40%, - transparent - ); + background-color: var(--search-highlight-tint); font-weight: ${euiTheme.font.weight.bold}; } `} diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.test.ts b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.test.ts index 752fa3c7bb..61de11c687 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.test.ts +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.test.ts @@ -1,29 +1,28 @@ -import { - goToLabel, - navigableSearchResults, - type ApiPropertyResult, - type NavigableResult, -} from './apiPropertyResults' +import { groupSearchResults, navigableRowCount } from './apiPropertyResults' import type { SearchResultItem } from './useNavigationSearchQuery' -const property: ApiPropertyResult = { - name: 'knn', - path: 'knn', - type: 'object', - description: 'Nearest neighbours', - anchor: 'req-knn', - location: 'request', - url: '/docs/api/doc/elasticsearch/operation/operation-search#req-knn', -} +const property = (path: string, location: 'query' | 'request') => ({ + name: path.split('.').pop() ?? path, + path, + type: 'boolean', + description: 'Count hits', + anchor: `${location}-${path}`, + location, + url: `/docs/api/doc/elasticsearch/operation/operation-search#${location}-${path}`, +}) -const operation: SearchResultItem = { +const search: SearchResultItem = { type: 'api', url: '/docs/api/doc/elasticsearch/operation/operation-search', title: 'Search', - description: 'Search documents', + description: 'Run a search', score: 5, parents: [], - properties: [property], + properties: [ + property('track_total_hits', 'query'), + property('track_total_hits', 'request'), + property('size', 'request'), + ], } const page: SearchResultItem = { @@ -35,28 +34,39 @@ const page: SearchResultItem = { parents: [], } -const cases: Array<[string, NavigableResult, string]> = [ - [ - 'an API operation', - { kind: 'operation', result: operation }, - 'Go to operation', - ], - ['a docs page', { kind: 'operation', result: page }, 'Go to page'], - [ - 'a property', - { kind: 'property', result: operation, property }, - 'Go to property', - ], -] +it('numbers rows in keyboard order: each operation, then its properties', () => { + const groups = groupSearchResults([search, page]) + expect( + groups.map((group) => [ + group.index, + group.properties.map((row) => row.index), + ]) + ).toEqual([ + [0, [1, 2, 3]], + [4, []], + ]) + expect(navigableRowCount(groups)).toBe(5) +}) -it.each(cases)('labels the Enter action for %s', (_, entry, label) => { - expect(goToLabel(entry)).toBe(label) +it('shows a location only when the same path appears in two locations', () => { + const [group] = groupSearchResults([search]) + expect( + group.properties.map((row) => [ + row.property.path, + row.property.location, + row.showLocation, + ]) + ).toEqual([ + ['track_total_hits', 'query', true], + ['track_total_hits', 'request', true], + ['size', 'request', false], + ]) }) -it('labels the operation and each of its properties in order', () => { - expect(navigableSearchResults([operation, page]).map(goToLabel)).toEqual([ - 'Go to operation', - 'Go to property', - 'Go to page', +it('lists no properties under a docs page even when the payload carries some', () => { + const [group] = groupSearchResults([ + { ...page, properties: [property('size', 'request')] }, ]) + expect(group.properties).toEqual([]) + expect(navigableRowCount(groupSearchResults([page]))).toBe(1) }) diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts index 749daefa31..e22371e7bf 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts @@ -13,37 +13,47 @@ export const ApiPropertyResult = z.object({ export type ApiPropertyResult = z.infer -export type NavigableResult = - | { kind: 'operation'; result: SearchResultItem } - | { - kind: 'property' - result: SearchResultItem - property: ApiPropertyResult - } - export const GO_TO_LABELS = { page: 'Go to page', operation: 'Go to operation', property: 'Go to property', } as const -export const goToLabel = (entry: NavigableResult): string => { - if (entry.kind === 'property') return GO_TO_LABELS.property - return entry.result.type === 'api' - ? GO_TO_LABELS.operation - : GO_TO_LABELS.page +export interface PropertyRow { + property: ApiPropertyResult + /** Position among every navigable row; the keyboard selection index. */ + index: number + /** Set when the same path appears in two locations, so the row says which one it is. */ + showLocation: boolean +} + +export interface ResultGroup { + result: SearchResultItem + index: number + properties: PropertyRow[] } -export const navigableSearchResults = ( +/** One box per result, with rows numbered in keyboard order: the operation, then its properties. */ +export const groupSearchResults = ( results: SearchResultItem[] -): NavigableResult[] => - results.flatMap((result): NavigableResult[] => [ - { kind: 'operation', result }, - ...(result.type === 'api' ? (result.properties ?? []) : []).map( - (property): NavigableResult => ({ - kind: 'property', - result, - property, - }) - ), - ]) +): ResultGroup[] => { + let index = 0 + return results.map((result) => { + const group: ResultGroup = { result, index: index++, properties: [] } + const properties = + result.type === 'api' ? (result.properties ?? []) : [] + group.properties = properties.map((property) => ({ + property, + index: index++, + showLocation: properties.some( + (other) => + other.path === property.path && + other.location !== property.location + ), + })) + return group + }) +} + +export const navigableRowCount = (groups: ResultGroup[]) => + groups.reduce((count, group) => count + 1 + group.properties.length, 0) diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/useNavigationSearchTelemetry.ts b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/useNavigationSearchTelemetry.ts index 8313289e8d..36c7ad990d 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/useNavigationSearchTelemetry.ts +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/useNavigationSearchTelemetry.ts @@ -12,6 +12,7 @@ import { ATTR_NAVIGATION_SEARCH_RESULT_URL, ATTR_NAVIGATION_SEARCH_RESULT_POSITION, ATTR_NAVIGATION_SEARCH_RESULT_SCORE, + ATTR_NAVIGATION_SEARCH_RESULT_ANCHOR, ATTR_NAVIGATION_SEARCH_TRIGGER, ATTR_NAVIGATION_SEARCH_CLOSE_REASON, ATTR_NAVIGATION_SEARCH_HAD_RESULTS, @@ -104,7 +105,7 @@ export const useNavigationSearchTelemetry = ( [ATTR_NAVIGATION_SEARCH_RESULT_URL]: url, [ATTR_NAVIGATION_SEARCH_RESULT_SCORE]: score, ...(anchor - ? { 'navigation_search.result.anchor': anchor } + ? { [ATTR_NAVIGATION_SEARCH_RESULT_ANCHOR]: anchor } : {}), ...(surface ? { [ATTR_NAVIGATION_SEARCH_SURFACE]: surface } diff --git a/src/services/search/Elastic.Documentation.Search/Query/QueryFieldNames.cs b/src/services/search/Elastic.Documentation.Search/Query/QueryFieldNames.cs index 401856b0ea..6615fd3857 100644 --- a/src/services/search/Elastic.Documentation.Search/Query/QueryFieldNames.cs +++ b/src/services/search/Elastic.Documentation.Search/Query/QueryFieldNames.cs @@ -20,6 +20,9 @@ private static DocumentationMappingContext.DocumentationDocumentResolver Doc public static string NavigationDepth { get; } = $"{Doc.Fields.Navigation}.depth"; public static string NavigationTableOfContents { get; } = $"{Doc.Fields.Navigation}.table_of_contents"; public static string ApiEndpoints { get; } = $"{Doc.Fields.Api}.endpoints"; + public static string ApiProperties { get; } = $"{Doc.Fields.Api}.properties"; + public static string ApiPropertiesName { get; } = $"{ApiProperties}.name"; + public static string ApiPropertiesPathMatch { get; } = $"{ApiProperties}.path.match"; public static string PathKeyword { get; } = $"{Doc.Fields.Path}.keyword"; public static string PathMatch { get; } = $"{Doc.Fields.Path}.match"; public static string TitleKeyword { get; } = $"{Doc.Fields.Title}.keyword"; diff --git a/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs b/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs index 8899512386..d50698e972 100644 --- a/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs +++ b/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs @@ -18,7 +18,7 @@ namespace Elastic.Documentation.Search; public static class SearchQueryBuilder { public const string ApiPropertyHits = "api_properties"; - private static readonly string[] ApiPropertySourceIncludes = ["api.properties.*"]; + private static readonly string[] ApiPropertySourceIncludes = [$"{QueryFieldNames.ApiProperties}.*"]; /// /// Rank-feature and term boosts applied as should clauses on top of the base query. @@ -41,7 +41,23 @@ public static class SearchQueryBuilder ] }; - public static Query? BuildApiPropertyQuery(string searchQuery, string? typeFilter) + public static Query? BuildApiPropertyQuery(string searchQuery, string? typeFilter) => + ParseApiPropertyQuery(searchQuery, typeFilter) is { } parts ? BuildNestedPropertyQuery(parts.Property) : null; + + public static Query ApplyApiPropertyQuery(Query query, string searchQuery, string? typeFilter) + { + if (ParseApiPropertyQuery(searchQuery, typeFilter) is not var (operation, property)) + return query; + + var properties = BuildNestedPropertyQuery(property); + if (operation.Length > 0 && (BuildBareWordEndpointQuery(operation) ?? BuildApiEndpointQuery(operation)) is { } endpoint) + properties = new BoolQuery { Must = [properties], Should = [endpoint] }; + + return new BoolQuery { Should = [query, properties], MinimumShouldMatch = 1, Filter = [DocumentFilter] }; + } + + /// The operation and field halves of a query that may match API fields, or null when the query never can. + private static (string Operation, string Property)? ParseApiPropertyQuery(string searchQuery, string? typeFilter) { var input = searchQuery.Trim(); if (input.Length == 0 || typeFilter is not (null or "" or "all" or "api")) @@ -49,10 +65,14 @@ public static class SearchQueryBuilder if (typeFilter != "api" && input.Any(char.IsWhiteSpace) && !input.Contains('.') && !input.Contains('_')) return null; - var (_, property) = SplitApiPropertyQuery(input); - return new NestedQuery + var separator = input.AsSpan().LastIndexOfAny(" \t\r\n"); + return separator < 0 ? ("", input) : (input[..separator].TrimEnd(), input[(separator + 1)..]); + } + + private static Query BuildNestedPropertyQuery(string property) => + new NestedQuery { - Path = "api.properties", + Path = QueryFieldNames.ApiProperties, IgnoreUnmapped = true, ScoreMode = ChildScoreMode.Max, Query = BuildPropertyMatchQuery(property), @@ -63,26 +83,6 @@ public static class SearchQueryBuilder Source = new SourceConfig(new SourceFilter { Includes = ApiPropertySourceIncludes }) } }; - } - - public static Query ApplyApiPropertyQuery(Query query, string searchQuery, string? typeFilter) - { - var properties = BuildApiPropertyQuery(searchQuery, typeFilter); - if (properties is null) - return query; - - var (operation, _) = SplitApiPropertyQuery(searchQuery.Trim()); - if (operation.Length > 0 && (BuildBareWordEndpointQuery(operation) ?? BuildApiEndpointQuery(operation)) is { } endpoint) - properties = new BoolQuery { Must = [properties], Should = [endpoint] }; - - return new BoolQuery { Should = [query, properties], MinimumShouldMatch = 1, Filter = [DocumentFilter] }; - } - - private static (string Operation, string Property) SplitApiPropertyQuery(string input) - { - var separator = input.AsSpan().LastIndexOfAny(" \t\r\n"); - return separator < 0 ? ("", input) : (input[..separator].TrimEnd(), input[(separator + 1)..]); - } private static Query BuildPropertyMatchQuery(string input) { @@ -99,7 +99,10 @@ private static Query BuildPropertyMatchQuery(string input) new BoolQuery { Must = [BuildPropertyNameQuery(input[(separator + 1)..])], - Filter = [new MatchBoolPrefixQuery { Field = "api.properties.path.match", Query = input, Operator = Operator.And }] + Filter = + [ + new MatchBoolPrefixQuery { Field = QueryFieldNames.ApiPropertiesPathMatch, Query = input, Operator = Operator.And } + ] } ] }; @@ -113,13 +116,13 @@ private static Query BuildPropertyNameQuery(string name) => [ new ConstantScoreQuery { - Filter = new TermQuery { Field = "api.properties.name", Value = name, CaseInsensitive = true }, + Filter = new TermQuery { Field = QueryFieldNames.ApiPropertiesName, Value = name, CaseInsensitive = true }, Boost = 1 }, new ConstantScoreQuery { // A keyword prefix preserves underscores and field names longer than the edge-ngram limit. - Filter = new PrefixQuery { Field = "api.properties.name", Value = name, CaseInsensitive = true }, + Filter = new PrefixQuery { Field = QueryFieldNames.ApiPropertiesName, Value = name, CaseInsensitive = true }, Boost = 0.6f } ] diff --git a/tests/Elastic.ApiExplorer.Tests/ApiPropertyIndexTests.cs b/tests/Elastic.ApiExplorer.Tests/ApiPropertyIndexTests.cs index a5ddec96b2..cc018a213b 100644 --- a/tests/Elastic.ApiExplorer.Tests/ApiPropertyIndexTests.cs +++ b/tests/Elastic.ApiExplorer.Tests/ApiPropertyIndexTests.cs @@ -47,7 +47,7 @@ public async Task Export_NestedDictionaryAndUnion_IndexesRenderedFields() new SchemaAnalyzer(spec), new ParameterRowSource(TestSpecs.BuilderFor(spec), null, OperationEndpoint.Build(operation, null, [])) ); - var entries = trees.IndexEntries(); + var entries = trees.IndexEntries(new Dictionary()); entries.Should().Contain( p => p.Path == "flight.travel_agency" && p.Anchor == "req-flight-travel_agency" && p.Type == "string" && p.Description == diff --git a/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs b/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs index 9d1337586d..68e81045cc 100644 --- a/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs +++ b/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs @@ -149,21 +149,26 @@ public void ProcessHit_ManyInnerHits_KeepsTheThreeBestDistinctAnchorsInScoreOrde InnerHit("req-a", 4.5, "other.a"), InnerHit("req-c", 3, "c") ); - var json = """ - {"took":1,"timed_out":false,"_shards":{"total":1,"successful":1,"failed":0},"hits":{"total":{"value":1,"relation":"eq"},"hits":[ - {"_index":"test","_id":"search","_score":1,"_source":{"title":"Search","search_title":"Search","path":"/search"}, - "inner_hits":{"api_properties":{"hits":{"total":{"value":5,"relation":"eq"},"max_score":5,"hits":[__INNER_HITS__]}}}}]}} - """.Replace( - "__INNER_HITS__", - innerHits + var result = SearchResultProcessor.ProcessHit( + ParseResponse(SearchResponseJson(innerHits)).Hits.Single(), + "a", + new Dictionary() ); - var result = SearchResultProcessor.ProcessHit(ParseResponse(json).Hits.Single(), "a", new Dictionary()); - result.Properties.Select(p => p.Anchor).Should().Equal("req-a", "req-b", "req-c"); result.Properties.Select(p => p.Path).Should().Equal("a", "b", "c"); } + private static string SearchResponseJson(string innerHits) => + """ + {"took":1,"timed_out":false,"_shards":{"total":1,"successful":1,"failed":0},"hits":{"total":{"value":1,"relation":"eq"},"hits":[ + {"_index":"test","_id":"search","_score":1,"_source":{"title":"Search","search_title":"Search","path":"/search"}, + "inner_hits":{"api_properties":{"hits":{"total":{"value":5,"relation":"eq"},"max_score":5,"hits":[__INNER_HITS__]}}}}]}} + """.Replace( + "__INNER_HITS__", + innerHits + ); + private static string InnerHit(string anchor, double score, string path) => $$$""" {"_index":"test","_id":"search","_score":{{{score.ToString(System.Globalization.CultureInfo.InvariantCulture)}}},"_nested":{"field":"api.properties","offset":0}, @@ -189,28 +194,10 @@ private static Elastic.Clients.Elasticsearch.SearchResponse>(stream); - var result = SearchResultProcessor.ProcessHit(response.Hits.Single(), "track_total", new Dictionary()); + var json = SearchResponseJson(InnerHit("req-track_total_hits", 5, "track_total_hits")); + + var result = SearchResultProcessor.ProcessHit(ParseResponse(json).Hits.Single(), "track_total", new Dictionary()); + result.Properties.Should().ContainSingle().Which.Anchor.Should().Be("req-track_total_hits"); } } From 58a9630d5e13b0c0dd7f4e6560860d7eadd9c1b6 Mon Sep 17 00:00:00 2001 From: Jan Calanog Date: Tue, 3 Nov 2026 12:20:25 +0100 Subject: [PATCH 08/23] Show the primary route of a path hit in API search results A query such as `_search` matched an operation's path, but the result only showed the match buried in the body snippet after "Method: POST Path:". The index now stores each operation's routes with their methods, taken from the same endpoint rows the operation page renders, and the navigation search returns them. When a query word names a path, the result replaces the description with the primary route: the method the page leads with and the path with the match highlighted. An alternate route takes its place only when the primary one does not contain the word, so the hit is always explained without listing every variant. The autocomplete source filter now returns every required member of the api object, since a hit that carries any part of it must deserialize, and a test pins that rule. The mapping update sends the whole api object so the existing semantic index gains the field. Co-Authored-By: Claude Fable 5.1 --- docs/data/openapi/api-explorer.md | 2 +- .../Export/OpenApiDocumentExporter.cs | 13 +++- .../ElasticsearchMarkdownExporter.cs | 8 +-- .../NavigationSearch/RouteLine.tsx | 64 +++++++++++++++++++ .../SearchResultsList.test.tsx | 40 +++++++++++- .../NavigationSearch/SearchResultsList.tsx | 14 +++- .../apiPropertyResults.test.ts | 26 +++++++- .../NavigationSearch/apiPropertyResults.ts | 35 ++++++++++ .../useNavigationSearchQuery.ts | 3 +- .../SerializationContext.cs | 2 + .../Common/SourceGenerationContext.cs | 2 + .../Docs/ApiOperationMetadata.cs | 5 ++ .../Docs/ApiRouteEntry.cs | 22 +++++++ .../DefaultSearchService.cs | 10 ++- .../Elastic.Documentation.Search.csproj | 5 ++ .../INavigationSearchService.cs | 5 ++ .../NavigationSearchService.cs | 1 + .../OpenApiDocumentExporterTests.cs | 24 +++++++ .../ApiPropertySearchTests.cs | 11 ++++ .../AutocompleteSourceIncludesTests.cs | 33 ++++++++++ .../NavigationSearchServiceTests.cs | 19 +++++- 21 files changed, 328 insertions(+), 16 deletions(-) create mode 100644 src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/RouteLine.tsx create mode 100644 src/services/search/Elastic.Documentation.Search.Contract/Docs/ApiRouteEntry.cs create mode 100644 tests/Elastic.Documentation.Api.Tests/AutocompleteSourceIncludesTests.cs diff --git a/docs/data/openapi/api-explorer.md b/docs/data/openapi/api-explorer.md index 3a21561bf9..86684879ae 100644 --- a/docs/data/openapi/api-explorer.md +++ b/docs/data/openapi/api-explorer.md @@ -18,7 +18,7 @@ The API title comes from `info.title` in the spec, so fix naming and description API search matches parameter and field names, including prefixes and qualified paths. Direct operation and endpoint matches rank above field matches. Combine an endpoint and a field, such as `_search knn`, to find the operation and its matching fields. Each matching operation lists up to three matching fields beneath it, with their paths, types, and locations. Child rows match the field's own name; ancestor names and descriptions provide context without adding unrelated children. Select a field to open its anchor, including fields inside collapsed sections. Arrow keys move through operations and fields in order; Enter opens the selected row. -Every result uses the same bordered box, with matching fields grouped beneath the operation when present. Matches use the same yellow tint as the destination property's flash. Navigating to a field reveals it and flashes its name, including when search replaces the current page without a full reload. +When a query names a path, such as `_search`, the result shows the operation's primary route in place of the description: the method the page leads with and the path with the match highlighted. An alternate route appears only when the primary route does not contain the query word. Every result uses the same bordered box, with matching fields grouped beneath the operation when present. Matches use the same yellow tint as the destination property's flash. Navigating to a field reveals it and flashes its name, including when search replaces the current page without a full reload. The assembler indexes fields from the same property trees used to render operation pages. Fields of a repeated shape appear under its first listing. On the existing semantic index, the indexer adds the nested `api.properties` mapping before incremental synchronization. Property changes participate in the document hash, so a field update is synchronized even when the operation description stays the same. diff --git a/src/Elastic.ApiExplorer/Export/OpenApiDocumentExporter.cs b/src/Elastic.ApiExplorer/Export/OpenApiDocumentExporter.cs index c9f7bebd98..2ff992425b 100644 --- a/src/Elastic.ApiExplorer/Export/OpenApiDocumentExporter.cs +++ b/src/Elastic.ApiExplorer/Export/OpenApiDocumentExporter.cs @@ -130,10 +130,11 @@ public IEnumerable ConvertToDocuments(OpenApiDocument ope VersionsConfiguration = versionsConfiguration } ); + var endpoint = OperationEndpoint.Build(apiOperation, operation.Value.Description, []); var trees = OperationPageModel.BuildPropertyTrees( apiOperation, new SchemaAnalyzer(openApiDocument), - new ParameterRowSource(builder, null, OperationEndpoint.Build(apiOperation, operation.Value.Description, [])) + new ParameterRowSource(builder, null, endpoint) ); // Extract tags as headings @@ -162,6 +163,16 @@ public IEnumerable ConvertToDocuments(OpenApiDocument ope Api = new ApiOperationMetadata { Properties = trees.IndexEntries(plainDescriptions), + Routes = endpoint + .Rows + .Select( + row => new ApiRouteEntry + { + Path = row.Route, + Methods = [row.Method.ToUpperInvariant(), .. row.AlsoMethods.Select(m => m.ToUpperInvariant())] + } + ) + .ToArray(), Endpoints = ApiEndpointPath.IndexKeys([path.Key, .. AlternatePaths(operation.Value.Description)]), Method = method, Path = path.Key, diff --git a/src/Elastic.Documentation.Indexing/Exporters/Elasticsearch/ElasticsearchMarkdownExporter.cs b/src/Elastic.Documentation.Indexing/Exporters/Elasticsearch/ElasticsearchMarkdownExporter.cs index ab52c1395f..4a24a81015 100644 --- a/src/Elastic.Documentation.Indexing/Exporters/Elasticsearch/ElasticsearchMarkdownExporter.cs +++ b/src/Elastic.Documentation.Indexing/Exporters/Elasticsearch/ElasticsearchMarkdownExporter.cs @@ -238,12 +238,10 @@ private async Task UpdateApiPropertyMapping(Cancel ctx) if (!exists.ApiCallDetails.HasSuccessfulStatusCode) throw new InvalidOperationException($"Could not check semantic index '{target}': {exists}"); + // The whole api object: Elasticsearch accepts fields that already exist unchanged and adds the new ones. var mapping = JsonNode.Parse(_semanticTypeContext.GetMappingsJson())!; - var properties = mapping["properties"]!["api"]!["properties"]!["properties"]!.DeepClone(); - var update = new JsonObject - { - ["properties"] = new JsonObject { ["api"] = new JsonObject { ["properties"] = new JsonObject { ["properties"] = properties } } } - }; + var api = mapping["properties"]!["api"]!.DeepClone(); + var update = new JsonObject { ["properties"] = new JsonObject { ["api"] = api } }; var response = await _operations.WithRetryAsync( () => _transport.PutAsync($"{target}/_mapping", PostData.String(update.ToJsonString()), ctx), $"PUT {target}/_mapping", diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/RouteLine.tsx b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/RouteLine.tsx new file mode 100644 index 0000000000..0d6a5a1f47 --- /dev/null +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/RouteLine.tsx @@ -0,0 +1,64 @@ +import type { ApiRoute } from './apiPropertyResults' +import { EuiHighlight, useEuiTheme } from '@elastic/eui' +import { css } from '@emotion/react' + +/** The route a query named: the method the page leads with and the path. */ +export const RouteLine = ({ + route: { + path, + methods: [method], + }, + tokens, +}: { + route: ApiRoute + tokens: string[] +}) => { + const { euiTheme } = useEuiTheme() + return ( +
+ + {method} + + + + {path} + + +
+ ) +} diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.test.tsx b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.test.tsx index 0d590804eb..c137f3506f 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.test.tsx +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.test.tsx @@ -121,7 +121,7 @@ const renderList = ({ typeFilter?: TypeFilter } = {}) => { const onMouseMove = vi.fn() - renderWithProviders( + const { container } = renderWithProviders( ) - return { onMouseMove } + return { onMouseMove, container } } describe('property rows', () => { @@ -139,6 +139,42 @@ describe('property rows', () => { navigationSearchStore.getState().actions.setSearchTerm('track_total') }) + it('shows the primary route a query named instead of the description', () => { + const withRoutes: SearchResultItem = { + ...operation, + description: 'Returns search hits', + routes: [ + { path: '/{index}/_search', methods: ['POST', 'GET'] }, + { path: '/_search', methods: ['POST', 'GET'] }, + ], + } + navigationSearchStore.getState().actions.setSearchTerm('_search') + const { container } = renderList({ + groups: groupSearchResults([withRoutes]), + }) + const lines = container.querySelectorAll('.route-line') + expect(lines).toHaveLength(1) + expect(lines[0]).toHaveTextContent('POST') + expect(lines[0]).not.toHaveTextContent('GET') + expect(lines[0]).toHaveTextContent('/{index}/_search') + expect(lines[0].querySelector('mark')).toHaveTextContent('_search') + expect(screen.queryByText('Returns search hits')).toBeNull() + }) + + it('keeps the description when the query names no route', () => { + const withRoutes: SearchResultItem = { + ...operation, + description: 'Returns search hits', + routes: [{ path: '/_search', methods: ['POST', 'GET'] }], + } + navigationSearchStore.getState().actions.setSearchTerm('knn') + const { container } = renderList({ + groups: groupSearchResults([withRoutes]), + }) + expect(container.querySelector('.route-line')).toBeNull() + expect(screen.getByText('Returns search hits')).toBeInTheDocument() + }) + it('names the Enter action after each row destination', () => { renderList({ groups: groupSearchResults([operation, page]), diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.tsx b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.tsx index a7f984db51..73a0c49e63 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.tsx +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.tsx @@ -2,9 +2,11 @@ import { config } from '../../config' import { useHtmxLink } from '../shared/htmx/useHtmxLink' import { JumpToIndicator } from './JumpToIndicator' import { PropertyResultRow } from './PropertyResultRow' +import { RouteLine } from './RouteLine' import { SanitizedHtmlContent } from './SanitizedHtmlContent' import { GO_TO_LABELS, + primaryRoute, type ApiPropertyResult, type ResultGroup, } from './apiPropertyResults' @@ -183,6 +185,7 @@ export const SearchResultsList = ({ onMouseMove={() => handleItemMouseMove(index)} onClick={() => handleResultClick(result, index)} typeFilter={typeFilter} + searchTerm={searchTerm} /> {properties.map( ({ property, index: propertyIndex, showLocation }) => ( @@ -227,6 +230,7 @@ interface SearchResultRowProps { onMouseMove: () => void onClick: () => void typeFilter: TypeFilter + searchTerm: string } const SearchResultRow = ({ @@ -238,10 +242,12 @@ const SearchResultRow = ({ onMouseMove, onClick, typeFilter, + searchTerm, }: SearchResultRowProps) => { const { euiTheme } = useEuiTheme() const isMobile = useIsWithinMaxBreakpoint('s') const { ref, href } = useHtmxLink(result.url) + const { route, tokens } = primaryRoute(result.routes ?? [], searchTerm) const breadcrumbItems = useMemo( () => navigationSearchBreadcrumbs( @@ -321,8 +327,12 @@ const SearchResultRow = ({ > - {result.description && ( - <Description text={result.description} /> + {route ? ( + <RouteLine route={route} tokens={tokens} /> + ) : ( + result.description && ( + <Description text={result.description} /> + ) )} </div> {!isMobile && ( diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.test.ts b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.test.ts index 61de11c687..1c5db6e6ee 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.test.ts +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.test.ts @@ -1,4 +1,8 @@ -import { groupSearchResults, navigableRowCount } from './apiPropertyResults' +import { + groupSearchResults, + navigableRowCount, + primaryRoute, +} from './apiPropertyResults' import type { SearchResultItem } from './useNavigationSearchQuery' const property = (path: string, location: 'query' | 'request') => ({ @@ -70,3 +74,23 @@ it('lists no properties under a docs page even when the payload carries some', ( expect(group.properties).toEqual([]) expect(navigableRowCount(groupSearchResults([page]))).toBe(1) }) + +const routes = [ + { path: '/{index}/_search', methods: ['POST', 'GET'] }, + { path: '/_search', methods: ['POST', 'GET'] }, + { path: '/_search/scroll', methods: ['POST', 'GET'] }, +] + +it.each([ + ['_search', ['_search'], '/{index}/_search'], + ['/_search', ['_search'], '/{index}/_search'], + ['GET /_search knn', ['_search', 'knn'], '/{index}/_search'], + ['scroll', ['scroll'], '/_search/scroll'], + ['knn', ['knn'], undefined], + ['get', [], undefined], + ['a', [], undefined], +])('picks the primary route for %s', (searchTerm, tokens, path) => { + const matched = primaryRoute(routes, searchTerm) + expect(matched.tokens).toEqual(tokens) + expect(matched.route?.path).toBe(path) +}) diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts index e22371e7bf..36dbb82a89 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts @@ -13,6 +13,41 @@ export const ApiPropertyResult = z.object({ export type ApiPropertyResult = z.infer<typeof ApiPropertyResult> +export const ApiRoute = z.object({ + path: z.string(), + methods: z.array(z.string()), +}) + +export type ApiRoute = z.infer<typeof ApiRoute> + +const HTTP_METHODS = new Set([ + 'get', + 'post', + 'put', + 'patch', + 'delete', + 'head', + 'options', +]) + +/** + * The query words that can name a path, and the first route in page order whose path contains one. + * Routes arrive with the page's primary route first, so that one wins whenever it matches. + */ +export const primaryRoute = (routes: ApiRoute[], searchTerm: string) => { + const tokens = searchTerm + .toLowerCase() + .split(/\s+/) + .map((word) => word.replace(/^\/+/, '')) + .filter((word) => word.length > 1 && !HTTP_METHODS.has(word)) + return { + tokens, + route: routes.find((route) => + tokens.some((token) => route.path.toLowerCase().includes(token)) + ), + } +} + export const GO_TO_LABELS = { page: 'Go to page', operation: 'Go to operation', diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/useNavigationSearchQuery.ts b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/useNavigationSearchQuery.ts index e628fbba3e..e12f2a3e93 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/useNavigationSearchQuery.ts +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/useNavigationSearchQuery.ts @@ -15,7 +15,7 @@ import { isRateLimitError, } from '../shared/errorHandling' import { ApiError } from '../shared/errorHandling' -import { ApiPropertyResult } from './apiPropertyResults' +import { ApiPropertyResult, ApiRoute } from './apiPropertyResults' import { usePageNumber, useSearchTerm } from './navigationSearch.store' import { useIsNavigationSearchAwaitingNewInput, @@ -44,6 +44,7 @@ const SearchResultItem = z.object({ score: z.number(), parents: z.array(SearchResultItemParent), properties: z.array(ApiPropertyResult).optional(), + routes: z.array(ApiRoute).optional(), }) export type SearchResultItem = z.infer<typeof SearchResultItem> diff --git a/src/api/Elastic.Documentation.Api/SerializationContext.cs b/src/api/Elastic.Documentation.Api/SerializationContext.cs index 81e55dbbf0..065d9c28e2 100644 --- a/src/api/Elastic.Documentation.Api/SerializationContext.cs +++ b/src/api/Elastic.Documentation.Api/SerializationContext.cs @@ -27,6 +27,8 @@ public record OutputMessage(string Role, MessagePart[] Parts, string FinishReaso [JsonSerializable(typeof(NavigationSearchRequest))] [JsonSerializable(typeof(NavigationSearchResponse))] [JsonSerializable(typeof(NavigationSearchProperty))] +[JsonSerializable(typeof(Search.Contract.ApiRouteEntry))] +[JsonSerializable(typeof(Search.Contract.ApiRouteEntry[]))] [JsonSerializable(typeof(NavigationSearchAggregations))] [JsonSerializable(typeof(InputMessage))] [JsonSerializable(typeof(OutputMessage[]))] diff --git a/src/services/search/Elastic.Documentation.Search.Contract/Common/SourceGenerationContext.cs b/src/services/search/Elastic.Documentation.Search.Contract/Common/SourceGenerationContext.cs index 50a7c13073..c293b3dae2 100644 --- a/src/services/search/Elastic.Documentation.Search.Contract/Common/SourceGenerationContext.cs +++ b/src/services/search/Elastic.Documentation.Search.Contract/Common/SourceGenerationContext.cs @@ -18,6 +18,8 @@ namespace Elastic.Documentation.Search.Contract; [JsonSerializable(typeof(ApiOperationMetadata))] [JsonSerializable(typeof(ApiPropertyEntry))] [JsonSerializable(typeof(ApiPropertyEntry[]))] +[JsonSerializable(typeof(ApiRouteEntry))] +[JsonSerializable(typeof(ApiRouteEntry[]))] [JsonSerializable(typeof(IndexedProduct))] [JsonSerializable(typeof(IndexedProduct[]))] [JsonSerializable(typeof(ParentDocument))] diff --git a/src/services/search/Elastic.Documentation.Search.Contract/Docs/ApiOperationMetadata.cs b/src/services/search/Elastic.Documentation.Search.Contract/Docs/ApiOperationMetadata.cs index 5c1fabece3..36b7467289 100644 --- a/src/services/search/Elastic.Documentation.Search.Contract/Docs/ApiOperationMetadata.cs +++ b/src/services/search/Elastic.Documentation.Search.Contract/Docs/ApiOperationMetadata.cs @@ -17,6 +17,11 @@ public record ApiOperationMetadata [JsonPropertyName("properties")] public ApiPropertyEntry[] Properties { get; init; } = []; + /// <summary>Every route the operation page lists, with its methods, in page order.</summary> + [Object] + [JsonPropertyName("routes")] + public ApiRouteEntry[] Routes { get; init; } = []; + /// <summary> /// Lowercased endpoint paths without the leading <c>/</c>, with and without leading and trailing /// parameters, each parameter stored as <c>*</c>, e.g. <c>*/_search</c> and <c>_search</c>. diff --git a/src/services/search/Elastic.Documentation.Search.Contract/Docs/ApiRouteEntry.cs b/src/services/search/Elastic.Documentation.Search.Contract/Docs/ApiRouteEntry.cs new file mode 100644 index 0000000000..c31f381df1 --- /dev/null +++ b/src/services/search/Elastic.Documentation.Search.Contract/Docs/ApiRouteEntry.cs @@ -0,0 +1,22 @@ +// Licensed to Elasticsearch B.V under one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + +using System.Text.Json.Serialization; +using Elastic.Mapping; + +namespace Elastic.Documentation.Search.Contract; + +/// <summary>One route of an operation with every method it accepts. Stored for display in search results, not searched.</summary> +public record ApiRouteEntry +{ + /// <summary>Spec path, verbatim, e.g. <c>/{index}/_search</c>.</summary> + [Keyword(Index = false)] + [JsonPropertyName("path")] + public required string Path { get; init; } + + /// <summary>Upper-case HTTP methods, the one the page leads with first, e.g. <c>POST</c>, <c>GET</c>.</summary> + [Keyword(Index = false)] + [JsonPropertyName("methods")] + public required string[] Methods { get; init; } +} diff --git a/src/services/search/Elastic.Documentation.Search/DefaultSearchService.cs b/src/services/search/Elastic.Documentation.Search/DefaultSearchService.cs index bda4b84937..578c14c05c 100644 --- a/src/services/search/Elastic.Documentation.Search/DefaultSearchService.cs +++ b/src/services/search/Elastic.Documentation.Search/DefaultSearchService.cs @@ -32,7 +32,7 @@ public partial class DefaultSearchService<TDocument>( private const string PreTag = "<mark>"; private const string PostTag = "</mark>"; - private static readonly string[] AutocompleteSourceIncludes = + internal static readonly string[] AutocompleteSourceIncludes = [ "content_type", "title", @@ -40,7 +40,13 @@ public partial class DefaultSearchService<TDocument>( "path", "description", "parents", - "headings" + "headings", + // every required member of ApiOperationMetadata, or the hit fails to deserialize; properties arrive as inner hits + "api.endpoints", + "api.method", + "api.path", + "api.operation_id", + "api.routes" ]; private static readonly string[] SearchSourceIncludes = diff --git a/src/services/search/Elastic.Documentation.Search/Elastic.Documentation.Search.csproj b/src/services/search/Elastic.Documentation.Search/Elastic.Documentation.Search.csproj index a13548e940..328b831968 100644 --- a/src/services/search/Elastic.Documentation.Search/Elastic.Documentation.Search.csproj +++ b/src/services/search/Elastic.Documentation.Search/Elastic.Documentation.Search.csproj @@ -21,4 +21,9 @@ <PackageReference Include="Microsoft.Extensions.Logging" /> </ItemGroup> + <ItemGroup> + <AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo"> + <_Parameter1>Elastic.Documentation.Api.Tests</_Parameter1> + </AssemblyAttribute> + </ItemGroup> </Project> diff --git a/src/services/search/Elastic.Documentation.Search/INavigationSearchService.cs b/src/services/search/Elastic.Documentation.Search/INavigationSearchService.cs index 71683bef89..0a31b72d48 100644 --- a/src/services/search/Elastic.Documentation.Search/INavigationSearchService.cs +++ b/src/services/search/Elastic.Documentation.Search/INavigationSearchService.cs @@ -2,6 +2,8 @@ // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information +using Elastic.Documentation.Search.Contract; + namespace Elastic.Documentation.Search; public interface INavigationSearchService @@ -48,6 +50,9 @@ public record NavigationSearchResultItemParent public record NavigationSearchResultItem { public NavigationSearchProperty[] Properties { get; init; } = []; + + /// <summary>The operation's routes with their methods; empty for a docs page.</summary> + public ApiRouteEntry[] Routes { get; init; } = []; public required string Type { get; init; } public required string Url { get; init; } public required string Title { get; init; } diff --git a/src/services/search/Elastic.Documentation.Search/NavigationSearchService.cs b/src/services/search/Elastic.Documentation.Search/NavigationSearchService.cs index 829698ff61..1c6b405f69 100644 --- a/src/services/search/Elastic.Documentation.Search/NavigationSearchService.cs +++ b/src/services/search/Elastic.Documentation.Search/NavigationSearchService.cs @@ -52,6 +52,7 @@ public async Task<NavigationSearchResponse> NavigationSearchAsync(NavigationSear Url = item.Document.Path, Title = item.Title, Description = item.Description, + Routes = item.Document.Api?.Routes ?? [], Properties = item .Properties .Select( diff --git a/tests/Elastic.ApiExplorer.Tests/OpenApiDocumentExporterTests.cs b/tests/Elastic.ApiExplorer.Tests/OpenApiDocumentExporterTests.cs index a82bad8af1..2db6d0b304 100644 --- a/tests/Elastic.ApiExplorer.Tests/OpenApiDocumentExporterTests.cs +++ b/tests/Elastic.ApiExplorer.Tests/OpenApiDocumentExporterTests.cs @@ -270,6 +270,30 @@ Returns one or more data sources. doc.Body.Should().NotContain("/_query/data_source</span>"); } + [Test] + public void Operation_MethodList_IndexesEveryRouteWithItsMethods() + { + const string raw = + """ + **All methods and paths for this operation:** + + <div> + <span class="operation-verb get">GET</span> + <span class="operation-path">/_query/data_source</span> + </div> + + Returns one or more data sources. + """; + + var doc = ExportOperation("Get ES|QL data sources", raw, "esql-get-data-source"); + + doc.Api! + .Routes + .Select(r => $"{string.Join(",", r.Methods)} {r.Path}") + .Should() + .Equal("PUT /_query/data_source/{name}", "GET /_query/data_source"); + } + [Test] public void Operation_OnlyMethodList_IndexesTheSummary() { diff --git a/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs b/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs index 68e81045cc..ea0391998d 100644 --- a/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs +++ b/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs @@ -136,6 +136,17 @@ public void Mapping_ApiProperties_IsNestedWithKeywordNames(bool semantic) var fields = field.GetProperty("properties"); fields.GetProperty("name").GetProperty("type").GetString().Should().Be("keyword"); fields.GetProperty("anchor").GetProperty("type").GetString().Should().Be("keyword"); + + var routes = json + .RootElement + .GetProperty("properties") + .GetProperty("api") + .GetProperty("properties") + .GetProperty("routes") + .GetProperty("properties"); + routes.GetProperty("path").GetProperty("type").GetString().Should().Be("keyword"); + routes.GetProperty("path").GetProperty("index").GetBoolean().Should().BeFalse(); + routes.GetProperty("methods").GetProperty("type").GetString().Should().Be("keyword"); } [Test] diff --git a/tests/Elastic.Documentation.Api.Tests/AutocompleteSourceIncludesTests.cs b/tests/Elastic.Documentation.Api.Tests/AutocompleteSourceIncludesTests.cs new file mode 100644 index 0000000000..3a324ee236 --- /dev/null +++ b/tests/Elastic.Documentation.Api.Tests/AutocompleteSourceIncludesTests.cs @@ -0,0 +1,33 @@ +// Licensed to Elasticsearch B.V under one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Text.Json.Serialization; +using AwesomeAssertions; +using Elastic.Documentation.Search; +using Elastic.Documentation.Search.Contract; + +namespace Elastic.Documentation.Api.Tests; + +public class AutocompleteSourceIncludesTests +{ + /// <summary> + /// A hit whose <c>_source</c> holds any part of <c>api</c> deserializes into <see cref="ApiOperationMetadata"/>, + /// which rejects a document missing a required member. The filter must therefore return every required member. + /// </summary> + [Test] + public void AutocompleteSourceIncludes_CoverEveryRequiredApiMember() + { + var required = typeof(ApiOperationMetadata) + .GetProperties(BindingFlags.Public | BindingFlags.Instance) + .Where(p => p.GetCustomAttribute<RequiredMemberAttribute>() is not null) + .Select(p => $"api.{p.GetCustomAttribute<JsonPropertyNameAttribute>()!.Name}") + .ToArray(); + + required.Should().NotBeEmpty(); + DefaultSearchService<DocumentationDocument>.AutocompleteSourceIncludes.Should().Contain(required); + DefaultSearchService<DocumentationDocument>.AutocompleteSourceIncludes.Should().Contain("api.routes"); + } +} diff --git a/tests/Elastic.Documentation.Api.Tests/NavigationSearchServiceTests.cs b/tests/Elastic.Documentation.Api.Tests/NavigationSearchServiceTests.cs index 64f16badfa..55d0648edf 100644 --- a/tests/Elastic.Documentation.Api.Tests/NavigationSearchServiceTests.cs +++ b/tests/Elastic.Documentation.Api.Tests/NavigationSearchServiceTests.cs @@ -23,7 +23,19 @@ public async Task NavigationSearchAsync_PropertyHit_LinksToTheAnchorOnTheOperati { Title = "Search", SearchTitle = "Search", - Path = "/docs/api/doc/elasticsearch/operation/operation-search" + Path = "/docs/api/doc/elasticsearch/operation/operation-search", + Api = new ApiOperationMetadata + { + Endpoints = ["_search", "*/_search"], + Method = "POST", + Path = "/{index}/_search", + OperationId = "search", + Routes = + [ + new ApiRouteEntry { Path = "/{index}/_search", Methods = ["POST", "GET"] }, + new ApiRouteEntry { Path = "/_search", Methods = ["POST", "GET"] } + ] + } }; var property = new ApiPropertyEntry { @@ -71,5 +83,10 @@ public async Task NavigationSearchAsync_PropertyHit_LinksToTheAnchorOnTheOperati linked.Url.Should().Be("/docs/api/doc/elasticsearch/operation/operation-search#req-knn"); linked.Anchor.Should().Be("req-knn"); linked.Location.Should().Be("request"); + result + .Routes + .Select(r => (r.Path, string.Join(",", r.Methods))) + .Should() + .Equal(("/{index}/_search", "POST,GET"), ("/_search", "POST,GET")); } } From e596b4621fc0e74da3787180bb8afd90fd35c37f Mon Sep 17 00:00:00 2001 From: Jan Calanog <reakaleek@users.noreply.github.com> Date: Tue, 3 Nov 2026 12:28:22 +0100 Subject: [PATCH 09/23] Show the route a query names in full over the primary route Typing `/_search` showed `POST /{index}/_search`, the page's primary route, which left the reader checking whether that was the route they meant. A route whose whole path is a query word now wins, so `/_search` and `_search` show `POST /_search`, while `search` or `index` still show the primary route that contains them. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --- docs/data/openapi/api-explorer.md | 2 +- .../SearchResultsList.test.tsx | 21 +++++++++++++++++-- .../apiPropertyResults.test.ts | 10 +++++---- .../NavigationSearch/apiPropertyResults.ts | 18 ++++++++++------ 4 files changed, 38 insertions(+), 13 deletions(-) diff --git a/docs/data/openapi/api-explorer.md b/docs/data/openapi/api-explorer.md index 86684879ae..3940d527c0 100644 --- a/docs/data/openapi/api-explorer.md +++ b/docs/data/openapi/api-explorer.md @@ -18,7 +18,7 @@ The API title comes from `info.title` in the spec, so fix naming and description API search matches parameter and field names, including prefixes and qualified paths. Direct operation and endpoint matches rank above field matches. Combine an endpoint and a field, such as `_search knn`, to find the operation and its matching fields. Each matching operation lists up to three matching fields beneath it, with their paths, types, and locations. Child rows match the field's own name; ancestor names and descriptions provide context without adding unrelated children. Select a field to open its anchor, including fields inside collapsed sections. Arrow keys move through operations and fields in order; Enter opens the selected row. -When a query names a path, such as `_search`, the result shows the operation's primary route in place of the description: the method the page leads with and the path with the match highlighted. An alternate route appears only when the primary route does not contain the query word. Every result uses the same bordered box, with matching fields grouped beneath the operation when present. Matches use the same yellow tint as the destination property's flash. Navigating to a field reveals it and flashes its name, including when search replaces the current page without a full reload. +When a query names a path, such as `_search`, the result shows one route in place of the description: the method the page leads with and the path with the match highlighted. The route whose whole path is the query word wins, so `/_search` shows `/_search`; otherwise the operation's primary route shows when it contains the word, and an alternate route only when the primary does not. Every result uses the same bordered box, with matching fields grouped beneath the operation when present. Matches use the same yellow tint as the destination property's flash. Navigating to a field reveals it and flashes its name, including when search replaces the current page without a full reload. The assembler indexes fields from the same property trees used to render operation pages. Fields of a repeated shape appear under its first listing. On the existing semantic index, the indexer adds the nested `api.properties` mapping before incremental synchronization. Property changes participate in the document hash, so a field update is synchronized even when the operation description stays the same. diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.test.tsx b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.test.tsx index c137f3506f..6204453e47 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.test.tsx +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.test.tsx @@ -148,7 +148,7 @@ describe('property rows', () => { { path: '/_search', methods: ['POST', 'GET'] }, ], } - navigationSearchStore.getState().actions.setSearchTerm('_search') + navigationSearchStore.getState().actions.setSearchTerm('search') const { container } = renderList({ groups: groupSearchResults([withRoutes]), }) @@ -157,10 +157,27 @@ describe('property rows', () => { expect(lines[0]).toHaveTextContent('POST') expect(lines[0]).not.toHaveTextContent('GET') expect(lines[0]).toHaveTextContent('/{index}/_search') - expect(lines[0].querySelector('mark')).toHaveTextContent('_search') + expect(lines[0].querySelector('mark')).toHaveTextContent('search') expect(screen.queryByText('Returns search hits')).toBeNull() }) + it('shows the route a query names in full over the primary route', () => { + const withRoutes: SearchResultItem = { + ...operation, + routes: [ + { path: '/{index}/_search', methods: ['POST', 'GET'] }, + { path: '/_search', methods: ['POST', 'GET'] }, + ], + } + navigationSearchStore.getState().actions.setSearchTerm('/_search') + const { container } = renderList({ + groups: groupSearchResults([withRoutes]), + }) + expect(container.querySelector('.route-line')).toHaveTextContent( + 'POST/_search' + ) + }) + it('keeps the description when the query names no route', () => { const withRoutes: SearchResultItem = { ...operation, diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.test.ts b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.test.ts index 1c5db6e6ee..b9b8127564 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.test.ts +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.test.ts @@ -82,14 +82,16 @@ const routes = [ ] it.each([ - ['_search', ['_search'], '/{index}/_search'], - ['/_search', ['_search'], '/{index}/_search'], - ['GET /_search knn', ['_search', 'knn'], '/{index}/_search'], + ['_search', ['_search'], '/_search'], + ['/_search', ['_search'], '/_search'], + ['GET /_search knn', ['_search', 'knn'], '/_search'], + ['search', ['search'], '/{index}/_search'], + ['index', ['index'], '/{index}/_search'], ['scroll', ['scroll'], '/_search/scroll'], ['knn', ['knn'], undefined], ['get', [], undefined], ['a', [], undefined], -])('picks the primary route for %s', (searchTerm, tokens, path) => { +])('picks the route for %s', (searchTerm, tokens, path) => { const matched = primaryRoute(routes, searchTerm) expect(matched.tokens).toEqual(tokens) expect(matched.route?.path).toBe(path) diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts index 36dbb82a89..b96f4e46d5 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts @@ -30,21 +30,27 @@ const HTTP_METHODS = new Set([ 'options', ]) +const pathKey = (path: string) => path.toLowerCase().replace(/^\/+/, '') + /** - * The query words that can name a path, and the first route in page order whose path contains one. - * Routes arrive with the page's primary route first, so that one wins whenever it matches. + * The query words that can name a path, and the one route to show for them: the route whose whole + * path is a query word, else the first route in page order whose path contains one. Routes arrive + * with the page's primary route first, so that one wins among the partial matches. */ export const primaryRoute = (routes: ApiRoute[], searchTerm: string) => { const tokens = searchTerm .toLowerCase() .split(/\s+/) - .map((word) => word.replace(/^\/+/, '')) + .map(pathKey) .filter((word) => word.length > 1 && !HTTP_METHODS.has(word)) + const containing = routes.filter((route) => + tokens.some((token) => pathKey(route.path).includes(token)) + ) return { tokens, - route: routes.find((route) => - tokens.some((token) => route.path.toLowerCase().includes(token)) - ), + route: + containing.find((route) => tokens.includes(pathKey(route.path))) ?? + containing[0], } } From 9f0a77fe6c676a59b864e0775845e5f313433cf4 Mon Sep 17 00:00:00 2001 From: Jan Calanog <reakaleek@users.noreply.github.com> Date: Tue, 3 Nov 2026 12:57:46 +0100 Subject: [PATCH 10/23] Read a combined API query in either word order A combined query took its last word as the field and the rest as the endpoint, so `knn /_search` looked for a field named `/_search` and returned the operation without its `knn` rows, while `knn search` surfaced an unrelated operation whose fields contain "search". The field is now the last word that cannot be part of an endpoint, one that neither starts with a slash nor is an HTTP method, and the endpoint is everything else in order. `knn /_search`, `/_search knn` and `knn GET /_search` read the same. A query made only of endpoint words skips the field branch instead of searching for a field named after the path. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --- docs/data/openapi/api-explorer.md | 2 +- .../Query/SearchQueryBuilder.cs | 12 ++++++++++-- .../ApiPropertySearchTests.cs | 6 ++++++ 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/docs/data/openapi/api-explorer.md b/docs/data/openapi/api-explorer.md index 3940d527c0..faef935551 100644 --- a/docs/data/openapi/api-explorer.md +++ b/docs/data/openapi/api-explorer.md @@ -16,7 +16,7 @@ The cards for APIs that are in neither group show the API's deployments as small The API title comes from `info.title` in the spec, so fix naming and description copy in the spec. -API search matches parameter and field names, including prefixes and qualified paths. Direct operation and endpoint matches rank above field matches. Combine an endpoint and a field, such as `_search knn`, to find the operation and its matching fields. Each matching operation lists up to three matching fields beneath it, with their paths, types, and locations. Child rows match the field's own name; ancestor names and descriptions provide context without adding unrelated children. Select a field to open its anchor, including fields inside collapsed sections. Arrow keys move through operations and fields in order; Enter opens the selected row. +API search matches parameter and field names, including prefixes and qualified paths. Direct operation and endpoint matches rank above field matches. Combine an endpoint and a field, such as `_search knn`, to find the operation and its matching fields. The order does not matter when the endpoint carries its slash: `knn /_search` and `/_search knn` read the same. Without a slash the last word is the field, so `knn _search` looks for a field named `_search`. Each matching operation lists up to three matching fields beneath it, with their paths, types, and locations. Child rows match the field's own name; ancestor names and descriptions provide context without adding unrelated children. Select a field to open its anchor, including fields inside collapsed sections. Arrow keys move through operations and fields in order; Enter opens the selected row. When a query names a path, such as `_search`, the result shows one route in place of the description: the method the page leads with and the path with the match highlighted. The route whose whole path is the query word wins, so `/_search` shows `/_search`; otherwise the operation's primary route shows when it contains the word, and an alternate route only when the primary does not. Every result uses the same bordered box, with matching fields grouped beneath the operation when present. Matches use the same yellow tint as the destination property's flash. Navigating to a field reveals it and flashes its name, including when search replaces the current page without a full reload. diff --git a/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs b/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs index d50698e972..2743fcb586 100644 --- a/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs +++ b/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs @@ -18,6 +18,10 @@ namespace Elastic.Documentation.Search; public static class SearchQueryBuilder { public const string ApiPropertyHits = "api_properties"; + private static readonly HashSet<string> HttpMethods = new( + ["get", "post", "put", "patch", "delete", "head", "options"], + StringComparer.OrdinalIgnoreCase + ); private static readonly string[] ApiPropertySourceIncludes = [$"{QueryFieldNames.ApiProperties}.*"]; /// <summary> @@ -65,8 +69,12 @@ private static (string Operation, string Property)? ParseApiPropertyQuery(string if (typeFilter != "api" && input.Any(char.IsWhiteSpace) && !input.Contains('.') && !input.Contains('_')) return null; - var separator = input.AsSpan().LastIndexOfAny(" \t\r\n"); - return separator < 0 ? ("", input) : (input[..separator].TrimEnd(), input[(separator + 1)..]); + // The field is the last word that cannot be part of an endpoint; the endpoint is everything else, in order. + var words = input.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries); + var field = Array.FindLastIndex(words, w => !w.StartsWith('/') && !HttpMethods.Contains(w)); + if (field < 0) + return null; + return (string.Join(' ', words.Where((_, i) => i != field)), words[field]); } private static Query BuildNestedPropertyQuery(string property) => diff --git a/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs b/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs index ea0391998d..45a1829a60 100644 --- a/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs +++ b/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs @@ -39,6 +39,8 @@ public void BuildApiPropertyQuery_Identifier_ReturnsNestedInnerHits(string input [Arguments("knn", "knn")] [Arguments("_search knn", "knn")] [Arguments("GET /_search knn", "knn")] + [Arguments("knn /_search", "knn")] + [Arguments("knn GET /_search", "knn")] [Arguments("track_total", "track_total")] [Arguments("trav", "trav")] public void BuildApiPropertyQuery_FieldTerm_MatchesOnlyItsOwnNameWithBoundedScores(string input, string name) @@ -102,6 +104,8 @@ public void BuildApiPropertyQuery_QualifiedPath_RequiresMatchingLeafAndPath() [Arguments("_search knn")] [Arguments("GET /_search knn")] [Arguments("search knn")] + [Arguments("knn /_search")] + [Arguments("knn GET /_search")] public void ApplyApiPropertyQuery_OperationAndField_RequiresFieldMatchBeforeEndpointBoost(string input) { using var json = JsonDocument.Parse( @@ -119,6 +123,8 @@ public void ApplyApiPropertyQuery_OperationAndField_RequiresFieldMatchBeforeEndp [Arguments("how to search", null)] [Arguments("trav", "docs")] [Arguments("", "api")] + [Arguments("/_search", "api")] + [Arguments("GET /_search", "api")] public void BuildApiPropertyQuery_ExcludedQuery_ReturnsNull(string input, string? filter) => SearchQueryBuilder.BuildApiPropertyQuery(input, filter).Should().BeNull(); From e625b47920088e01a3f8c65973c998ca4fd41e9e Mon Sep 17 00:00:00 2001 From: Jan Calanog <reakaleek@users.noreply.github.com> Date: Tue, 3 Nov 2026 13:15:00 +0100 Subject: [PATCH 11/23] Let the index decide which word of a two-word API query is the field Without a slash or a method word nothing marks the endpoint in a two-word query, so `knn search` took `search` as the field and surfaced an unrelated operation. Such a query is now read both ways, and each reading requires its endpoint half to match the stored endpoint keys: `search` becomes `_search` and holds, `knn` becomes `_knn` and matches nothing, so only the reading that holds returns rows. `knn search`, `search knn`, `_search knn` and `knn _search` now all return the search operation with its `knn` rows. Each reading carries its own inner-hits name, because Elasticsearch rejects two nested queries that share one, and the result processor merges the groups. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --- docs/data/openapi/api-explorer.md | 2 +- .../Highlighting/SearchResultProcessor.cs | 10 +-- .../Query/SearchQueryBuilder.cs | 63 ++++++++++++----- .../ApiPropertySearchTests.cs | 67 +++++++++++++++++-- 4 files changed, 116 insertions(+), 26 deletions(-) diff --git a/docs/data/openapi/api-explorer.md b/docs/data/openapi/api-explorer.md index faef935551..31487b943f 100644 --- a/docs/data/openapi/api-explorer.md +++ b/docs/data/openapi/api-explorer.md @@ -16,7 +16,7 @@ The cards for APIs that are in neither group show the API's deployments as small The API title comes from `info.title` in the spec, so fix naming and description copy in the spec. -API search matches parameter and field names, including prefixes and qualified paths. Direct operation and endpoint matches rank above field matches. Combine an endpoint and a field, such as `_search knn`, to find the operation and its matching fields. The order does not matter when the endpoint carries its slash: `knn /_search` and `/_search knn` read the same. Without a slash the last word is the field, so `knn _search` looks for a field named `_search`. Each matching operation lists up to three matching fields beneath it, with their paths, types, and locations. Child rows match the field's own name; ancestor names and descriptions provide context without adding unrelated children. Select a field to open its anchor, including fields inside collapsed sections. Arrow keys move through operations and fields in order; Enter opens the selected row. +API search matches parameter and field names, including prefixes and qualified paths. Direct operation and endpoint matches rank above field matches. Combine an endpoint and a field, such as `_search knn`, to find the operation and its matching fields. The order does not matter: `knn /_search`, `/_search knn`, `knn search` and `search knn` read the same. A word with a leading slash or an HTTP method is always the endpoint; with two plain words the index tries both orders and keeps the one whose endpoint exists, so both halves must match. With three or more plain words the last word is the field. Each matching operation lists up to three matching fields beneath it, with their paths, types, and locations. Child rows match the field's own name; ancestor names and descriptions provide context without adding unrelated children. Select a field to open its anchor, including fields inside collapsed sections. Arrow keys move through operations and fields in order; Enter opens the selected row. When a query names a path, such as `_search`, the result shows one route in place of the description: the method the page leads with and the path with the match highlighted. The route whose whole path is the query word wins, so `/_search` shows `/_search`; otherwise the operation's primary route shows when it contains the word, and an alternate route only when the primary does not. Every result uses the same bordered box, with matching fields grouped beneath the operation when present. Matches use the same yellow tint as the destination property's flash. Navigating to a field reveals it and flashes its name, including when search replaces the current page without a full reload. diff --git a/src/services/search/Elastic.Documentation.Search/Highlighting/SearchResultProcessor.cs b/src/services/search/Elastic.Documentation.Search/Highlighting/SearchResultProcessor.cs index bef340b787..ac357bc3c4 100644 --- a/src/services/search/Elastic.Documentation.Search/Highlighting/SearchResultProcessor.cs +++ b/src/services/search/Elastic.Documentation.Search/Highlighting/SearchResultProcessor.cs @@ -61,14 +61,16 @@ public static SearchResultItem<TDocument> ProcessHit<TDocument>( }; } + /// <summary>Every property inner hit, from each reading of the query; see <see cref="SearchQueryBuilder.ApiPropertyHits"/>.</summary> private static IReadOnlyList<ApiPropertyEntry> MatchedProperties<TDocument>(Hit<TDocument> hit) { - if (hit.InnerHits is null || !hit.InnerHits.TryGetValue(SearchQueryBuilder.ApiPropertyHits, out var matches)) + if (hit.InnerHits is null) return []; - return matches - .Hits - .Hits + return hit + .InnerHits + .Where(group => SearchQueryBuilder.IsApiPropertyHits(group.Key)) + .SelectMany(group => group.Value.Hits.Hits) .OrderByDescending(h => h.Score ?? 0) .Select( h => h.Source is JsonElement source ? source.Deserialize(Contract.SourceGenerationContext.Default.ApiPropertyEntry) : null diff --git a/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs b/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs index 2743fcb586..4da8fbda20 100644 --- a/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs +++ b/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs @@ -18,6 +18,13 @@ namespace Elastic.Documentation.Search; public static class SearchQueryBuilder { public const string ApiPropertyHits = "api_properties"; + + /// <summary>Elasticsearch needs one inner-hits name per nested query, so each reading of a query gets its own.</summary> + public static bool IsApiPropertyHits(string innerHitsName) => + innerHitsName == ApiPropertyHits || innerHitsName.StartsWith(ApiPropertyHits + "_", StringComparison.Ordinal); + + private static string InnerHitsName(int reading) => reading == 0 ? ApiPropertyHits : $"{ApiPropertyHits}_{reading}"; + private static readonly HashSet<string> HttpMethods = new( ["get", "post", "put", "patch", "delete", "head", "options"], StringComparer.OrdinalIgnoreCase @@ -45,39 +52,65 @@ public static class SearchQueryBuilder ] }; + /// <summary>The nested field query for the query's first reading, see <see cref="ParseApiPropertyQuery"/>.</summary> public static Query? BuildApiPropertyQuery(string searchQuery, string? typeFilter) => - ParseApiPropertyQuery(searchQuery, typeFilter) is { } parts ? BuildNestedPropertyQuery(parts.Property) : null; + ParseApiPropertyQuery(searchQuery, typeFilter) is [var first, ..] ? BuildNestedPropertyQuery(first.Property, ApiPropertyHits) : null; public static Query ApplyApiPropertyQuery(Query query, string searchQuery, string? typeFilter) { - if (ParseApiPropertyQuery(searchQuery, typeFilter) is not var (operation, property)) + var readings = ParseApiPropertyQuery(searchQuery, typeFilter); + // With one reading the endpoint only lifts the operation. With two, the index decides which reading holds, + // so each requires its endpoint: a bare word that names no endpoint, such as `_knn`, matches nothing. + var branches = readings + .Select((r, i) => BuildReadingQuery(r, InnerHitsName(i), endpointRequired: readings.Count > 1)) + .OfType<Query>() + .ToList(); + if (branches.Count == 0) return query; - var properties = BuildNestedPropertyQuery(property); - if (operation.Length > 0 && (BuildBareWordEndpointQuery(operation) ?? BuildApiEndpointQuery(operation)) is { } endpoint) - properties = new BoolQuery { Must = [properties], Should = [endpoint] }; - + var properties = branches.Count == 1 ? branches[0] : new BoolQuery { Should = branches, MinimumShouldMatch = 1 }; return new BoolQuery { Should = [query, properties], MinimumShouldMatch = 1, Filter = [DocumentFilter] }; } - /// <summary>The operation and field halves of a query that may match API fields, or null when the query never can.</summary> - private static (string Operation, string Property)? ParseApiPropertyQuery(string searchQuery, string? typeFilter) + private static Query? BuildReadingQuery((string Operation, string Property) reading, string innerHitsName, bool endpointRequired) + { + var properties = BuildNestedPropertyQuery(reading.Property, innerHitsName); + if (reading.Operation.Length == 0) + return properties; + + var endpoint = BuildBareWordEndpointQuery(reading.Operation) ?? BuildApiEndpointQuery(reading.Operation); + if (endpoint is null) + return endpointRequired ? null : properties; + return endpointRequired + ? new BoolQuery { Must = [properties, endpoint] } + : new BoolQuery { Must = [properties], Should = [endpoint] }; + } + + /// <summary> + /// The ways a query may split into an endpoint half and a field half; empty when it never names a field. + /// A word that starts with a slash or is an HTTP method can only be endpoint, so the field is the last word + /// that is neither. Two plain words are ambiguous, so both orders are returned, the last word as the field first. + /// </summary> + private static IReadOnlyList<(string Operation, string Property)> ParseApiPropertyQuery(string searchQuery, string? typeFilter) { var input = searchQuery.Trim(); if (input.Length == 0 || typeFilter is not (null or "" or "all" or "api")) - return null; + return []; if (typeFilter != "api" && input.Any(char.IsWhiteSpace) && !input.Contains('.') && !input.Contains('_')) - return null; + return []; - // The field is the last word that cannot be part of an endpoint; the endpoint is everything else, in order. var words = input.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries); + var marked = words.Any(w => w.StartsWith('/') || HttpMethods.Contains(w)); + if (!marked && words.Length == 2) + return [(words[0], words[1]), (words[1], words[0])]; + var field = Array.FindLastIndex(words, w => !w.StartsWith('/') && !HttpMethods.Contains(w)); if (field < 0) - return null; - return (string.Join(' ', words.Where((_, i) => i != field)), words[field]); + return []; + return [(string.Join(' ', words.Where((_, i) => i != field)), words[field])]; } - private static Query BuildNestedPropertyQuery(string property) => + private static Query BuildNestedPropertyQuery(string property, string innerHitsName) => new NestedQuery { Path = QueryFieldNames.ApiProperties, @@ -86,7 +119,7 @@ private static Query BuildNestedPropertyQuery(string property) => Query = BuildPropertyMatchQuery(property), InnerHits = new InnerHits { - Name = ApiPropertyHits, + Name = innerHitsName, Size = 5, Source = new SourceConfig(new SourceFilter { Includes = ApiPropertySourceIncludes }) } diff --git a/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs b/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs index 45a1829a60..d93acf16fa 100644 --- a/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs +++ b/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs @@ -101,12 +101,10 @@ public void BuildApiPropertyQuery_QualifiedPath_RequiresMatchingLeafAndPath() } [Test] - [Arguments("_search knn")] [Arguments("GET /_search knn")] - [Arguments("search knn")] [Arguments("knn /_search")] [Arguments("knn GET /_search")] - public void ApplyApiPropertyQuery_OperationAndField_RequiresFieldMatchBeforeEndpointBoost(string input) + public void ApplyApiPropertyQuery_MarkedEndpointAndField_RequiresFieldMatchBeforeEndpointBoost(string input) { using var json = JsonDocument.Parse( Client.RequestResponseSerializer.SerializeToString( @@ -119,6 +117,63 @@ public void ApplyApiPropertyQuery_OperationAndField_RequiresFieldMatchBeforeEndp endpoint.GetProperty("filter").GetProperty("terms").GetProperty("api.endpoints")[0].GetString().Should().Be("_search"); } + [Test] + [Arguments("_search knn")] + [Arguments("search knn")] + [Arguments("knn search")] + [Arguments("knn _search")] + public void ApplyApiPropertyQuery_TwoPlainWords_TriesBothReadingsWithTheEndpointRequired(string input) + { + using var json = JsonDocument.Parse( + Client.RequestResponseSerializer.SerializeToString( + SearchQueryBuilder.ApplyApiPropertyQuery(new Elastic.Clients.Elasticsearch.QueryDsl.MatchNoneQuery(), input, "api") + ) + ); + var readings = json.RootElement.GetProperty("bool").GetProperty("should")[1].GetProperty("bool").GetProperty("should"); + readings.GetArrayLength().Should().Be(2); + var knn = readings.EnumerateArray().Single(r => r.GetRawText().Contains("\"value\":\"knn\"")).GetProperty("bool"); + var must = knn.GetProperty("must"); + must.GetArrayLength().Should().Be(2); + must[0].GetProperty("nested").GetProperty("query").GetRawText().Should().Contain("\"value\":\"knn\""); + must[1] + .GetProperty("dis_max") + .GetProperty("queries")[0] + .GetProperty("constant_score") + .GetProperty("filter") + .GetProperty("terms") + .GetProperty("api.endpoints")[0] + .GetString() + .Should() + .Be("_search"); + knn.TryGetProperty("should", out _).Should().BeFalse(); + var names = System + .Text + .RegularExpressions + .Regex + .Matches(readings.GetRawText(), "\"name\":\"([^\"]+)\"") + .Select(m => m.Groups[1].Value) + .ToArray(); + names + .Should() + .HaveCount(2) + .And + .OnlyHaveUniqueItems() + .And + .AllSatisfy(n => SearchQueryBuilder.IsApiPropertyHits(n).Should().BeTrue()); + } + + [Test] + public void ProcessHit_InnerHitsFromBothReadings_AreMerged() + { + var second = + $$$""","api_properties_1":{"hits":{"total":{"value":1,"relation":"eq"},"max_score":4,"hits":[{{{InnerHit("req-b", 4, "b")}}}]}}"""; + var json = SearchResponseJson(InnerHit("req-a", 5, "a"), second); + + var result = SearchResultProcessor.ProcessHit(ParseResponse(json).Hits.Single(), "a", new Dictionary<string, string[]>()); + + result.Properties.Select(p => p.Anchor).Should().Equal("req-a", "req-b"); + } + [Test] [Arguments("how to search", null)] [Arguments("trav", "docs")] @@ -176,15 +231,15 @@ public void ProcessHit_ManyInnerHits_KeepsTheThreeBestDistinctAnchorsInScoreOrde result.Properties.Select(p => p.Path).Should().Equal("a", "b", "c"); } - private static string SearchResponseJson(string innerHits) => + private static string SearchResponseJson(string innerHits, string moreInnerHitGroups = "") => """ {"took":1,"timed_out":false,"_shards":{"total":1,"successful":1,"failed":0},"hits":{"total":{"value":1,"relation":"eq"},"hits":[ {"_index":"test","_id":"search","_score":1,"_source":{"title":"Search","search_title":"Search","path":"/search"}, - "inner_hits":{"api_properties":{"hits":{"total":{"value":5,"relation":"eq"},"max_score":5,"hits":[__INNER_HITS__]}}}}]}} + "inner_hits":{"api_properties":{"hits":{"total":{"value":5,"relation":"eq"},"max_score":5,"hits":[__INNER_HITS__]}}__MORE_GROUPS__}}]}} """.Replace( "__INNER_HITS__", innerHits - ); + ).Replace("__MORE_GROUPS__", moreInnerHitGroups); private static string InnerHit(string anchor, double score, string path) => $$$""" From 454464458ce0fb55c57a393ee9f66292256114a5 Mon Sep 17 00:00:00 2001 From: Jan Calanog <reakaleek@users.noreply.github.com> Date: Tue, 3 Nov 2026 13:27:31 +0100 Subject: [PATCH 12/23] Highlight the field word of a query in either order on property rows A property row highlighted only the last query word, a leftover of the rule that read the last word as the field, so `knn search` marked nothing on the `knn` rows that the query now returns. The row now highlights every query word that can name a field, which excludes paths and HTTP method words, so `knn search` and `search knn` both mark `knn`. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --- .../PropertyResultRow.test.tsx | 3 +++ .../NavigationSearch/PropertyResultRow.tsx | 9 ++++++--- .../apiPropertyResults.test.ts | 12 ++++++++++++ .../NavigationSearch/apiPropertyResults.ts | 18 ++++++++++++++++++ 4 files changed, 39 insertions(+), 3 deletions(-) diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.test.tsx b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.test.tsx index e29bf1ddc8..24bb7caebd 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.test.tsx +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.test.tsx @@ -35,6 +35,9 @@ it.each([ ['elasticsearch', 'remote_cluster'], ], ['_search knn.field', 'knn.field', ['knn', 'field']], + ['knn search', 'retriever.knn', ['knn']], + ['knn /_search', 'retriever.knn', ['knn']], + ['knn GET /_search', 'knn', ['knn']], ])('highlights the property match for %s', (searchTerm, path, matches) => { renderRow(searchTerm, path) const row = screen.getByRole('link') diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.tsx b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.tsx index 0e43f438b4..114fcd38de 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.tsx +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.tsx @@ -1,6 +1,10 @@ import { useHtmxLink } from '../shared/htmx/useHtmxLink' import { JumpToIndicator } from './JumpToIndicator' -import { GO_TO_LABELS, type ApiPropertyResult } from './apiPropertyResults' +import { + GO_TO_LABELS, + fieldSearchTerms, + type ApiPropertyResult, +} from './apiPropertyResults' import { EuiHighlight, useEuiTheme, @@ -33,8 +37,7 @@ export const PropertyResultRow = ({ const isMobile = useIsWithinMaxBreakpoint('s') const { ref, href } = useHtmxLink(property.url) const leafOffset = property.path.lastIndexOf('.') + 1 - const [lastWord = ''] = searchTerm.trim().split(/\s+/).slice(-1) - const propertySearch = lastWord.split('.').filter(Boolean) + const propertySearch = fieldSearchTerms(searchTerm) const highlight = (text: string) => ( <EuiHighlight search={propertySearch} diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.test.ts b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.test.ts index b9b8127564..4b309ed9f6 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.test.ts +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.test.ts @@ -1,4 +1,5 @@ import { + fieldSearchTerms, groupSearchResults, navigableRowCount, primaryRoute, @@ -96,3 +97,14 @@ it.each([ expect(matched.tokens).toEqual(tokens) expect(matched.route?.path).toBe(path) }) + +it.each([ + ['knn search', ['knn', 'search']], + ['search knn', ['search', 'knn']], + ['knn /_search', ['knn']], + ['GET /_search knn.field', ['knn', 'field']], + ['_search knn', ['_search', 'knn']], + ['/_search', []], +])('takes the field terms of %s', (searchTerm, terms) => { + expect(fieldSearchTerms(searchTerm)).toEqual(terms) +}) diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts index b96f4e46d5..9b6f38f78b 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts @@ -32,6 +32,24 @@ const HTTP_METHODS = new Set([ const pathKey = (path: string) => path.toLowerCase().replace(/^\/+/, '') +const canBeField = (word: string) => + word.length > 0 && + !word.startsWith('/') && + !HTTP_METHODS.has(word.toLowerCase()) + +/** The parts of a query that can name a field, split on dots, in either word order; what a property row highlights. */ +export const fieldSearchTerms = (searchTerm: string) => + Array.from( + new Set( + searchTerm + .trim() + .split(/\s+/) + .filter(canBeField) + .flatMap((word) => word.split('.')) + .filter(Boolean) + ) + ) + /** * The query words that can name a path, and the one route to show for them: the route whose whole * path is a query word, else the first route in page order whose path contains one. Routes arrive From fc143a9ea4962d2fe5ec4382a501120b27f10378 Mon Sep 17 00:00:00 2001 From: Jan Calanog <reakaleek@users.noreply.github.com> Date: Tue, 3 Nov 2026 13:36:36 +0100 Subject: [PATCH 13/23] Report a clicked result's rank, not its keyboard row, in telemetry A property row's click reported the keyboard row index, which counts the property rows above it, so a page listed after an operation with three fields was reported at position 4. The position is now the result's rank among the results for the operation and for each of its properties, and the anchor keeps identifying the property row. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --- .../NavigationSearchComponent.test.tsx | 1 + .../NavigationSearch/SearchResultsList.tsx | 14 +++++--------- .../NavigationSearch/apiPropertyResults.test.ts | 1 + .../NavigationSearch/apiPropertyResults.ts | 11 +++++++++-- 4 files changed, 16 insertions(+), 11 deletions(-) diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearchComponent.test.tsx b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearchComponent.test.tsx index 0d3e69baec..ddce2ed0ff 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearchComponent.test.tsx +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearchComponent.test.tsx @@ -115,6 +115,7 @@ describe('NavigationSearchWrapper type attribute', () => { 'navigation_search_result_clicked', expect.objectContaining({ [ATTR_NAVIGATION_SEARCH_RESULT_ANCHOR]: 'req-track_total_hits', + 'navigation_search.result.position': 0, }) ) }) diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.tsx b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.tsx index 73a0c49e63..a86ef0a45e 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.tsx +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.tsx @@ -151,12 +151,12 @@ export const SearchResultsList = ({ const handleResultClick = ( result: SearchResultItem, - index: number, + rank: number, property?: ApiPropertyResult ) => { trackResultClicked({ query: searchTerm, - position: index, + position: rank, url: property?.url ?? result.url, score: result.score, anchor: property?.anchor, @@ -166,7 +166,7 @@ export const SearchResultsList = ({ return ( <div ref={containerRef} css={containerStyles}> - {results.map(({ result, index, properties }) => ( + {results.map(({ result, index, rank, properties }) => ( <div key={result.url} css={css` @@ -183,7 +183,7 @@ export const SearchResultsList = ({ isKeyboardNavigating={isKeyboardNavigating.current} onMouseEnter={() => handleMouseEnter(index)} onMouseMove={() => handleItemMouseMove(index)} - onClick={() => handleResultClick(result, index)} + onClick={() => handleResultClick(result, rank)} typeFilter={typeFilter} searchTerm={searchTerm} /> @@ -206,11 +206,7 @@ export const SearchResultsList = ({ handleItemMouseMove(propertyIndex) } onClick={() => - handleResultClick( - result, - propertyIndex, - property - ) + handleResultClick(result, rank, property) } /> ) diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.test.ts b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.test.ts index 4b309ed9f6..e961673d06 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.test.ts +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.test.ts @@ -50,6 +50,7 @@ it('numbers rows in keyboard order: each operation, then its properties', () => [0, [1, 2, 3]], [4, []], ]) + expect(groups.map((group) => group.rank)).toEqual([0, 1]) expect(navigableRowCount(groups)).toBe(5) }) diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts index 9b6f38f78b..5bf82b464b 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts @@ -89,6 +89,8 @@ export interface PropertyRow { export interface ResultGroup { result: SearchResultItem index: number + /** Position among the results; what a click reports, for the operation and for each of its properties. */ + rank: number properties: PropertyRow[] } @@ -97,8 +99,13 @@ export const groupSearchResults = ( results: SearchResultItem[] ): ResultGroup[] => { let index = 0 - return results.map((result) => { - const group: ResultGroup = { result, index: index++, properties: [] } + return results.map((result, rank) => { + const group: ResultGroup = { + result, + index: index++, + rank, + properties: [], + } const properties = result.type === 'api' ? (result.properties ?? []) : [] group.properties = properties.map((property) => ({ From b5e5828bb2b28ea20cd91c7f4e2afc4588ec622b Mon Sep 17 00:00:00 2001 From: Jan Calanog <reakaleek@users.noreply.github.com> Date: Tue, 3 Nov 2026 13:37:08 +0100 Subject: [PATCH 14/23] Never let a query word match a path placeholder in the route line A query word was matched against the raw spec path, so `index` or `id` matched `{index}` and `{id}` and a query such as `delete index` replaced most descriptions with a route line even though it named no path. A placeholder now stands as `*` when a path is compared, as the indexed endpoint keys already do, so only a literal segment can match. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --- .../NavigationSearch/apiPropertyResults.test.ts | 3 ++- .../web-components/NavigationSearch/apiPropertyResults.ts | 7 ++++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.test.ts b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.test.ts index e961673d06..61a00ff01f 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.test.ts +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.test.ts @@ -88,7 +88,8 @@ it.each([ ['/_search', ['_search'], '/_search'], ['GET /_search knn', ['_search', 'knn'], '/_search'], ['search', ['search'], '/{index}/_search'], - ['index', ['index'], '/{index}/_search'], + ['index', ['index'], undefined], + ['in', ['in'], undefined], ['scroll', ['scroll'], '/_search/scroll'], ['knn', ['knn'], undefined], ['get', [], undefined], diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts index 5bf82b464b..4e0faed256 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts @@ -30,7 +30,12 @@ const HTTP_METHODS = new Set([ 'options', ]) -const pathKey = (path: string) => path.toLowerCase().replace(/^\/+/, '') +/** A path as a query word can name it: lower case, no leading slash, and a `{parameter}` stands as `*` so a word never matches a placeholder. */ +const pathKey = (path: string) => + path + .toLowerCase() + .replace(/\{[^}]*\}/g, '*') + .replace(/^\/+/, '') const canBeField = (word: string) => word.length > 0 && From a215f392d4ad4cbe54e746c2061ddbbef789eac3 Mon Sep 17 00:00:00 2001 From: Jan Calanog <reakaleek@users.noreply.github.com> Date: Tue, 3 Nov 2026 13:38:44 +0100 Subject: [PATCH 15/23] Treat an HTTP method word as an endpoint only before a path A method word was never allowed to be the field, so `options` found no property and `_bulk delete` looked for a field named `_bulk`, although both are real schema fields. A method word now marks the endpoint only when the next word starts with a slash, as in `GET /_search`, on both the query builder and the result row's highlighting. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --- docs/data/openapi/api-explorer.md | 2 +- .../apiPropertyResults.test.ts | 6 +++- .../NavigationSearch/apiPropertyResults.ts | 34 +++++++++++-------- .../Query/SearchQueryBuilder.cs | 13 ++++--- .../ApiPropertySearchTests.cs | 2 ++ 5 files changed, 36 insertions(+), 21 deletions(-) diff --git a/docs/data/openapi/api-explorer.md b/docs/data/openapi/api-explorer.md index 31487b943f..5669ca6ee4 100644 --- a/docs/data/openapi/api-explorer.md +++ b/docs/data/openapi/api-explorer.md @@ -16,7 +16,7 @@ The cards for APIs that are in neither group show the API's deployments as small The API title comes from `info.title` in the spec, so fix naming and description copy in the spec. -API search matches parameter and field names, including prefixes and qualified paths. Direct operation and endpoint matches rank above field matches. Combine an endpoint and a field, such as `_search knn`, to find the operation and its matching fields. The order does not matter: `knn /_search`, `/_search knn`, `knn search` and `search knn` read the same. A word with a leading slash or an HTTP method is always the endpoint; with two plain words the index tries both orders and keeps the one whose endpoint exists, so both halves must match. With three or more plain words the last word is the field. Each matching operation lists up to three matching fields beneath it, with their paths, types, and locations. Child rows match the field's own name; ancestor names and descriptions provide context without adding unrelated children. Select a field to open its anchor, including fields inside collapsed sections. Arrow keys move through operations and fields in order; Enter opens the selected row. +API search matches parameter and field names, including prefixes and qualified paths. Direct operation and endpoint matches rank above field matches. Combine an endpoint and a field, such as `_search knn`, to find the operation and its matching fields. The order does not matter: `knn /_search`, `/_search knn`, `knn search` and `search knn` read the same. A word with a leading slash, or an HTTP method word right before one, is always the endpoint; on its own a word such as `options` or `delete` may name a field. With two plain words the index tries both orders and keeps the one whose endpoint exists, so both halves must match. With three or more plain words the last word is the field. Each matching operation lists up to three matching fields beneath it, with their paths, types, and locations. Child rows match the field's own name; ancestor names and descriptions provide context without adding unrelated children. Select a field to open its anchor, including fields inside collapsed sections. Arrow keys move through operations and fields in order; Enter opens the selected row. When a query names a path, such as `_search`, the result shows one route in place of the description: the method the page leads with and the path with the match highlighted. The route whose whole path is the query word wins, so `/_search` shows `/_search`; otherwise the operation's primary route shows when it contains the word, and an alternate route only when the primary does not. Every result uses the same bordered box, with matching fields grouped beneath the operation when present. Matches use the same yellow tint as the destination property's flash. Navigating to a field reveals it and flashes its name, including when search replaces the current page without a full reload. diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.test.ts b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.test.ts index 61a00ff01f..a4ec915389 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.test.ts +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.test.ts @@ -92,7 +92,8 @@ it.each([ ['in', ['in'], undefined], ['scroll', ['scroll'], '/_search/scroll'], ['knn', ['knn'], undefined], - ['get', [], undefined], + ['get', ['get'], undefined], + ['GET /_search', ['_search'], '/_search'], ['a', [], undefined], ])('picks the route for %s', (searchTerm, tokens, path) => { const matched = primaryRoute(routes, searchTerm) @@ -107,6 +108,9 @@ it.each([ ['GET /_search knn.field', ['knn', 'field']], ['_search knn', ['_search', 'knn']], ['/_search', []], + ['options', ['options']], + ['_bulk delete', ['_bulk', 'delete']], + ['get knn', ['get', 'knn']], ])('takes the field terms of %s', (searchTerm, terms) => { expect(fieldSearchTerms(searchTerm)).toEqual(terms) }) diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts index 4e0faed256..f2e9125861 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts @@ -37,23 +37,29 @@ const pathKey = (path: string) => .replace(/\{[^}]*\}/g, '*') .replace(/^\/+/, '') -const canBeField = (word: string) => - word.length > 0 && - !word.startsWith('/') && - !HTTP_METHODS.has(word.toLowerCase()) +const words = (searchTerm: string) => + searchTerm.trim().split(/\s+/).filter(Boolean) + +/** `GET` right before `/_search` is a method; on its own, `get` or `options` may well be a field name. */ +const isMethodBeforePath = (all: string[], i: number) => + HTTP_METHODS.has(all[i].toLowerCase()) && + (all[i + 1]?.startsWith('/') ?? false) /** The parts of a query that can name a field, split on dots, in either word order; what a property row highlights. */ -export const fieldSearchTerms = (searchTerm: string) => - Array.from( +export const fieldSearchTerms = (searchTerm: string) => { + const all = words(searchTerm) + return Array.from( new Set( - searchTerm - .trim() - .split(/\s+/) - .filter(canBeField) + all + .filter( + (word, i) => + !word.startsWith('/') && !isMethodBeforePath(all, i) + ) .flatMap((word) => word.split('.')) .filter(Boolean) ) ) +} /** * The query words that can name a path, and the one route to show for them: the route whose whole @@ -61,11 +67,11 @@ export const fieldSearchTerms = (searchTerm: string) => * with the page's primary route first, so that one wins among the partial matches. */ export const primaryRoute = (routes: ApiRoute[], searchTerm: string) => { - const tokens = searchTerm - .toLowerCase() - .split(/\s+/) + const all = words(searchTerm) + const tokens = all + .filter((_, i) => !isMethodBeforePath(all, i)) .map(pathKey) - .filter((word) => word.length > 1 && !HTTP_METHODS.has(word)) + .filter((word) => word.length > 1) const containing = routes.filter((route) => tokens.some((token) => pathKey(route.path).includes(token)) ) diff --git a/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs b/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs index 4da8fbda20..c30cc6db9c 100644 --- a/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs +++ b/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs @@ -88,8 +88,9 @@ public static Query ApplyApiPropertyQuery(Query query, string searchQuery, strin /// <summary> /// The ways a query may split into an endpoint half and a field half; empty when it never names a field. - /// A word that starts with a slash or is an HTTP method can only be endpoint, so the field is the last word - /// that is neither. Two plain words are ambiguous, so both orders are returned, the last word as the field first. + /// A word that starts with a slash, or an HTTP method right before one, can only be endpoint, so the field is the + /// last word that is neither; on its own, `get` or `options` may name a field. Two plain words are ambiguous, so + /// both orders are returned, the last word as the field first. /// </summary> private static IReadOnlyList<(string Operation, string Property)> ParseApiPropertyQuery(string searchQuery, string? typeFilter) { @@ -100,11 +101,13 @@ public static Query ApplyApiPropertyQuery(Query query, string searchQuery, strin return []; var words = input.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries); - var marked = words.Any(w => w.StartsWith('/') || HttpMethods.Contains(w)); - if (!marked && words.Length == 2) + var endpointWords = words.Select( + (w, i) => w.StartsWith('/') || (HttpMethods.Contains(w) && i + 1 < words.Length && words[i + 1].StartsWith('/')) + ).ToArray(); + if (!endpointWords.Any(e => e) && words.Length == 2) return [(words[0], words[1]), (words[1], words[0])]; - var field = Array.FindLastIndex(words, w => !w.StartsWith('/') && !HttpMethods.Contains(w)); + var field = Array.LastIndexOf(endpointWords, false); if (field < 0) return []; return [(string.Join(' ', words.Where((_, i) => i != field)), words[field])]; diff --git a/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs b/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs index d93acf16fa..684cbb9019 100644 --- a/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs +++ b/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs @@ -41,6 +41,8 @@ public void BuildApiPropertyQuery_Identifier_ReturnsNestedInnerHits(string input [Arguments("GET /_search knn", "knn")] [Arguments("knn /_search", "knn")] [Arguments("knn GET /_search", "knn")] + [Arguments("options", "options")] + [Arguments("_bulk delete", "delete")] [Arguments("track_total", "track_total")] [Arguments("trav", "trav")] public void BuildApiPropertyQuery_FieldTerm_MatchesOnlyItsOwnNameWithBoundedScores(string input, string name) From 6d8d93c399c7f8fcb995132fdabbf3ce360e06b6 Mon Sep 17 00:00:00 2001 From: Jan Calanog <reakaleek@users.noreply.github.com> Date: Tue, 3 Nov 2026 13:40:07 +0100 Subject: [PATCH 16/23] Keep field matching out of the way of pages in the docs-wide search The nested field query also ran in the unfiltered docs search for any single word, matching field names by prefix, so `s` or `index` lifted hundreds of API operations above the pages about them and inflated the type counts. The docs-wide search now tries only words that look like identifiers, containing `_` or `.`, and matches a field by its exact name; the prefix clause stays in the API-filtered lookup where the bare-word endpoint boost already lives for the same reason. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --- docs/data/openapi/api-explorer.md | 2 +- .../Query/SearchQueryBuilder.cs | 65 +++++++++++-------- .../ApiPropertySearchTests.cs | 18 ++++- 3 files changed, 56 insertions(+), 29 deletions(-) diff --git a/docs/data/openapi/api-explorer.md b/docs/data/openapi/api-explorer.md index 5669ca6ee4..bbea81ef0c 100644 --- a/docs/data/openapi/api-explorer.md +++ b/docs/data/openapi/api-explorer.md @@ -16,7 +16,7 @@ The cards for APIs that are in neither group show the API's deployments as small The API title comes from `info.title` in the spec, so fix naming and description copy in the spec. -API search matches parameter and field names, including prefixes and qualified paths. Direct operation and endpoint matches rank above field matches. Combine an endpoint and a field, such as `_search knn`, to find the operation and its matching fields. The order does not matter: `knn /_search`, `/_search knn`, `knn search` and `search knn` read the same. A word with a leading slash, or an HTTP method word right before one, is always the endpoint; on its own a word such as `options` or `delete` may name a field. With two plain words the index tries both orders and keeps the one whose endpoint exists, so both halves must match. With three or more plain words the last word is the field. Each matching operation lists up to three matching fields beneath it, with their paths, types, and locations. Child rows match the field's own name; ancestor names and descriptions provide context without adding unrelated children. Select a field to open its anchor, including fields inside collapsed sections. Arrow keys move through operations and fields in order; Enter opens the selected row. +API search matches parameter and field names, including prefixes and qualified paths. The docs-wide search matches a field only by its exact name, and only for a word that contains `_` or `.`, so a plain word keeps ranking pages first. Direct operation and endpoint matches rank above field matches. Combine an endpoint and a field, such as `_search knn`, to find the operation and its matching fields. The order does not matter: `knn /_search`, `/_search knn`, `knn search` and `search knn` read the same. A word with a leading slash, or an HTTP method word right before one, is always the endpoint; on its own a word such as `options` or `delete` may name a field. With two plain words the index tries both orders and keeps the one whose endpoint exists, so both halves must match. With three or more plain words the last word is the field. Each matching operation lists up to three matching fields beneath it, with their paths, types, and locations. Child rows match the field's own name; ancestor names and descriptions provide context without adding unrelated children. Select a field to open its anchor, including fields inside collapsed sections. Arrow keys move through operations and fields in order; Enter opens the selected row. When a query names a path, such as `_search`, the result shows one route in place of the description: the method the page leads with and the path with the match highlighted. The route whose whole path is the query word wins, so `/_search` shows `/_search`; otherwise the operation's primary route shows when it contains the word, and an alternate route only when the primary does not. Every result uses the same bordered box, with matching fields grouped beneath the operation when present. Matches use the same yellow tint as the destination property's flash. Navigating to a field reveals it and flashes its name, including when search replaces the current page without a full reload. diff --git a/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs b/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs index c30cc6db9c..e0d838974f 100644 --- a/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs +++ b/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs @@ -54,7 +54,9 @@ public static bool IsApiPropertyHits(string innerHitsName) => /// <summary>The nested field query for the query's first reading, see <see cref="ParseApiPropertyQuery"/>.</summary> public static Query? BuildApiPropertyQuery(string searchQuery, string? typeFilter) => - ParseApiPropertyQuery(searchQuery, typeFilter) is [var first, ..] ? BuildNestedPropertyQuery(first.Property, ApiPropertyHits) : null; + ParseApiPropertyQuery(searchQuery, typeFilter) is [var first, ..] + ? BuildNestedPropertyQuery(first.Property, ApiPropertyHits, allowPrefix: typeFilter == "api") + : null; public static Query ApplyApiPropertyQuery(Query query, string searchQuery, string? typeFilter) { @@ -62,7 +64,9 @@ public static Query ApplyApiPropertyQuery(Query query, string searchQuery, strin // With one reading the endpoint only lifts the operation. With two, the index decides which reading holds, // so each requires its endpoint: a bare word that names no endpoint, such as `_knn`, matches nothing. var branches = readings - .Select((r, i) => BuildReadingQuery(r, InnerHitsName(i), endpointRequired: readings.Count > 1)) + .Select( + (r, i) => BuildReadingQuery(r, InnerHitsName(i), endpointRequired: readings.Count > 1, allowPrefix: typeFilter == "api") + ) .OfType<Query>() .ToList(); if (branches.Count == 0) @@ -72,9 +76,14 @@ public static Query ApplyApiPropertyQuery(Query query, string searchQuery, strin return new BoolQuery { Should = [query, properties], MinimumShouldMatch = 1, Filter = [DocumentFilter] }; } - private static Query? BuildReadingQuery((string Operation, string Property) reading, string innerHitsName, bool endpointRequired) + private static Query? BuildReadingQuery( + (string Operation, string Property) reading, + string innerHitsName, + bool endpointRequired, + bool allowPrefix + ) { - var properties = BuildNestedPropertyQuery(reading.Property, innerHitsName); + var properties = BuildNestedPropertyQuery(reading.Property, innerHitsName, allowPrefix); if (reading.Operation.Length == 0) return properties; @@ -97,7 +106,9 @@ public static Query ApplyApiPropertyQuery(Query query, string searchQuery, strin var input = searchQuery.Trim(); if (input.Length == 0 || typeFilter is not (null or "" or "all" or "api")) return []; - if (typeFilter != "api" && input.Any(char.IsWhiteSpace) && !input.Contains('.') && !input.Contains('_')) + // The docs-wide search only tries words that look like identifiers; a plain word would lift every API + // operation that happens to have a field of that name above the pages about it. + if (typeFilter != "api" && !input.Contains('.') && !input.Contains('_')) return []; var words = input.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries); @@ -113,13 +124,13 @@ public static Query ApplyApiPropertyQuery(Query query, string searchQuery, strin return [(string.Join(' ', words.Where((_, i) => i != field)), words[field])]; } - private static Query BuildNestedPropertyQuery(string property, string innerHitsName) => + private static Query BuildNestedPropertyQuery(string property, string innerHitsName, bool allowPrefix) => new NestedQuery { Path = QueryFieldNames.ApiProperties, IgnoreUnmapped = true, ScoreMode = ChildScoreMode.Max, - Query = BuildPropertyMatchQuery(property), + Query = BuildPropertyMatchQuery(property, allowPrefix), InnerHits = new InnerHits { Name = innerHitsName, @@ -128,9 +139,9 @@ private static Query BuildNestedPropertyQuery(string property, string innerHitsN } }; - private static Query BuildPropertyMatchQuery(string input) + private static Query BuildPropertyMatchQuery(string input, bool allowPrefix) { - var name = BuildPropertyNameQuery(input); + var name = BuildPropertyNameQuery(input, allowPrefix); var separator = input.LastIndexOf('.'); if (separator < 0 || separator == input.Length - 1) return name; @@ -142,7 +153,7 @@ private static Query BuildPropertyMatchQuery(string input) name, new BoolQuery { - Must = [BuildPropertyNameQuery(input[(separator + 1)..])], + Must = [BuildPropertyNameQuery(input[(separator + 1)..], allowPrefix)], Filter = [ new MatchBoolPrefixQuery { Field = QueryFieldNames.ApiPropertiesPathMatch, Query = input, Operator = Operator.And } @@ -152,25 +163,25 @@ private static Query BuildPropertyMatchQuery(string input) }; } - private static Query BuildPropertyNameQuery(string name) => - new DisMaxQuery + /// <summary> + /// Bound field scores below operation matches, regardless of term rarity in nested documents. Only an + /// API-filtered lookup matches by prefix: in the docs-wide search a prefix such as `s` would lift hundreds of operations. + /// </summary> + private static Query BuildPropertyNameQuery(string name, bool allowPrefix) + { + var exact = new ConstantScoreQuery { - // Bound field scores below operation matches, regardless of term rarity in nested documents. - Queries = - [ - new ConstantScoreQuery - { - Filter = new TermQuery { Field = QueryFieldNames.ApiPropertiesName, Value = name, CaseInsensitive = true }, - Boost = 1 - }, - new ConstantScoreQuery - { - // A keyword prefix preserves underscores and field names longer than the edge-ngram limit. - Filter = new PrefixQuery { Field = QueryFieldNames.ApiPropertiesName, Value = name, CaseInsensitive = true }, - Boost = 0.6f - } - ] + Filter = new TermQuery { Field = QueryFieldNames.ApiPropertiesName, Value = name, CaseInsensitive = true }, + Boost = 1 }; + // A keyword prefix preserves underscores and field names longer than the edge-ngram limit. + var prefix = new ConstantScoreQuery + { + Filter = new PrefixQuery { Field = QueryFieldNames.ApiPropertiesName, Value = name, CaseInsensitive = true }, + Boost = 0.6f + }; + return new DisMaxQuery { Queries = allowPrefix ? [exact, prefix] : [exact] }; + } public static Query? BuildDiminishQuery(IReadOnlyCollection<string> diminishTerms) { diff --git a/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs b/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs index 684cbb9019..72f72059f1 100644 --- a/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs +++ b/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs @@ -24,7 +24,7 @@ public class ApiPropertySearchTests [Arguments("travel_agency", "api")] [Arguments("trav", "api")] [Arguments("flight.travel", "api")] - [Arguments("trav", null)] + [Arguments("track_total", null)] public void BuildApiPropertyQuery_Identifier_ReturnsNestedInnerHits(string input, string? filter) { using var json = JsonDocument.Parse( @@ -77,6 +77,20 @@ public void BuildApiPropertyQuery_FieldTerm_MatchesOnlyItsOwnNameWithBoundedScor scores[0].Should().BeGreaterThan(scores[1], "an exact field name ranks ahead of a prefix"); } + [Test] + [Arguments(null, 1)] + [Arguments("all", 1)] + [Arguments("api", 2)] + public void BuildApiPropertyQuery_PrefixMatch_OnlyInTheApiFilteredLookup(string? filter, int nameClauses) + { + using var json = JsonDocument.Parse( + Client.RequestResponseSerializer.SerializeToString(SearchQueryBuilder.BuildApiPropertyQuery("track_total", filter)) + ); + var clauses = json.RootElement.GetProperty("nested").GetProperty("query").GetProperty("dis_max").GetProperty("queries"); + clauses.GetArrayLength().Should().Be(nameClauses); + clauses[0].GetRawText().Should().Contain("\"term\""); + } + [Test] public void BuildApiPropertyQuery_QualifiedPath_RequiresMatchingLeafAndPath() { @@ -179,6 +193,8 @@ public void ProcessHit_InnerHitsFromBothReadings_AreMerged() [Test] [Arguments("how to search", null)] [Arguments("trav", "docs")] + [Arguments("trav", null)] + [Arguments("index", "all")] [Arguments("", "api")] [Arguments("/_search", "api")] [Arguments("GET /_search", "api")] From 014bd997b38b1f40528e251e74aa01471fe03944 Mon Sep 17 00:00:00 2001 From: Jan Calanog <reakaleek@users.noreply.github.com> Date: Tue, 3 Nov 2026 13:40:51 +0100 Subject: [PATCH 17/23] Match the literal endpoint as well as its underscore alias The endpoint half of a combined query tried the underscore alias first and, since `_deployments` always builds a query, never tried the literal `deployments`. With the endpoint required in a two-word query, `deployments status` could not reach the fields of `/deployments`. The endpoint half now accepts the path as typed or its alias. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --- .../Query/SearchQueryBuilder.cs | 17 ++++++++++- .../ApiPropertySearchTests.cs | 29 ++++++++++++------- 2 files changed, 35 insertions(+), 11 deletions(-) diff --git a/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs b/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs index e0d838974f..091b8b0044 100644 --- a/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs +++ b/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs @@ -87,7 +87,7 @@ bool allowPrefix if (reading.Operation.Length == 0) return properties; - var endpoint = BuildBareWordEndpointQuery(reading.Operation) ?? BuildApiEndpointQuery(reading.Operation); + var endpoint = BuildEndpointHalfQuery(reading.Operation); if (endpoint is null) return endpointRequired ? null : properties; return endpointRequired @@ -95,6 +95,21 @@ bool allowPrefix : new BoolQuery { Must = [properties], Should = [endpoint] }; } + /// <summary> + /// The endpoint half as typed and, for a bare word, as its underscore alias too: `deployments` is a route of + /// its own while `search` means `_search`, and a required endpoint must accept either. + /// </summary> + private static Query? BuildEndpointHalfQuery(string operation) + { + var candidates = new[] { BuildApiEndpointQuery(operation), BuildBareWordEndpointQuery(operation) }.OfType<Query>().ToList(); + return candidates.Count switch + { + 0 => null, + 1 => candidates[0], + _ => new DisMaxQuery { Queries = candidates } + }; + } + /// <summary> /// The ways a query may split into an endpoint half and a field half; empty when it never names a field. /// A word that starts with a slash, or an HTTP method right before one, can only be endpoint, so the field is the diff --git a/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs b/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs index 72f72059f1..47a130b544 100644 --- a/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs +++ b/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs @@ -151,16 +151,7 @@ public void ApplyApiPropertyQuery_TwoPlainWords_TriesBothReadingsWithTheEndpoint var must = knn.GetProperty("must"); must.GetArrayLength().Should().Be(2); must[0].GetProperty("nested").GetProperty("query").GetRawText().Should().Contain("\"value\":\"knn\""); - must[1] - .GetProperty("dis_max") - .GetProperty("queries")[0] - .GetProperty("constant_score") - .GetProperty("filter") - .GetProperty("terms") - .GetProperty("api.endpoints")[0] - .GetString() - .Should() - .Be("_search"); + must[1].GetRawText().Should().Contain("\"api.endpoints\":[\"_search\""); knn.TryGetProperty("should", out _).Should().BeFalse(); var names = System .Text @@ -178,6 +169,24 @@ public void ApplyApiPropertyQuery_TwoPlainWords_TriesBothReadingsWithTheEndpoint .AllSatisfy(n => SearchQueryBuilder.IsApiPropertyHits(n).Should().BeTrue()); } + [Test] + public void ApplyApiPropertyQuery_EndpointHalf_MatchesTheLiteralPathAndItsUnderscoreAlias() + { + using var json = JsonDocument.Parse( + Client.RequestResponseSerializer.SerializeToString( + SearchQueryBuilder.ApplyApiPropertyQuery( + new Elastic.Clients.Elasticsearch.QueryDsl.MatchNoneQuery(), + "deployments status", + "api" + ) + ) + ); + var readings = json.RootElement.GetProperty("bool").GetProperty("should")[1].GetProperty("bool").GetProperty("should"); + var status = readings.EnumerateArray().Single(r => r.GetRawText().Contains("\"value\":\"status\"")).GetProperty("bool"); + var endpoint = status.GetProperty("must")[1].GetRawText(); + endpoint.Should().Contain("\"deployments\"").And.Contain("\"_deployments\""); + } + [Test] public void ProcessHit_InnerHitsFromBothReadings_AreMerged() { From 79e01fa2e3dce08c36b2329a18dca0f9f74c4a0d Mon Sep 17 00:00:00 2001 From: Jan Calanog <reakaleek@users.noreply.github.com> Date: Tue, 3 Nov 2026 13:42:21 +0100 Subject: [PATCH 18/23] Keep only the inner hits of the reading a document matched Elasticsearch computes a nested query's inner hits for every returned document from that nested query alone, so a two-word query's rejected reading still attached its field rows: for `knn search` the reading that paired field `search` with endpoint `_knn` returned `search_*` rows on the search operation, which could take two of the three slots. Each reading is now a named query carrying its inner-hits name, and the processor keeps a group only when the hit matched that reading. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --- .../Highlighting/SearchResultProcessor.cs | 12 ++++++++- .../Query/SearchQueryBuilder.cs | 4 ++- .../ApiPropertySearchTests.cs | 27 ++++++++++++++----- 3 files changed, 34 insertions(+), 9 deletions(-) diff --git a/src/services/search/Elastic.Documentation.Search/Highlighting/SearchResultProcessor.cs b/src/services/search/Elastic.Documentation.Search/Highlighting/SearchResultProcessor.cs index ac357bc3c4..dc135137f8 100644 --- a/src/services/search/Elastic.Documentation.Search/Highlighting/SearchResultProcessor.cs +++ b/src/services/search/Elastic.Documentation.Search/Highlighting/SearchResultProcessor.cs @@ -67,9 +67,12 @@ private static IReadOnlyList<ApiPropertyEntry> MatchedProperties<TDocument>(Hit< if (hit.InnerHits is null) return []; + // A reading's inner hits are computed from its nested query alone, so a reading the document did not + // match still carries them; only a named reading this hit matched counts. + var matched = MatchedQueryNames(hit); return hit .InnerHits - .Where(group => SearchQueryBuilder.IsApiPropertyHits(group.Key)) + .Where(group => SearchQueryBuilder.IsApiPropertyHits(group.Key) && (matched is null || matched.Contains(group.Key))) .SelectMany(group => group.Value.Hits.Hits) .OrderByDescending(h => h.Score ?? 0) .Select( @@ -81,6 +84,13 @@ private static IReadOnlyList<ApiPropertyEntry> MatchedProperties<TDocument>(Hit< .ToArray(); } + /// <summary>The named queries this hit matched, or null when the query named none.</summary> + private static IReadOnlySet<string>? MatchedQueryNames<TDocument>(Hit<TDocument> hit) => + hit.MatchedQueries?.Match<IReadOnlySet<string>>( + names => (names ?? []).ToHashSet(StringComparer.Ordinal), + scored => (scored?.Keys ?? []).ToHashSet(StringComparer.Ordinal) + ); + public static IReadOnlyDictionary<string, long> ExtractTermsAggregation<TDocument>( Clients.Elasticsearch.SearchResponse<TDocument> response, string aggregationName diff --git a/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs b/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs index 091b8b0044..5d27996e90 100644 --- a/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs +++ b/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs @@ -90,8 +90,10 @@ bool allowPrefix var endpoint = BuildEndpointHalfQuery(reading.Operation); if (endpoint is null) return endpointRequired ? null : properties; + // Named after its inner hits, so the result processor can tell which reading a hit matched: inner hits + // are computed from the nested query alone, even for a reading whose endpoint did not hold. return endpointRequired - ? new BoolQuery { Must = [properties, endpoint] } + ? new BoolQuery { Must = [properties, endpoint], QueryName = innerHitsName } : new BoolQuery { Must = [properties], Should = [endpoint] }; } diff --git a/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs b/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs index 47a130b544..84dc7566f5 100644 --- a/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs +++ b/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs @@ -153,6 +153,7 @@ public void ApplyApiPropertyQuery_TwoPlainWords_TriesBothReadingsWithTheEndpoint must[0].GetProperty("nested").GetProperty("query").GetRawText().Should().Contain("\"value\":\"knn\""); must[1].GetRawText().Should().Contain("\"api.endpoints\":[\"_search\""); knn.TryGetProperty("should", out _).Should().BeFalse(); + readings.EnumerateArray().Should().AllSatisfy(r => r.GetProperty("bool").TryGetProperty("_name", out _).Should().BeTrue()); var names = System .Text .RegularExpressions @@ -192,13 +193,25 @@ public void ProcessHit_InnerHitsFromBothReadings_AreMerged() { var second = $$$""","api_properties_1":{"hits":{"total":{"value":1,"relation":"eq"},"max_score":4,"hits":[{{{InnerHit("req-b", 4, "b")}}}]}}"""; - var json = SearchResponseJson(InnerHit("req-a", 5, "a"), second); + var json = SearchResponseJson(InnerHit("req-a", 5, "a"), second, "\"matched_queries\":[\"api_properties\",\"api_properties_1\"],"); var result = SearchResultProcessor.ProcessHit(ParseResponse(json).Hits.Single(), "a", new Dictionary<string, string[]>()); result.Properties.Select(p => p.Anchor).Should().Equal("req-a", "req-b"); } + [Test] + public void ProcessHit_InnerHitsOfAReadingTheDocumentDidNotMatch_AreDropped() + { + var second = + $$$""","api_properties_1":{"hits":{"total":{"value":1,"relation":"eq"},"max_score":4,"hits":[{{{InnerHit("req-b", 4, "b")}}}]}}"""; + var json = SearchResponseJson(InnerHit("req-a", 5, "a"), second, "\"matched_queries\":[\"api_properties\"],"); + + var result = SearchResultProcessor.ProcessHit(ParseResponse(json).Hits.Single(), "a", new Dictionary<string, string[]>()); + + result.Properties.Select(p => p.Anchor).Should().Equal("req-a"); + } + [Test] [Arguments("how to search", null)] [Arguments("trav", "docs")] @@ -258,15 +271,15 @@ public void ProcessHit_ManyInnerHits_KeepsTheThreeBestDistinctAnchorsInScoreOrde result.Properties.Select(p => p.Path).Should().Equal("a", "b", "c"); } - private static string SearchResponseJson(string innerHits, string moreInnerHitGroups = "") => + private static string SearchResponseJson(string innerHits, string moreInnerHitGroups = "", string matchedQueries = "") => """ {"took":1,"timed_out":false,"_shards":{"total":1,"successful":1,"failed":0},"hits":{"total":{"value":1,"relation":"eq"},"hits":[ - {"_index":"test","_id":"search","_score":1,"_source":{"title":"Search","search_title":"Search","path":"/search"}, + {"_index":"test","_id":"search","_score":1,__MATCHED__"_source":{"title":"Search","search_title":"Search","path":"/search"}, "inner_hits":{"api_properties":{"hits":{"total":{"value":5,"relation":"eq"},"max_score":5,"hits":[__INNER_HITS__]}}__MORE_GROUPS__}}]}} - """.Replace( - "__INNER_HITS__", - innerHits - ).Replace("__MORE_GROUPS__", moreInnerHitGroups); + """ + .Replace("__INNER_HITS__", innerHits) + .Replace("__MORE_GROUPS__", moreInnerHitGroups) + .Replace("__MATCHED__", matchedQueries); private static string InnerHit(string anchor, double score, string path) => $$$""" From 467abf9098e59da5ce5b04d2092ade6d8d6bd00d Mon Sep 17 00:00:00 2001 From: Jan Calanog <reakaleek@users.noreply.github.com> Date: Tue, 3 Nov 2026 13:47:37 +0100 Subject: [PATCH 19/23] Index every listing the operation page keeps apart The exporter rendered every property description as an empty string, so two listings that differ only in their variant descriptions hashed alike and the second was folded into the first. The page renders the descriptions and keeps both, so its anchors had no index entries. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --- .../Export/OpenApiDocumentExporter.cs | 3 +- .../OpenApiDocumentExporterTests.cs | 28 +++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/src/Elastic.ApiExplorer/Export/OpenApiDocumentExporter.cs b/src/Elastic.ApiExplorer/Export/OpenApiDocumentExporter.cs index 2ff992425b..467036a371 100644 --- a/src/Elastic.ApiExplorer/Export/OpenApiDocumentExporter.cs +++ b/src/Elastic.ApiExplorer/Export/OpenApiDocumentExporter.cs @@ -125,7 +125,8 @@ public IEnumerable<DocumentationDocument> ConvertToDocuments(OpenApiDocument ope openApiDocument, new PropertyDisplayOptions { - RenderMarkdown = _ => HtmlString.Empty, + // Listing sharing keys on the rendered description, so a blank renderer would merge listings the page keeps apart. + RenderMarkdown = markdown => new HtmlString(markdown), ApiRootUrl = productUrl, VersionsConfiguration = versionsConfiguration } diff --git a/tests/Elastic.ApiExplorer.Tests/OpenApiDocumentExporterTests.cs b/tests/Elastic.ApiExplorer.Tests/OpenApiDocumentExporterTests.cs index 2db6d0b304..b4b1e70a24 100644 --- a/tests/Elastic.ApiExplorer.Tests/OpenApiDocumentExporterTests.cs +++ b/tests/Elastic.ApiExplorer.Tests/OpenApiDocumentExporterTests.cs @@ -270,6 +270,34 @@ Returns one or more data sources. doc.Body.Should().NotContain("/_query/data_source</span>"); } + [Test] + public async Task ConvertToDocuments_UnionsThatDifferOnlyByDescription_IndexBothListings() + { + var spec = await TestSpecs.LoadSpecAsync( + """ + { + "openapi":"3.0.3", "info":{"title":"Fields","version":"1"}, + "paths":{"/thing":{"post":{"operationId":"thing","responses":{"200":{"description":"OK"}}, + "requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{ + "choice":{"oneOf":[ + {"type":"object","description":"Code it","properties":{"c1":{"type":"string"},"c2":{"type":"string"},"c3":{"type":"string"},"c4":{"type":"string"},"c5":{"type":"string"},"c6":{"type":"string"}}}, + {"type":"object","description":"Number it","properties":{"n1":{"type":"integer"},"n2":{"type":"integer"},"n3":{"type":"integer"},"n4":{"type":"integer"},"n5":{"type":"integer"},"n6":{"type":"integer"}}} + ]}, + "pick":{"oneOf":[ + {"type":"object","description":"Code it, but differently","properties":{"c1":{"type":"string"},"c2":{"type":"string"},"c3":{"type":"string"},"c4":{"type":"string"},"c5":{"type":"string"},"c6":{"type":"string"}}}, + {"type":"object","description":"Number it, but differently","properties":{"n1":{"type":"integer"},"n2":{"type":"integer"},"n3":{"type":"integer"},"n4":{"type":"integer"},"n5":{"type":"integer"},"n6":{"type":"integer"}}} + ]} + }}}}}}}} + } + """ + ); + + var doc = new OpenApiDocumentExporter(StackVersions()).ConvertToDocuments(spec, "fields").Single(); + + // Large enough to be shared, alike in every way but the variant descriptions: the page keeps both listings, so the index must too. + doc.Api!.Properties.Select(p => p.Path).Should().Contain(["choice.c1", "choice.n6", "pick.c1", "pick.n6"]); + } + [Test] public void Operation_MethodList_IndexesEveryRouteWithItsMethods() { From 915d2301ca8cefc30e5cd339ec4c4bed024474d4 Mon Sep 17 00:00:00 2001 From: Jan Calanog <reakaleek@users.noreply.github.com> Date: Tue, 3 Nov 2026 14:12:17 +0100 Subject: [PATCH 20/23] Try a docs-wide field word only when it looks like an identifier The guard looked at the whole query, so `elasticsearch index_name settings` passed it on the underscore and then tried the plain word `settings` as the field, lifting every operation with a `settings` field into the docs-wide results. The check now applies to the field word of each reading, which is what the docs describe. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --- .../Query/SearchQueryBuilder.cs | 12 +++++++----- .../ApiPropertySearchTests.cs | 3 +++ 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs b/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs index 5d27996e90..5b8094e904 100644 --- a/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs +++ b/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs @@ -123,12 +123,14 @@ bool allowPrefix var input = searchQuery.Trim(); if (input.Length == 0 || typeFilter is not (null or "" or "all" or "api")) return []; - // The docs-wide search only tries words that look like identifiers; a plain word would lift every API - // operation that happens to have a field of that name above the pages about it. - if (typeFilter != "api" && !input.Contains('.') && !input.Contains('_')) - return []; + var readings = ParseReadings(input.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)); + // The docs-wide search only tries a field word that looks like an identifier; a plain word would lift every + // API operation that happens to have a field of that name above the pages about it. + return typeFilter == "api" ? readings : readings.Where(r => r.Property.Contains('.') || r.Property.Contains('_')).ToArray(); + } - var words = input.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries); + private static IReadOnlyList<(string Operation, string Property)> ParseReadings(string[] words) + { var endpointWords = words.Select( (w, i) => w.StartsWith('/') || (HttpMethods.Contains(w) && i + 1 < words.Length && words[i + 1].StartsWith('/')) ).ToArray(); diff --git a/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs b/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs index 84dc7566f5..392828717e 100644 --- a/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs +++ b/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs @@ -25,6 +25,7 @@ public class ApiPropertySearchTests [Arguments("trav", "api")] [Arguments("flight.travel", "api")] [Arguments("track_total", null)] + [Arguments("knn_field search", null)] public void BuildApiPropertyQuery_Identifier_ReturnsNestedInnerHits(string input, string? filter) { using var json = JsonDocument.Parse( @@ -217,6 +218,8 @@ public void ProcessHit_InnerHitsOfAReadingTheDocumentDidNotMatch_AreDropped() [Arguments("trav", "docs")] [Arguments("trav", null)] [Arguments("index", "all")] + [Arguments("elasticsearch index_name settings", null)] + [Arguments("/_search knn", null)] [Arguments("", "api")] [Arguments("/_search", "api")] [Arguments("GET /_search", "api")] From 0e03da259a4527ea442a78fc20e9e6f7ef191099 Mon Sep 17 00:00:00 2001 From: Jan Calanog <reakaleek@users.noreply.github.com> Date: Tue, 3 Nov 2026 14:14:34 +0100 Subject: [PATCH 21/23] Keep no field rows on a hit that matched no reading Elasticsearch leaves matched_queries out of a hit when no named query matched it, so a hit the lexical branch alone matched looked the same as a hit from a query that named nothing, and kept the inner hits of every reading. Every reading is now named, so the processor can require the name and drop the rows of a reading the hit did not match. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --- .../Highlighting/SearchResultProcessor.cs | 15 +++++--- .../Query/SearchQueryBuilder.cs | 17 +++++---- .../ApiPropertySearchTests.cs | 38 ++++++++++++++++++- 3 files changed, 55 insertions(+), 15 deletions(-) diff --git a/src/services/search/Elastic.Documentation.Search/Highlighting/SearchResultProcessor.cs b/src/services/search/Elastic.Documentation.Search/Highlighting/SearchResultProcessor.cs index dc135137f8..5dd33f685f 100644 --- a/src/services/search/Elastic.Documentation.Search/Highlighting/SearchResultProcessor.cs +++ b/src/services/search/Elastic.Documentation.Search/Highlighting/SearchResultProcessor.cs @@ -2,6 +2,7 @@ // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information +using System.Collections.Frozen; using System.Text.Json; using Elastic.Clients.Elasticsearch.Core.Search; using Elastic.Documentation.Search.Contract; @@ -67,12 +68,13 @@ private static IReadOnlyList<ApiPropertyEntry> MatchedProperties<TDocument>(Hit< if (hit.InnerHits is null) return []; - // A reading's inner hits are computed from its nested query alone, so a reading the document did not - // match still carries them; only a named reading this hit matched counts. + // A reading's inner hits are computed from its nested query alone, so a reading the document did not match + // still carries them, and Elasticsearch omits matched_queries when no named query matched at all; only a + // reading this hit matched counts. var matched = MatchedQueryNames(hit); return hit .InnerHits - .Where(group => SearchQueryBuilder.IsApiPropertyHits(group.Key) && (matched is null || matched.Contains(group.Key))) + .Where(group => SearchQueryBuilder.IsApiPropertyHits(group.Key) && matched.Contains(group.Key)) .SelectMany(group => group.Value.Hits.Hits) .OrderByDescending(h => h.Score ?? 0) .Select( @@ -84,12 +86,13 @@ private static IReadOnlyList<ApiPropertyEntry> MatchedProperties<TDocument>(Hit< .ToArray(); } - /// <summary>The named queries this hit matched, or null when the query named none.</summary> - private static IReadOnlySet<string>? MatchedQueryNames<TDocument>(Hit<TDocument> hit) => + /// <summary>The named queries this hit matched; empty when none did, as Elasticsearch then omits the field.</summary> + private static IReadOnlySet<string> MatchedQueryNames<TDocument>(Hit<TDocument> hit) => hit.MatchedQueries?.Match<IReadOnlySet<string>>( names => (names ?? []).ToHashSet(StringComparer.Ordinal), scored => (scored?.Keys ?? []).ToHashSet(StringComparer.Ordinal) - ); + ) + ?? FrozenSet<string>.Empty; public static IReadOnlyDictionary<string, long> ExtractTermsAggregation<TDocument>( Clients.Elasticsearch.SearchResponse<TDocument> response, diff --git a/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs b/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs index 5b8094e904..cfa9342568 100644 --- a/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs +++ b/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs @@ -84,17 +84,18 @@ bool allowPrefix ) { var properties = BuildNestedPropertyQuery(reading.Property, innerHitsName, allowPrefix); - if (reading.Operation.Length == 0) - return properties; - - var endpoint = BuildEndpointHalfQuery(reading.Operation); + var endpoint = reading.Operation.Length == 0 ? null : BuildEndpointHalfQuery(reading.Operation); + if (endpoint is null && endpointRequired) + return null; + // Named after its inner hits so the result processor can tell which reading a hit matched: inner hits are + // computed from the nested query alone, even for a reading whose endpoint did not hold, and a hit the lexical + // branch alone matched carries no name. The name sits on the whole reading, as Elasticsearch reports a named + // clause that matched even when its parent did not. if (endpoint is null) - return endpointRequired ? null : properties; - // Named after its inner hits, so the result processor can tell which reading a hit matched: inner hits - // are computed from the nested query alone, even for a reading whose endpoint did not hold. + return new BoolQuery { Must = [properties], QueryName = innerHitsName }; return endpointRequired ? new BoolQuery { Must = [properties, endpoint], QueryName = innerHitsName } - : new BoolQuery { Must = [properties], Should = [endpoint] }; + : new BoolQuery { Must = [properties], Should = [endpoint], QueryName = innerHitsName }; } /// <summary> diff --git a/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs b/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs index 392828717e..107143327e 100644 --- a/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs +++ b/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs @@ -134,6 +134,28 @@ public void ApplyApiPropertyQuery_MarkedEndpointAndField_RequiresFieldMatchBefor endpoint.GetProperty("filter").GetProperty("terms").GetProperty("api.endpoints")[0].GetString().Should().Be("_search"); } + [Test] + [Arguments("track_total")] + [Arguments("/_search knn")] + public void ApplyApiPropertyQuery_SingleReading_IsNamedAfterItsInnerHits(string input) + { + using var json = JsonDocument.Parse( + Client.RequestResponseSerializer.SerializeToString( + SearchQueryBuilder.ApplyApiPropertyQuery(new Elastic.Clients.Elasticsearch.QueryDsl.MatchNoneQuery(), input, "api") + ) + ); + var reading = json.RootElement.GetProperty("bool").GetProperty("should")[1].GetProperty("bool"); + reading.GetProperty("_name").GetString().Should().Be("api_properties"); + reading + .GetProperty("must") + .GetProperty("nested") + .GetProperty("inner_hits") + .GetProperty("name") + .GetString() + .Should() + .Be("api_properties"); + } + [Test] [Arguments("_search knn")] [Arguments("search knn")] @@ -213,6 +235,16 @@ public void ProcessHit_InnerHitsOfAReadingTheDocumentDidNotMatch_AreDropped() result.Properties.Select(p => p.Anchor).Should().Equal("req-a"); } + [Test] + public void ProcessHit_HitThatMatchedNoReading_KeepsNoProperties() + { + var json = SearchResponseJson(InnerHit("req-index", 5, "index"), matchedQueries: ""); + + var result = SearchResultProcessor.ProcessHit(ParseResponse(json).Hits.Single(), "bulk index", new Dictionary<string, string[]>()); + + result.Properties.Should().BeEmpty(); + } + [Test] [Arguments("how to search", null)] [Arguments("trav", "docs")] @@ -274,7 +306,11 @@ public void ProcessHit_ManyInnerHits_KeepsTheThreeBestDistinctAnchorsInScoreOrde result.Properties.Select(p => p.Path).Should().Equal("a", "b", "c"); } - private static string SearchResponseJson(string innerHits, string moreInnerHitGroups = "", string matchedQueries = "") => + private static string SearchResponseJson( + string innerHits, + string moreInnerHitGroups = "", + string matchedQueries = "\"matched_queries\":[\"api_properties\"]," + ) => """ {"took":1,"timed_out":false,"_shards":{"total":1,"successful":1,"failed":0},"hits":{"total":{"value":1,"relation":"eq"},"hits":[ {"_index":"test","_id":"search","_score":1,__MATCHED__"_source":{"title":"Search","search_title":"Search","path":"/search"}, From 446b68b0487f475c4f2b160123cdf62adbd6f321 Mon Sep 17 00:00:00 2001 From: Jan Calanog <reakaleek@users.noreply.github.com> Date: Tue, 3 Nov 2026 14:16:38 +0100 Subject: [PATCH 22/23] Key listing identity on the description markdown, not its HTML The page and the index build the same property tree with different markdown renderers, and listing identity hashed the rendered HTML, so the two could disagree on which listings to share: `*Code it*` and `_Code it_` are one listing on the page and two in the index, leaving index entries whose anchors the page never renders. Identity now keys on the markdown both builders have, and the index renders nothing. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --- .../Components/PropertyTree/ListingContent.cs | 4 +- .../Export/OpenApiDocumentExporter.cs | 4 +- .../SharedListingTests.cs | 44 +++++++++++++++++++ 3 files changed, 48 insertions(+), 4 deletions(-) diff --git a/src/Elastic.ApiExplorer/Components/PropertyTree/ListingContent.cs b/src/Elastic.ApiExplorer/Components/PropertyTree/ListingContent.cs index c3febf8e8f..5e7ceeda69 100644 --- a/src/Elastic.ApiExplorer/Components/PropertyTree/ListingContent.cs +++ b/src/Elastic.ApiExplorer/Components/PropertyTree/ListingContent.cs @@ -42,7 +42,7 @@ private static void Append(StringBuilder text, ApiPropertyChildren children, Pag .Append('|') .Append(variant.DiscriminatorLabel) .Append('|') - .Append(variant.DescriptionHtml.Value) + .Append(variant.DescriptionMarkdown) .Append('|') .Append(variant.ShowProperties); Append(text, variant.Properties, shapes); @@ -81,7 +81,7 @@ private static void Append(StringBuilder text, ApiPropertyList? properties, Page .Append('|') .Append(property.ExternalDocs?.Url) .Append('|') - .Append(property.DescriptionHtml.Value) + .Append(property.DescriptionMarkdown) .Append('|') .AppendJoin(',', property.EnumValues) .Append('|') diff --git a/src/Elastic.ApiExplorer/Export/OpenApiDocumentExporter.cs b/src/Elastic.ApiExplorer/Export/OpenApiDocumentExporter.cs index 467036a371..3f7c3b0c6f 100644 --- a/src/Elastic.ApiExplorer/Export/OpenApiDocumentExporter.cs +++ b/src/Elastic.ApiExplorer/Export/OpenApiDocumentExporter.cs @@ -125,8 +125,8 @@ public IEnumerable<DocumentationDocument> ConvertToDocuments(OpenApiDocument ope openApiDocument, new PropertyDisplayOptions { - // Listing sharing keys on the rendered description, so a blank renderer would merge listings the page keeps apart. - RenderMarkdown = markdown => new HtmlString(markdown), + // Listing identity keys on the markdown and the index stores plain text, so nothing here needs the HTML. + RenderMarkdown = _ => HtmlString.Empty, ApiRootUrl = productUrl, VersionsConfiguration = versionsConfiguration } diff --git a/tests/Elastic.ApiExplorer.Tests/SharedListingTests.cs b/tests/Elastic.ApiExplorer.Tests/SharedListingTests.cs index 30ee4605a6..eeceaa457c 100644 --- a/tests/Elastic.ApiExplorer.Tests/SharedListingTests.cs +++ b/tests/Elastic.ApiExplorer.Tests/SharedListingTests.cs @@ -220,6 +220,50 @@ public async Task BuildPropertyList_UnionsDifferingInEnumValuesOrDeepFields_AreN Row("same").Repeats!.Name.Should().Be("first"); } + [Test] + public async Task BuildPropertyList_UnionsWhoseVariantDescriptionsDifferOnlyInMarkdown_AreNotShared() + { + var json = + """ + { + "openapi": "3.1.0", + "info": { "title": "t", "version": "1" }, + "paths": {}, + "components": { + "schemas": { + "Holder": { + "type": "object", + "properties": { + "first": { "oneOf": [ + { "type": "object", "description": "*Code it*", "properties": { "f0": { "type": "string" }, "f1": { "type": "string" }, "f2": { "type": "string" }, "f3": { "type": "string" }, "f4": { "type": "string" }, "f5": { "type": "string" }, "f6": { "type": "string" }, "f7": { "type": "string" }, "f8": { "type": "string" }, "f9": { "type": "string" } } }, + { "type": "object", "properties": { "other": { "type": "string" } } } ] }, + "second": { "oneOf": [ + { "type": "object", "description": "_Code it_", "properties": { "f0": { "type": "string" }, "f1": { "type": "string" }, "f2": { "type": "string" }, "f3": { "type": "string" }, "f4": { "type": "string" }, "f5": { "type": "string" }, "f6": { "type": "string" }, "f7": { "type": "string" }, "f8": { "type": "string" }, "f9": { "type": "string" } } }, + { "type": "object", "properties": { "other": { "type": "string" } } } ] }, + "third": { "oneOf": [ + { "type": "object", "description": "*Code it*", "properties": { "f0": { "type": "string" }, "f1": { "type": "string" }, "f2": { "type": "string" }, "f3": { "type": "string" }, "f4": { "type": "string" }, "f5": { "type": "string" }, "f6": { "type": "string" }, "f7": { "type": "string" }, "f8": { "type": "string" }, "f9": { "type": "string" } } }, + { "type": "object", "properties": { "other": { "type": "string" } } } ] } + } + } + } + } + } + """; + var document = await LoadSpecAsync(json); + + // Both spellings render alike; the index builds the same tree with a renderer of its own, so identity must not depend on one. + var builder = new ApiPropertyTreeBuilder( + document, + new PropertyDisplayOptions { RenderMarkdown = _ => new HtmlString("<p><em>Code it</em></p>"), ApiRootUrl = "/api/doc/fixture" } + ); + var list = builder.BuildPropertyList(document.Components!.Schemas!["Holder"], new PropertyTreeScope { Prefix = "" })!; + + ApiProperty Row(string name) => list.Items.Single(p => p.Name == name); + + Row("second").Repeats.Should().BeNull("its variant description is spelled differently, however it renders"); + Row("third").Repeats!.Name.Should().Be("first"); + } + [Test] public async Task BuildPropertyList_CopyWhoseNestedFieldsWereLinked_StillSharesTheWholeListing() { From 23bdadff551837430a30438926942c3d8c6688fe Mon Sep 17 00:00:00 2001 From: Jan Calanog <reakaleek@users.noreply.github.com> Date: Tue, 3 Nov 2026 19:04:32 +0100 Subject: [PATCH 23/23] Decide the endpoint requirement from the query, not the surviving readings Whether a reading must match its endpoint was taken from how many readings were left, so once the docs-wide filter dropped the plain reading of `bulk track_total_hits`, the one that remained had its endpoint demoted to a lift and admitted every operation with the field. The parse now records that two plain words require their endpoints, and the filter keeps that. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --- .../Query/SearchQueryBuilder.cs | 42 +++++++++++-------- .../ApiPropertySearchTests.cs | 23 ++++++++++ 2 files changed, 48 insertions(+), 17 deletions(-) diff --git a/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs b/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs index cfa9342568..c967c3f0e3 100644 --- a/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs +++ b/src/services/search/Elastic.Documentation.Search/Query/SearchQueryBuilder.cs @@ -54,19 +54,16 @@ public static bool IsApiPropertyHits(string innerHitsName) => /// <summary>The nested field query for the query's first reading, see <see cref="ParseApiPropertyQuery"/>.</summary> public static Query? BuildApiPropertyQuery(string searchQuery, string? typeFilter) => - ParseApiPropertyQuery(searchQuery, typeFilter) is [var first, ..] + ParseApiPropertyQuery(searchQuery, typeFilter).Readings is [var first, ..] ? BuildNestedPropertyQuery(first.Property, ApiPropertyHits, allowPrefix: typeFilter == "api") : null; public static Query ApplyApiPropertyQuery(Query query, string searchQuery, string? typeFilter) { - var readings = ParseApiPropertyQuery(searchQuery, typeFilter); - // With one reading the endpoint only lifts the operation. With two, the index decides which reading holds, - // so each requires its endpoint: a bare word that names no endpoint, such as `_knn`, matches nothing. - var branches = readings - .Select( - (r, i) => BuildReadingQuery(r, InnerHitsName(i), endpointRequired: readings.Count > 1, allowPrefix: typeFilter == "api") - ) + var parsed = ParseApiPropertyQuery(searchQuery, typeFilter); + var branches = parsed + .Readings + .Select((r, i) => BuildReadingQuery(r, InnerHitsName(i), parsed.EndpointRequired, allowPrefix: typeFilter == "api")) .OfType<Query>() .ToList(); if (branches.Count == 0) @@ -119,29 +116,40 @@ bool allowPrefix /// last word that is neither; on its own, `get` or `options` may name a field. Two plain words are ambiguous, so /// both orders are returned, the last word as the field first. /// </summary> - private static IReadOnlyList<(string Operation, string Property)> ParseApiPropertyQuery(string searchQuery, string? typeFilter) + private static ApiPropertyReadings ParseApiPropertyQuery(string searchQuery, string? typeFilter) { var input = searchQuery.Trim(); if (input.Length == 0 || typeFilter is not (null or "" or "all" or "api")) - return []; - var readings = ParseReadings(input.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)); + return ApiPropertyReadings.None; + var parsed = ParseReadings(input.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)); // The docs-wide search only tries a field word that looks like an identifier; a plain word would lift every - // API operation that happens to have a field of that name above the pages about it. - return typeFilter == "api" ? readings : readings.Where(r => r.Property.Contains('.') || r.Property.Contains('_')).ToArray(); + // API operation that happens to have a field of that name above the pages about it. Dropping a reading + // leaves the others as demanding as the query made them. + return typeFilter == "api" + ? parsed + : parsed with { Readings = parsed.Readings.Where(r => r.Property.Contains('.') || r.Property.Contains('_')).ToArray() }; } - private static IReadOnlyList<(string Operation, string Property)> ParseReadings(string[] words) + private static ApiPropertyReadings ParseReadings(string[] words) { var endpointWords = words.Select( (w, i) => w.StartsWith('/') || (HttpMethods.Contains(w) && i + 1 < words.Length && words[i + 1].StartsWith('/')) ).ToArray(); + // With one reading the endpoint only lifts the operation. With two, the index decides which reading holds, + // so each requires its endpoint: a bare word that names no endpoint, such as `_knn`, matches nothing. if (!endpointWords.Any(e => e) && words.Length == 2) - return [(words[0], words[1]), (words[1], words[0])]; + return new ApiPropertyReadings([(words[0], words[1]), (words[1], words[0])], EndpointRequired: true); var field = Array.LastIndexOf(endpointWords, false); if (field < 0) - return []; - return [(string.Join(' ', words.Where((_, i) => i != field)), words[field])]; + return ApiPropertyReadings.None; + return new ApiPropertyReadings([(string.Join(' ', words.Where((_, i) => i != field)), words[field])], EndpointRequired: false); + } + + /// <summary>The readings of a query, and whether each must match its endpoint rather than only be lifted by it.</summary> + private sealed record ApiPropertyReadings(IReadOnlyList<(string Operation, string Property)> Readings, bool EndpointRequired) + { + public static readonly ApiPropertyReadings None = new([], EndpointRequired: false); } private static Query BuildNestedPropertyQuery(string property, string innerHitsName, bool allowPrefix) => diff --git a/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs b/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs index 107143327e..1c46d4fc34 100644 --- a/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs +++ b/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs @@ -156,6 +156,29 @@ public void ApplyApiPropertyQuery_SingleReading_IsNamedAfterItsInnerHits(string .Be("api_properties"); } + [Test] + public void ApplyApiPropertyQuery_TwoPlainWordsDocsWide_KeepsTheEndpointRequiredForTheSurvivingReading() + { + using var json = JsonDocument.Parse( + Client.RequestResponseSerializer.SerializeToString( + SearchQueryBuilder.ApplyApiPropertyQuery( + new Elastic.Clients.Elasticsearch.QueryDsl.MatchNoneQuery(), + "bulk track_total_hits", + null + ) + ) + ); + var reading = json.RootElement.GetProperty("bool").GetProperty("should")[1].GetProperty("bool"); + var must = reading.GetProperty("must"); + must.GetArrayLength().Should().Be(2); + must[0].GetProperty("nested").GetProperty("query").GetRawText().Should().Contain("\"value\":\"track_total_hits\""); + must[1].GetRawText().Should().Contain("_bulk"); + reading + .TryGetProperty("should", out _) + .Should() + .BeFalse("the plain word names no field docs-wide, and the reading left must still hold its endpoint"); + } + [Test] [Arguments("_search knn")] [Arguments("search knn")]