Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
81c2d5f
Add API property search with direct links to matching fields
reakaleek Oct 24, 2026
34b7d57
Merge branch 'main' into index-api-attributes-sear-a6c56a6b
akira28 Oct 27, 2026
f07d78b
Merge branch 'main' into index-api-attributes-sear-a6c56a6b
akira28 Oct 27, 2026
07188e9
Merge remote-tracking branch 'origin/main' into index-api-attributes-…
reakaleek Nov 3, 2026
8fe995a
Move the API property search tests to Vitest
reakaleek Nov 3, 2026
717693e
Name the Enter action after its destination in API search
reakaleek Nov 3, 2026
6940c51
Keep the footer's Enter hint static as "Go to page"
reakaleek Nov 3, 2026
3486146
Align the property row's Enter badge with the operation row's
reakaleek Nov 3, 2026
486e2ab
Pin property search behaviours before simplifying
reakaleek Nov 3, 2026
8255e41
Simplify property search without changing what it does
reakaleek Nov 3, 2026
9d9630d
Merge remote-tracking branch 'origin/main' into index-api-attributes-…
reakaleek Nov 3, 2026
58a9630
Show the primary route of a path hit in API search results
reakaleek Nov 3, 2026
e596b46
Show the route a query names in full over the primary route
reakaleek Nov 3, 2026
9f0a77f
Read a combined API query in either word order
reakaleek Nov 3, 2026
e625b47
Let the index decide which word of a two-word API query is the field
reakaleek Nov 3, 2026
4544644
Highlight the field word of a query in either order on property rows
reakaleek Nov 3, 2026
fc143a9
Report a clicked result's rank, not its keyboard row, in telemetry
reakaleek Nov 3, 2026
b5e5828
Never let a query word match a path placeholder in the route line
reakaleek Nov 3, 2026
a215f39
Treat an HTTP method word as an endpoint only before a path
reakaleek Nov 3, 2026
6d8d93c
Keep field matching out of the way of pages in the docs-wide search
reakaleek Nov 3, 2026
014bd99
Match the literal endpoint as well as its underscore alias
reakaleek Nov 3, 2026
79e01fa
Keep only the inner hits of the reading a document matched
reakaleek Nov 3, 2026
467abf9
Index every listing the operation page keeps apart
reakaleek Nov 3, 2026
915d230
Try a docs-wide field word only when it looks like an identifier
reakaleek Nov 3, 2026
0e03da2
Keep no field rows on a hit that matched no reading
reakaleek Nov 3, 2026
446b68b
Key listing identity on the description markdown, not its HTML
reakaleek Nov 3, 2026
23bdadf
Decide the endpoint requirement from the query, not the surviving rea…
reakaleek Nov 3, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/data/openapi/api-explorer.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
:::
Expand Down
Original file line number Diff line number Diff line change
@@ -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
{
/// <param name="plainDescriptions">Plain text per description markdown, shared across a spec: shared schemas repeat the same text on every operation.</param>
public static IEnumerable<ApiPropertyEntry> Entries(
IEnumerable<ApiProperty> properties,
string location,
Dictionary<string, string> 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<string, string> plainDescriptions)
{
if (!plainDescriptions.TryGetValue(markdown, out var text))
plainDescriptions[markdown] = text = ApiMarkdown.StripHtml(ApiSeoDescription.ToPlainText(markdown));
return text;
}

/// <summary>Every property in page order: each property, then its nested, dictionary and variant children.</summary>
public static IEnumerable<ApiProperty> 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<ApiProperty> Flatten(ApiUnionVariants? variants) =>
variants?.Variants.Where(v => v.ShowProperties && v.Properties is not null).SelectMany(v => Flatten(v.Properties)) ?? [];
}
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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('|')
Expand Down
31 changes: 31 additions & 0 deletions src/Elastic.ApiExplorer/Export/OpenApiDocumentExporter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;

