diff --git a/docs/data/openapi/api-explorer.md b/docs/data/openapi/api-explorer.md index a5acd38017..bbea81ef0c 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. 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. + +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..1fcb716395 --- /dev/null +++ b/src/Elastic.ApiExplorer/Components/PropertyTree/ApiPropertyIndex.cs @@ -0,0 +1,49 @@ +// 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 +{ + /// 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 + { + Name = property.Name, + Path = string.IsNullOrEmpty(property.JsonPath) ? property.Name : property.JsonPath, + Type = property.Type.Text, + Location = location, + Anchor = property.AnchorId, + Description = PlainText(property.DescriptionMarkdown ?? "", plainDescriptions) + } + ); + + private static string PlainText(string markdown, Dictionary plainDescriptions) + { + 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)) ?? []; +} 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 01da75bd9f..3f7c3b0c6f 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; @@ -66,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) @@ -117,6 +120,23 @@ 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 + { + // 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 + } + ); + var endpoint = OperationEndpoint.Build(apiOperation, operation.Value.Description, []); + var trees = OperationPageModel.BuildPropertyTrees( + apiOperation, + new SchemaAnalyzer(openApiDocument), + new ParameterRowSource(builder, null, endpoint) + ); // Extract tags as headings var headings = operation.Value.Tags?.Select(t => t.Name).Where(n => !string.IsNullOrEmpty(n)).OfType().ToArray() @@ -143,6 +163,17 @@ 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.ApiExplorer/Operations/OperationPageModel.Properties.cs b/src/Elastic.ApiExplorer/Operations/OperationPageModel.Properties.cs new file mode 100644 index 0000000000..2dbdebe28a --- /dev/null +++ b/src/Elastic.ApiExplorer/Operations/OperationPageModel.Properties.cs @@ -0,0 +1,60 @@ +// 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(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) => + ApiPropertyIndex.Flatten(content.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 578c261ee6..7d2a75e68f 100644 --- a/src/Elastic.ApiExplorer/Operations/OperationPageModel.cs +++ b/src/Elastic.ApiExplorer/Operations/OperationPageModel.cs @@ -182,19 +182,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 { @@ -206,13 +194,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 1ffef3bac8..9328a78544 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; @@ -35,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, @@ -54,12 +53,13 @@ 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}") ?? []), - string.Join(",", doc.Links ?? []) + string.Join(",", doc.Links ?? []), + 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.Indexing/Exporters/Elasticsearch/ElasticsearchMarkdownExporter.cs b/src/Elastic.Documentation.Indexing/Exporters/Elasticsearch/ElasticsearchMarkdownExporter.cs index 1852c946ca..4a24a81015 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,28 @@ 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.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/api-docs.ts b/src/Elastic.Documentation.Site/Assets/api-docs.ts index 212b2d3b32..57c8ad0aeb 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) } @@ -711,10 +712,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 ac7dc05686..7d7a459e14 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 @@ -119,6 +119,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() vi.advanceTimersByTime(1000) 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 dc4986e1e4..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,7 +351,7 @@ const Title = ({ text }: { text: string }) => { margin-bottom: calc(${euiTheme.size.xs} / 2); mark { - background-color: ${euiTheme.colors.backgroundLightPrimary}; + background-color: var(--search-highlight-tint); font-weight: ${euiTheme.font.weight.bold}; color: ${euiTheme.colors.textParagraph}; } @@ -376,7 +376,7 @@ const Description = ({ text }: { text: string }) => { text-overflow: ellipsis; mark { - background-color: ${euiTheme.colors.backgroundLightPrimary}; + background-color: var(--search-highlight-tint); font-weight: ${euiTheme.font.weight.bold}; } `} 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..bf4f43cd3c --- /dev/null +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/JumpToIndicator.tsx @@ -0,0 +1,26 @@ +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 2f4aa47df4..10c65e2e7b 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,11 @@ import { availableIcons } from '../../eui-icons-cache' import { SearchInput } from './SearchInput' import { SearchResultsList } from './SearchResultsList' +import { + GO_TO_LABELS, + groupSearchResults, + navigableRowCount, +} from './apiPropertyResults' import { useSearchTerm, useSearchActions, @@ -22,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 @@ -47,7 +52,10 @@ export const NavigationSearch = ({ const { trackOpened, trackClosed } = useNavigationSearchTelemetry(typeFilter) - const results = data?.results ?? [] + const groups = useMemo( + () => groupSearchResults(data?.results ?? []), + [data] + ) const hasContent = !!searchTerm.trim() const isSearching = isLoading || isFetching @@ -56,7 +64,7 @@ export const NavigationSearch = ({ trackClosed({ reason: 'navigate', query: searchTerm, - hadResults: results.length > 0, + hadResults: groups.length > 0, hadSelection: selectedIndex >= 0, }) } @@ -67,7 +75,7 @@ export const NavigationSearch = ({ handleInputKeyDown, handleMouseMove, } = useNavigationSearchKeyboardNavigation({ - resultsCount: results.length, + resultsCount: navigableRowCount(groups), isLoading: isSearching, onClose: () => setIsPopoverOpen(false), onNavigate: handleResultClick, @@ -91,7 +99,7 @@ export const NavigationSearch = ({ trackClosed({ reason: 'escape', query: searchTerm, - hadResults: results.length > 0, + hadResults: groups.length > 0, hadSelection: selectedIndex >= 0, }) setSearchTerm('') @@ -119,7 +127,7 @@ export const NavigationSearch = ({ trackClosed({ reason: 'blur', query: searchTerm, - hadResults: results.length > 0, + hadResults: groups.length > 0, hadSelection: selectedIndex >= 0, }) } @@ -192,12 +200,15 @@ export const NavigationSearch = ({ > {hasContent && (
- +
)} @@ -205,48 +216,14 @@ 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' }, + { keys: ['returnKey'], label: GO_TO_LABELS.page }, { keys: ['sortUp', 'sortDown'], label: 'Navigate' }, { keys: ['Esc'], label: 'Close' }, ] -interface SearchDropdownContentProps { - isKeyboardNavigating: React.MutableRefObject - onMouseMove: () => void - onResultClick: () => void - typeFilter: TypeFilter -} - -const SearchDropdownContent = ({ - isKeyboardNavigating, - onMouseMove, - onResultClick, - typeFilter, -}: SearchDropdownContentProps) => { - return ( - <> - - - - ) -} - -const SearchDropdownFooter = ({ typeFilter }: { typeFilter: TypeFilter }) => { +const SearchDropdownFooter = () => { const { euiTheme } = useEuiTheme() const isMobile = useIsWithinMaxBreakpoint('s') - const shortcuts = - typeFilter === 'api' ? API_KEYBOARD_SHORTCUTS : KEYBOARD_SHORTCUTS if (isMobile) { return null @@ -269,7 +246,7 @@ const SearchDropdownFooter = ({ typeFilter }: { typeFilter: TypeFilter }) => { gap: ${euiTheme.size.base}; `} > - {shortcuts.map((shortcut, index) => ( + {KEYBOARD_SHORTCUTS.map((shortcut, index) => ( { }) }) + 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 = vi.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('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 = vi.fn((event: Event) => event.preventDefault()) + child.addEventListener('click', clicked) + await userEvent.click(input) + expect(input).toHaveFocus() + expect(navigationSearchStore.getState().selectedIndex).toBe(0) + 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.getByText('Go to page')).toBeInTheDocument() + await userEvent.keyboard('{Enter}') + expect(clicked).toHaveBeenCalledTimes(1) + expect(logInfo).toHaveBeenCalledWith( + 'navigation_search_result_clicked', + expect.objectContaining({ + [ATTR_NAVIGATION_SEARCH_RESULT_ANCHOR]: 'req-track_total_hits', + 'navigation_search.result.position': 0, + }) + ) + }) + 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 df6bc11265..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,6 +3,7 @@ import { renderWithProviders } from '../../test-utils/render' import { resetCooldownStore } from '../../test-utils/stores' import { NavigationSearch } from './NavigationSearch' import { SearchResultsList } from './SearchResultsList' +import { groupSearchResults } from './apiPropertyResults' import { navigationSearchStore } from './navigationSearch.store' import * as queryHook from './useNavigationSearchQuery' import { screen, waitFor } from '@testing-library/react' @@ -23,7 +24,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', @@ -31,7 +35,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, @@ -181,6 +188,8 @@ describe('Navigation Search Telemetry Integration', () => { describe('Navigation Search Result Click Tracking', () => { // Shared props for SearchResultsList - reduces duplication const createResultsListProps = () => ({ + results: groupSearchResults(mockSearchResults.results), + isLoading: false, isKeyboardNavigating: { current: false }, onMouseMove: vi.fn(), onResultClick: 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 new file mode 100644 index 0000000000..24bb7caebd --- /dev/null +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.test.tsx @@ -0,0 +1,53 @@ +import { renderWithProviders } from '../../test-utils/render' +import { PropertyResultRow } from './PropertyResultRow' +import { screen } from '@testing-library/react' + +const renderRow = (searchTerm: string, path: string) => + renderWithProviders( + + ) + +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']], + ['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') + 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 new file mode 100644 index 0000000000..114fcd38de --- /dev/null +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/PropertyResultRow.tsx @@ -0,0 +1,154 @@ +import { useHtmxLink } from '../shared/htmx/useHtmxLink' +import { JumpToIndicator } from './JumpToIndicator' +import { + GO_TO_LABELS, + fieldSearchTerms, + type ApiPropertyResult, +} from './apiPropertyResults' +import { + EuiHighlight, + useEuiTheme, + useIsWithinMaxBreakpoint, +} 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 isMobile = useIsWithinMaxBreakpoint('s') + const { ref, href } = useHtmxLink(property.url) + const leafOffset = property.path.lastIndexOf('.') + 1 + const propertySearch = fieldSearchTerms(searchTerm) + const highlight = (text: string) => ( + + {text} + + ) + 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; + } + .jump-to-indicator { + order: 2; + margin-left: ${euiTheme.size.s}; + } + &:hover:not([data-keyboard-navigating='true']) { + background: ${euiTheme.colors.backgroundBaseHighlighted}; + } + &:focus-visible { + outline: 2px solid ${euiTheme.colors.primary}; + outline-offset: -2px; + } + `} + > + + {highlight(property.path.slice(0, leafOffset))} + {highlight(property.path.slice(leafOffset))} + + {property.type} + + {property.location} + + {property.description} + {!isMobile && } + + ) +} 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 3858ac91dd..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 @@ -1,8 +1,19 @@ +import { renderWithProviders } from '../../test-utils/render' import { + SearchResultsList, emptyStateCopy, formatApiProductCrumb, navigationSearchBreadcrumbs, } from './SearchResultsList' +import { groupSearchResults, type ResultGroup } from './apiPropertyResults' +import { navigationSearchStore } from './navigationSearch.store' +import type { SearchResultItem, TypeFilter } 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,169 @@ 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 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() + const { container } = renderWithProviders( + + ) + return { onMouseMove, container } +} + +describe('property rows', () => { + beforeEach(() => { + 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('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, + 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]), + 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', { + 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({ isKeyboardNavigating: 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/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.tsx b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.tsx index d609ea78c6..a86ef0a45e 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.tsx +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.tsx @@ -1,20 +1,23 @@ 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' 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, - EuiIcon, EuiLoadingSpinner, useEuiTheme, useEuiOverflowScroll, @@ -65,6 +68,8 @@ export const emptyStateCopy = (typeFilter: TypeFilter) => : "We couldn't find a page that matches your search" export interface SearchResultsListProps { + results: ResultGroup[] + isLoading: boolean isKeyboardNavigating: MutableRefObject onMouseMove: () => void onResultClick: () => void @@ -72,6 +77,8 @@ export interface SearchResultsListProps { } export const SearchResultsList = ({ + results, + isLoading, isKeyboardNavigating, onMouseMove, onResultClick, @@ -80,13 +87,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(() => { @@ -144,30 +149,69 @@ export const SearchResultsList = ({ } } - const handleResultClick = (result: SearchResultItem, index: number) => { + const handleResultClick = ( + result: SearchResultItem, + rank: number, + property?: ApiPropertyResult + ) => { trackResultClicked({ query: searchTerm, - position: index, - url: result.url, + position: rank, + url: property?.url ?? result.url, score: result.score, + anchor: property?.anchor, }) onResultClick() } return (
- {results.map((result, index) => ( - ( +
handleMouseEnter(index)} - onMouseMove={() => handleItemMouseMove(index)} - onClick={() => handleResultClick(result, index)} - typeFilter={typeFilter} - /> + css={css` + margin: ${euiTheme.size.s}; + border: 1px solid ${euiTheme.colors.borderBaseSubdued}; + border-radius: ${euiTheme.size.s}; + overflow: hidden; + `} + > + handleMouseEnter(index)} + onMouseMove={() => handleItemMouseMove(index)} + onClick={() => handleResultClick(result, rank)} + typeFilter={typeFilter} + searchTerm={searchTerm} + /> + {properties.map( + ({ property, index: propertyIndex, showLocation }) => ( + + handleMouseEnter(propertyIndex) + } + onMouseMove={() => + handleItemMouseMove(propertyIndex) + } + onClick={() => + handleResultClick(result, rank, property) + } + /> + ) + )} +
))}
) @@ -182,6 +226,7 @@ interface SearchResultRowProps { onMouseMove: () => void onClick: () => void typeFilter: TypeFilter + searchTerm: string } const SearchResultRow = ({ @@ -193,10 +238,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( @@ -252,10 +299,6 @@ const SearchResultRow = ({ text-decoration: underline; } } - - .jump-to-indicator { - visibility: visible; - } } &[data-selected='true'] { @@ -268,10 +311,6 @@ const SearchResultRow = ({ text-decoration: underline; } } - - .jump-to-indicator { - visibility: visible; - } } `} > @@ -284,13 +323,21 @@ const SearchResultRow = ({ > - {result.description && ( - <Description text={result.description} /> + {route ? ( + <RouteLine route={route} tokens={tokens} /> + ) : ( + result.description && ( + <Description text={result.description} /> + ) )} </div> {!isMobile && ( <JumpToIndicator - label={typeFilter === 'api' ? 'Jump to API' : 'Jump to'} + label={ + result.type === 'api' + ? GO_TO_LABELS.operation + : GO_TO_LABELS.page + } /> )} </a> @@ -382,7 +429,7 @@ const Title = ({ text }: { text: string }) => { margin-bottom: calc(${euiTheme.size.xs} / 2); mark { - background-color: ${euiTheme.colors.backgroundLightPrimary}; + background-color: var(--search-highlight-tint); font-weight: ${euiTheme.font.weight.bold}; color: ${euiTheme.colors.textParagraph}; } @@ -407,7 +454,7 @@ const Description = ({ text }: { text: string }) => { text-overflow: ellipsis; mark { - background-color: ${euiTheme.colors.backgroundLightPrimary}; + background-color: var(--search-highlight-tint); font-weight: ${euiTheme.font.weight.bold}; } `} @@ -416,23 +463,3 @@ const Description = ({ text }: { text: string }) => { </div> ) } - -const JumpToIndicator = ({ label }: { label: string }) => { - const { euiTheme } = useEuiTheme() - - return ( - <div - className="jump-to-indicator" - css={css` - flex-shrink: 0; - color: ${euiTheme.colors.textSubdued}; - margin-left: ${euiTheme.size.xxxxl}; - visibility: hidden; - `} - > - <EuiBadge color="hollow"> - {label} <EuiIcon type="returnKey" size="s" /> - </EuiBadge> - </div> - ) -} 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..a4ec915389 --- /dev/null +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.test.ts @@ -0,0 +1,116 @@ +import { + fieldSearchTerms, + groupSearchResults, + navigableRowCount, + primaryRoute, +} from './apiPropertyResults' +import type { SearchResultItem } from './useNavigationSearchQuery' + +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 search: 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 page: SearchResultItem = { + type: 'docs', + url: '/docs/elasticsearch', + title: 'Elasticsearch', + description: 'Learn about Elasticsearch', + score: 1, + parents: [], +} + +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(groups.map((group) => group.rank)).toEqual([0, 1]) + expect(navigableRowCount(groups)).toBe(5) +}) + +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('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) +}) + +const routes = [ + { path: '/{index}/_search', methods: ['POST', 'GET'] }, + { path: '/_search', methods: ['POST', 'GET'] }, + { path: '/_search/scroll', methods: ['POST', 'GET'] }, +] + +it.each([ + ['_search', ['_search'], '/_search'], + ['/_search', ['_search'], '/_search'], + ['GET /_search knn', ['_search', 'knn'], '/_search'], + ['search', ['search'], '/{index}/_search'], + ['index', ['index'], undefined], + ['in', ['in'], undefined], + ['scroll', ['scroll'], '/_search/scroll'], + ['knn', ['knn'], undefined], + ['get', ['get'], undefined], + ['GET /_search', ['_search'], '/_search'], + ['a', [], undefined], +])('picks the route for %s', (searchTerm, tokens, path) => { + const matched = primaryRoute(routes, searchTerm) + 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', []], + ['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 new file mode 100644 index 0000000000..f2e9125861 --- /dev/null +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/apiPropertyResults.ts @@ -0,0 +1,136 @@ +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<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', +]) + +/** 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 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) => { + const all = words(searchTerm) + return Array.from( + new Set( + 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 + * 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 all = words(searchTerm) + const tokens = all + .filter((_, i) => !isMethodBeforePath(all, i)) + .map(pathKey) + .filter((word) => word.length > 1) + const containing = routes.filter((route) => + tokens.some((token) => pathKey(route.path).includes(token)) + ) + return { + tokens, + route: + containing.find((route) => tokens.includes(pathKey(route.path))) ?? + containing[0], + } +} + +export const GO_TO_LABELS = { + page: 'Go to page', + operation: 'Go to operation', + property: 'Go to property', +} as const + +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 + /** Position among the results; what a click reports, for the operation and for each of its properties. */ + rank: number + properties: PropertyRow[] +} + +/** One box per result, with rows numbered in keyboard order: the operation, then its properties. */ +export const groupSearchResults = ( + results: SearchResultItem[] +): ResultGroup[] => { + let index = 0 + 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) => ({ + 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/useNavigationSearchQuery.ts b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/useNavigationSearchQuery.ts index d3ee170a06..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,6 +15,7 @@ import { isRateLimitError, } from '../shared/errorHandling' import { ApiError } from '../shared/errorHandling' +import { ApiPropertyResult, ApiRoute } from './apiPropertyResults' import { usePageNumber, useSearchTerm } from './navigationSearch.store' import { useIsNavigationSearchAwaitingNewInput, @@ -42,6 +43,8 @@ const SearchResultItem = z.object({ description: z.string(), 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/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/useNavigationSearchTelemetry.ts b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/useNavigationSearchTelemetry.ts index 37f951596e..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, @@ -33,6 +34,7 @@ export type NavigationMethod = 'keyboard' | 'mouse' export type NavigationDirection = 'up' | 'down' interface ResultClickParams { + anchor?: string query: string position: number url: string @@ -96,12 +98,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 + ? { [ATTR_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..065d9c28e2 100644 --- a/src/api/Elastic.Documentation.Api/SerializationContext.cs +++ b/src/api/Elastic.Documentation.Api/SerializationContext.cs @@ -26,6 +26,9 @@ public record OutputMessage(string Role, MessagePart[] Parts, string FinishReaso [JsonSerializable(typeof(PageFeedbackReason))] [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 8ddb038b7f..c293b3dae2 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,10 @@ namespace Elastic.Documentation.Search.Contract; [JsonSerializable(typeof(DocumentationDocument))] [JsonSerializable(typeof(AppliesToEntry))] [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 c247e85c62..36b7467289 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,15 @@ namespace Elastic.Documentation.Search.Contract; /// </summary> public record ApiOperationMetadata { + [Nested] + [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/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/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.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<DocumentationDocument> 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<TDocument> where TDocument : SearchDocumentBase public required string Description { get; init; } public float Score { get; init; } + public IReadOnlyList<ApiPropertyEntry> 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..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 = @@ -115,6 +121,7 @@ public async Task<AutocompleteResponse<TDocument>> 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<TDocument>( s => 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/Highlighting/SearchResultProcessor.cs b/src/services/search/Elastic.Documentation.Search/Highlighting/SearchResultProcessor.cs index 458a67deb4..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,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 System.Collections.Frozen; +using System.Text.Json; using Elastic.Clients.Elasticsearch.Core.Search; using Elastic.Documentation.Search.Contract; @@ -55,10 +57,43 @@ public static SearchResultItem<TDocument> ProcessHit<TDocument>( Document = doc, Title = title, Description = description, - Score = (float)(hit.Score ?? 0.0) + Score = (float)(hit.Score ?? 0.0), + Properties = MatchedProperties(hit) }; } + /// <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) + return []; + + // 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.Contains(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 + ) + .OfType<ApiPropertyEntry>() + .DistinctBy(p => p.Anchor) + .Take(3) + .ToArray(); + } + + /// <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, string aggregationName diff --git a/src/services/search/Elastic.Documentation.Search/INavigationSearchService.cs b/src/services/search/Elastic.Documentation.Search/INavigationSearchService.cs index bc18e57b31..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 @@ -47,6 +49,10 @@ 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; } @@ -54,3 +60,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..1c6b405f69 100644 --- a/src/services/search/Elastic.Documentation.Search/NavigationSearchService.cs +++ b/src/services/search/Elastic.Documentation.Search/NavigationSearchService.cs @@ -52,6 +52,22 @@ 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( + 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/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 43794aeed7..c967c3f0e3 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,20 @@ namespace Elastic.Documentation.Search; /// </summary> 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 + ); + private static readonly string[] ApiPropertySourceIncludes = [$"{QueryFieldNames.ApiProperties}.*"]; + /// <summary> /// Rank-feature and term boosts applied as <c>should</c> clauses on top of the base query. /// </summary> @@ -37,6 +52,165 @@ 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).Readings is [var first, ..] + ? BuildNestedPropertyQuery(first.Property, ApiPropertyHits, allowPrefix: typeFilter == "api") + : null; + + public static Query ApplyApiPropertyQuery(Query query, string searchQuery, string? typeFilter) + { + 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) + return query; + + var properties = branches.Count == 1 ? branches[0] : new BoolQuery { Should = branches, MinimumShouldMatch = 1 }; + return new BoolQuery { Should = [query, properties], MinimumShouldMatch = 1, Filter = [DocumentFilter] }; + } + + private static Query? BuildReadingQuery( + (string Operation, string Property) reading, + string innerHitsName, + bool endpointRequired, + bool allowPrefix + ) + { + var properties = BuildNestedPropertyQuery(reading.Property, innerHitsName, allowPrefix); + 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 new BoolQuery { Must = [properties], QueryName = innerHitsName }; + return endpointRequired + ? new BoolQuery { Must = [properties, endpoint], QueryName = innerHitsName } + : new BoolQuery { Must = [properties], Should = [endpoint], QueryName = innerHitsName }; + } + + /// <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 + /// 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 ApiPropertyReadings ParseApiPropertyQuery(string searchQuery, string? typeFilter) + { + var input = searchQuery.Trim(); + if (input.Length == 0 || typeFilter is not (null or "" or "all" or "api")) + 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. 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 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 new ApiPropertyReadings([(words[0], words[1]), (words[1], words[0])], EndpointRequired: true); + + var field = Array.LastIndexOf(endpointWords, false); + if (field < 0) + 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) => + new NestedQuery + { + Path = QueryFieldNames.ApiProperties, + IgnoreUnmapped = true, + ScoreMode = ChildScoreMode.Max, + Query = BuildPropertyMatchQuery(property, allowPrefix), + InnerHits = new InnerHits + { + Name = innerHitsName, + Size = 5, + Source = new SourceConfig(new SourceFilter { Includes = ApiPropertySourceIncludes }) + } + }; + + private static Query BuildPropertyMatchQuery(string input, bool allowPrefix) + { + var name = BuildPropertyNameQuery(input, allowPrefix); + 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)..], allowPrefix)], + Filter = + [ + new MatchBoolPrefixQuery { Field = QueryFieldNames.ApiPropertiesPathMatch, Query = input, Operator = Operator.And } + ] + } + ] + }; + } + + /// <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 + { + 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) { 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..cc018a213b --- /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<ApiExplorerFixture>(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** <em>name</em>."}}}, + "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(new Dictionary<string, string>()); + + 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.<string>.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, VersioningSystem> + { + [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<OperationNavigationItem>() + .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.ApiExplorer.Tests/OpenApiDocumentExporterTests.cs b/tests/Elastic.ApiExplorer.Tests/OpenApiDocumentExporterTests.cs index a82bad8af1..b4b1e70a24 100644 --- a/tests/Elastic.ApiExplorer.Tests/OpenApiDocumentExporterTests.cs +++ b/tests/Elastic.ApiExplorer.Tests/OpenApiDocumentExporterTests.cs @@ -270,6 +270,58 @@ 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() + { + 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.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() { diff --git a/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs b/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs new file mode 100644 index 0000000000..1c46d4fc34 --- /dev/null +++ b/tests/Elastic.Documentation.Api.Tests/ApiPropertySearchTests.cs @@ -0,0 +1,377 @@ +// 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("track_total", null)] + [Arguments("knn_field search", 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("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) + { + 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] + [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() + { + 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("GET /_search knn")] + [Arguments("knn /_search")] + [Arguments("knn GET /_search")] + public void ApplyApiPropertyQuery_MarkedEndpointAndField_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("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] + 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")] + [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].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 + .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 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() + { + 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\",\"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] + 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")] + [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")] + 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"); + + 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] + 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 result = SearchResultProcessor.ProcessHit( + ParseResponse(SearchResponseJson(innerHits)).Hits.Single(), + "a", + new Dictionary<string, string[]>() + ); + + 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, + 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"}, + "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("__MATCHED__", matchedQueries); + + 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<DocumentationDocument> 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<Elastic.Clients.Elasticsearch.SearchResponse<DocumentationDocument>>(stream); + } + + [Test] + public void ProcessHit_NestedPropertySource_ReturnsMatchingProperty() + { + var json = SearchResponseJson(InnerHit("req-track_total_hits", 5, "track_total_hits")); + + var result = SearchResultProcessor.ProcessHit(ParseResponse(json).Hits.Single(), "track_total", new Dictionary<string, string[]>()); + + result.Properties.Should().ContainSingle().Which.Anchor.Should().Be("req-track_total_hits"); + } +} 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 new file mode 100644 index 0000000000..55d0648edf --- /dev/null +++ b/tests/Elastic.Documentation.Api.Tests/NavigationSearchServiceTests.cs @@ -0,0 +1,92 @@ +// 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<ISearchService<DocumentationDocument>>(); + var document = new DocumentationDocument + { + Title = "Search", + SearchTitle = "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 + { + Name = "knn", + Path = "knn", + Type = "object", + Location = "request", + Anchor = "req-knn", + Description = "Approximate kNN" + }; + _ = A.CallTo( + () => inner.AutocompleteAsync(A<AutocompleteRequest>._, A<CancellationToken>._) + ).Returns(new AutocompleteResponse<DocumentationDocument> + { + Results = + [ + new SearchResultItem<DocumentationDocument> + { + 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<NavigationSearchService>.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"); + result + .Routes + .Select(r => (r.Path, string.Join(",", r.Methods))) + .Should() + .Equal(("/{index}/_search", "POST,GET"), ("/_search", "POST,GET")); + } +} 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")))); +}