Expand Down Expand Up @@ -66,6 +68,7 @@ public IEnumerable<DocumentationDocument> ConvertToDocuments(OpenApiDocument ope
// All API products currently version against Stack
var currentStack = versionsConfiguration.GetVersioningSystem(VersioningSystemId.Stack).Current;

var plainDescriptions = new Dictionary<string, string>();
foreach (var path in openApiDocument.Paths)
{
if (path.Value.Operations == null)
Expand Down Expand Up @@ -117,6 +120,23 @@ public IEnumerable<DocumentationDocument> 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,
Comment thread
infra-vault-gh-plugin-prod[bot] marked this conversation as resolved.
Resolved
VersionsConfiguration = versionsConfiguration
}
);
var endpoint = OperationEndpoint.Build(apiOperation, operation.Value.Description, []);
var trees = OperationPageModel.BuildPropertyTrees(
apiOperation,
new SchemaAnalyzer(openApiDocument),
new ParameterRowSource(builder, null, endpoint)
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Severity: P3 (Low)

Pass the operation's supplemental documentation into property indexing instead of always supplying null. Rendering applies parameter and request-body description overrides, but these new search rows always retain the original spec descriptions, or remain blank when only the supplemental file documents the field. Editing an override also leaves the indexed property metadata unchanged, so search continues showing text that no longer matches the destination row.

Generated by Libra. React with 👍 or 👎 to give feedback on this comment.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is substantial enough to track separately. Created #4662 as a follow-up. Not blocking this PR.


// Extract tags as headings
var headings = operation.Value.Tags?.Select(t => t.Name).Where(n => !string.IsNullOrEmpty(n)).OfType<string>().ToArray()
Expand All @@ -143,6 +163,17 @@ public IEnumerable<DocumentationDocument> ConvertToDocuments(OpenApiDocument ope
],
Api = new ApiOperationMetadata
{
Properties = trees.IndexEntries(plainDescriptions),
Routes = endpoint
.Rows
.Select(
Comment on lines +167 to +169

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Severity: P2 (Medium)

Populate Routes from the merged page endpoint rather than the individual spec operation. This endpoint is built with an empty sibling list, but navigation can collapse interchangeable operations onto one page. For a GET/POST /_search and /{index}/_search family without a description-level route listing, each indexed hit therefore carries only its own route and method, while the destination page leads with POST /{index}/_search and lists both routes. Search can consequently show a different primary route or omit a matching alternate route entirely.

Generated by Libra. React with 👍 or 👎 to give feedback on this comment.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is substantial enough to track separately. Created #4663 as a follow-up. Not blocking this PR.

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,
Expand Down
Original file line number Diff line number Diff line change
@@ -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<ApiMediaContent> Request,
IReadOnlyList<ApiResponse> Responses
)
{
public ApiPropertyEntry[] IndexEntries(Dictionary<string, string> plainDescriptions)
{
IEnumerable<ApiPropertyEntry> Entries(IEnumerable<ApiProperty> 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<ApiProperty> 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));
}
}
24 changes: 6 additions & 18 deletions src/Elastic.ApiExplorer/Operations/OperationPageModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand All @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<BuildContext, DocumentationSet> _apiDocsets = new(ReferenceEqualityComparer.Instance);

/// <summary>
/// Assigns hash, last updated, and batch index date to a documentation document.
/// </summary>
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);

/// <summary>The change-detection hash. Everything the index stores for a page takes part, so a metadata-only edit still syncs.</summary>
internal static string DocumentHash(DocumentationDocument doc, string semanticHash, string lexicalHash, string synonymsHash) =>
HashedBulkUpdate.CreateHash(
semanticHash,
lexicalHash,
doc.Path,
Expand All @@ -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;
}

/// <summary>Computes and assigns the whitespace-normalized content hash for change detection.</summary>
private static void AssignContentHash(DocumentationDocument doc) =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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");
Expand Down Expand Up @@ -227,6 +229,28 @@ private void ConfigureChannelOptions(string label, IngestChannelOptions<Document
};
}

private async Task UpdateApiPropertyMapping(Cancel ctx)
{
var target = _semanticTypeContext.ResolveReadTarget();
var exists = await _transport.HeadAsync(target, ctx).ConfigureAwait(false);
if (exists.ApiCallDetails.HttpStatusCode == 404)
return;
if (!exists.ApiCallDetails.HasSuccessfulStatusCode)
throw new InvalidOperationException($"Could not check semantic index '{target}': {exists}");

// The whole api object: Elasticsearch accepts fields that already exist unchanged and adds the new ones.
var mapping = JsonNode.Parse(_semanticTypeContext.GetMappingsJson())!;
var api = mapping["properties"]!["api"]!.DeepClone();
var update = new JsonObject { ["properties"] = new JsonObject { ["api"] = api } };
var response = await _operations.WithRetryAsync(
() => _transport.PutAsync<StringResponse>($"{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}");
}

/// <inheritdoc />
public async ValueTask StartAsync(Cancel ctx = default)
{
Expand Down
6 changes: 1 addition & 5 deletions src/Elastic.Documentation.Site/Assets/api-docs.css
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
13 changes: 6 additions & 7 deletions src/Elastic.Documentation.Site/Assets/api-docs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<HTMLElement, () => void>()

Expand Down Expand Up @@ -297,6 +297,7 @@ function flashTarget(target: HTMLElement): void {
function onHashChange(): void {
revealHashTarget()
const target = hashTarget()
initializedHashTarget = target
if (target) flashTarget(target)
}

Expand Down Expand Up @@ -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
}
Loading
Loading