Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
4 changes: 2 additions & 2 deletions docs/data/openapi/api-explorer.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ 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.
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. An operation also matches the words of its operation id and path, split on dots, hyphens, underscores and case changes, and the name of its group, so `ml flush`, `flush ML job` and `_ml _flush` all find `POST /_ml/anomaly_detectors/{job_id}/_flush`. 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.
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. Each result's breadcrumb ends with the operation's group, the same group the page shows.

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.

Expand Down
30 changes: 30 additions & 0 deletions src/Elastic.ApiExplorer/Export/ApiSearchWords.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// 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.RegularExpressions;

namespace Elastic.ApiExplorer.Export;

/// <summary>
/// The plain words of an operation id and its literal path segments, e.g. <c>ml-flush-job</c> and
/// <c>/_ml/anomaly_detectors/{job_id}/_flush</c> give <c>ml flush job anomaly detectors</c>.
/// The search analyzer keeps <c>_ - .</c> inside a token, so without these words <c>ml flush</c> never meets <c>_flush</c>.
/// </summary>
internal static partial class ApiSearchWords
{
[GeneratedRegex(@"[._\-]+|(?<=\p{Ll})(?=\p{Lu})")]
private static partial Regex WordBoundary();

internal static string[] Of(string operationId, string path) =>
[
.. path
.Split('/', StringSplitOptions.RemoveEmptyEntries)
.Where(segment => !segment.StartsWith('{'))
.Prepend(operationId)
.SelectMany(piece => WordBoundary().Split(piece))
.Where(word => word.Length > 0)
.Select(word => word.ToLowerInvariant())
.Distinct(StringComparer.Ordinal)
];
}
97 changes: 61 additions & 36 deletions src/Elastic.ApiExplorer/Export/OpenApiDocumentExporter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ public IEnumerable<DocumentationDocument> ConvertToDocuments(OpenApiDocument ope
var productUrl = ApiUrlBuilder.ProductRoot("/docs", product);
// All API products currently version against Stack
var currentStack = versionsConfiguration.GetVersioningSystem(VersioningSystemId.Stack).Current;
var tagMetadata = OpenApiExtensionReader.ParseTagMetadata(openApiDocument);

var plainDescriptions = new Dictionary<string, string>();
foreach (var path in openApiDocument.Paths)
Expand All @@ -92,7 +93,6 @@ public IEnumerable<DocumentationDocument> ConvertToDocuments(OpenApiDocument ope
var summary = operation.Value.Summary?.Trim();
var title = string.IsNullOrEmpty(summary) ? operationId : summary;
var method = operation.Key.ToString().ToUpperInvariant();
var searchTitle = BuildSearchTitle(title, productLabel, operationId, $"{method} {path.Key}");
var description = IndexedHitText(summary, operation.Value.Description, operationId);

// Build body content from operation details
Expand Down Expand Up @@ -138,47 +138,51 @@ public IEnumerable<DocumentationDocument> ConvertToDocuments(OpenApiDocument ope
new ParameterRowSource(builder, null, endpoint)
);

// Extract tags as headings
var headings = operation.Value.Tags?.Select(t => t.Name).Where(n => !string.IsNullOrEmpty(n)).OfType<string>().ToArray()
?? [];
var headings = operation.Value.Tags?.Select(OpenApiExtensionReader.TagName).OfType<string>().ToArray() ?? [];

// Infer product and repository metadata
var inference = documentInferrer?.InferForOpenApi(productId ?? product);

var groupParent = GroupParent(headings, tagMetadata, productUrl);
ParentDocument[] parents =
[
new ParentDocument { Title = "API", Path = "/docs/api" },
new ParentDocument { Title = productLabel, Path = productUrl }
];

var 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,
OperationId = operationId,
Deprecated = operation.Value.Deprecated
};

yield return new DocumentationDocument
{
ContentType = "api",
Path = url,
Title = title,
SearchTitle = searchTitle,
SearchTitle = BuildSearchTitle(title, productLabel, groupParent?.Title, api),
Description = description,
Body = body,
Headings = headings,
Links = [],
Applies = applies?.ToAppliesTo(),
Parents =
[
new ParentDocument { Title = "API", Path = "/docs/api" },
new ParentDocument { Title = productLabel, Path = productUrl }
],
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,
OperationId = operationId
},
Parents = groupParent is null ? parents : [.. parents, groupParent],
Api = api,
Product = inference?.Product?.Id,
RelatedProducts = inference?.RelatedProducts.Count > 0
? inference
Expand All @@ -191,23 +195,44 @@ public IEnumerable<DocumentationDocument> ConvertToDocuments(OpenApiDocument ope
}
}

/// <summary>
/// The breadcrumb entry for the operation's first tag, matching the group page the operation page links to;
/// null when untagged.
/// </summary>
private static ParentDocument? GroupParent(
string[] tags,
IReadOnlyDictionary<string, OpenApiTagMetadata> tagMetadata,
string productUrl
) =>
tags is [var tag, ..]
? new ParentDocument
{
Title = OpenApiExtensionReader.TagMetadataFor(tag, tagMetadata).DisplayName,
Path = $"{productUrl}/group/{ApiUrlBuilder.TagMoniker(tag)}"
}
: null;

/// <summary>
/// Display label for the product crumb, e.g. <c>elasticsearch</c> → <c>Elasticsearch API</c>.
/// </summary>
internal static string ProductApiLabel(string product) =>
$"{CultureInfo.InvariantCulture.TextInfo.ToTitleCase(product.Replace('-', ' '))} API";

/// <summary>
/// Search tokens users type for an operation: the product label, the raw operation id
/// (e.g. <c>_bulk</c>, <c>indices.get</c>), and the HTTP method plus path
/// (e.g. <c>PUT /_bulk</c>). Keep ids and paths verbatim — no case or punctuation
/// rewriting — because that is what people paste. The product label lives here rather
/// than in <c>Title</c>, so result rows do not repeat "Elasticsearch API" on every hit.
/// Search tokens users type for an operation: the title, the product label, the raw operation id
/// (e.g. <c>_bulk</c>, <c>indices.get</c>), the HTTP method plus path (e.g. <c>PUT /_bulk</c>),
/// the group, and the plain words of the id and path (<see cref="ApiSearchWords"/>). The raw id
/// and path stay verbatim because that is what people paste; the words serve people who type
/// <c>ml flush</c>. The product label lives here rather than in <c>Title</c>, so result rows do
/// not repeat "Elasticsearch API" on every hit.
/// </summary>
internal static string BuildSearchTitle(string title, string productLabel, string operationId, string methodAndPath)
internal static string BuildSearchTitle(string title, string productLabel, string? group, ApiOperationMetadata api)
{
var searchTitle = $"{title} - {productLabel} - {operationId} - {methodAndPath}";
return operationId.Contains('.', StringComparison.Ordinal) ? $"{searchTitle} - {operationId.Replace('.', ' ')}" : searchTitle;
var searchTitle = $"{title} - {productLabel} - {api.OperationId} - {api.Method} {api.Path}";
if (!string.IsNullOrWhiteSpace(group))
searchTitle += $" - {group}";
var words = ApiSearchWords.Of(api.OperationId, api.Path);
return words.Length == 0 ? searchTitle : $"{searchTitle} - {string.Join(' ', words)}";
}

/// <summary>
Expand Down
14 changes: 14 additions & 0 deletions src/Elastic.ApiExplorer/Model/OpenApiExtensionReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,20 @@ public sealed record OpenApiTagMetadata(string DisplayName, string Description,
/// </summary>
public static class OpenApiExtensionReader
{
/// <summary>
/// The tag an operation references, read from the reference id the way navigation does, so an operation
/// tagged with a name the document never declares still has one. Null when blank.
/// </summary>
public static string? TagName(OpenApiTagReference tag)
{
var name = tag.Reference?.Id ?? tag.Name;
return string.IsNullOrWhiteSpace(name) ? null : name;
}

/// <summary>The metadata of a tag as navigation shows it: the declared entry, else the capitalized name alone.</summary>
public static OpenApiTagMetadata TagMetadataFor(string tag, IReadOnlyDictionary<string, OpenApiTagMetadata> metadata) =>
metadata.TryGetValue(tag, out var meta) ? meta : new OpenApiTagMetadata(tag.CapitalizeFirstLetter(), string.Empty, null);

/// <summary>Reads a string-valued extension; null when absent or not a string.</summary>
public static string? TryGetString(IDictionary<string, IOpenApiExtension>? extensions, string key) =>
extensions?.TryGetValue(key, out var value) == true
Expand Down
5 changes: 2 additions & 3 deletions src/Elastic.ApiExplorer/Navigation/ApiNavigationBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public LandingNavigationItem CreateNavigation(
{
var op = pair.Operation;
var (ns, api) = OpenApiExtensionReader.GetNamespaceAndApiName(op.Value);
var tag = op.Value.Tags?.FirstOrDefault()?.Reference.Id;
var tag = op.Value.Tags?.FirstOrDefault() is { } firstTag ? OpenApiExtensionReader.TagName(firstTag) : null;
var tagClassification = ResolveTagClassification(tag, xTagGroups, orphanTagsLogged);

// Fall back to the operationId, then a deterministic route:method key; Guid.NewGuid() made grouping keys
Expand Down Expand Up @@ -103,8 +103,7 @@ public LandingNavigationItem CreateNavigation(
apis.Add(apiEndpoint);
}
var tagName = tagGroup.Key ?? "unknown";
if (!tagMetadataByName.TryGetValue(tagName, out var tagMeta))
tagMeta = new OpenApiTagMetadata(tagName.CapitalizeFirstLetter(), string.Empty, null);
var tagMeta = OpenApiExtensionReader.TagMetadataFor(tagName, tagMetadataByName);
if (!tagNameToUrlSegment.TryGetValue(tagName, out var urlSegment))
throw new InvalidOperationException($"Internal error: no URL segment for OpenAPI tag '{tagName}'.");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

using System.IO.Abstractions;
using Elastic.ApiExplorer.Infrastructure;
using Elastic.ApiExplorer.Model;
using Microsoft.OpenApi;

namespace Elastic.ApiExplorer.Supplemental;
Expand Down Expand Up @@ -131,8 +132,7 @@ OpenApiDocument document

foreach (var tagRef in operation.Tags)
{
var name = OperationTagName(tagRef);
if (!string.IsNullOrEmpty(name))
if (OpenApiExtensionReader.TagName(tagRef) is { } name)
_ = tags.Add(name);
}
}
Expand All @@ -141,9 +141,6 @@ OpenApiDocument document
return (operations, tags);
}

private static string? OperationTagName(OpenApiTagReference tagRef) =>
!string.IsNullOrEmpty(tagRef.Name) ? tagRef.Name : tagRef.Reference?.Id;

internal static (Dictionary<string, string> UniqueBySlug, IReadOnlyList<TagSlugCollision> Collisions) IndexTags(
IReadOnlyCollection<string> tagNames
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -187,9 +187,7 @@ public async ValueTask<bool> ExportAsync(MarkdownExportFileContext fileContext,
) // TODO: Confirm that 'header' data is correctly set for all HeadingBlock instances and that this extraction is reliable.
.Where(text => !string.IsNullOrEmpty(text))
.ToArray();
var summary = !string.IsNullOrEmpty(body)
? body[..Math.Min(body.Length, 400)] + " " + string.Join(" \n- ", headings)
: string.Empty;
var summary = BuildSummary(body, headings);

// this is temporary until https://github.com/elastic/docs-builder/pull/2070 lands
// this PR will add a service for us to resolve to a versioning scheme.
Expand Down Expand Up @@ -272,20 +270,7 @@ public async ValueTask<bool> FinishExportAsync(IDirectoryInfo outputFolder, Canc

// Plain-text, markup-stripped content — the single source of truth for search, AI
// enrichment input, and content hashing.
doc.Body = PlainTextExporter.ConvertToPlainText(document, _context);

var headings = document
.Descendants<HeadingBlock>()
.Select(
h => h.GetData("header") as string ?? string.Empty
) // TODO: Confirm that 'header' data is correctly set for all HeadingBlock instances and that this extraction is reliable.
.Where(text => !string.IsNullOrEmpty(text))
.ToArray();
var summary = !string.IsNullOrEmpty(doc.Body)
? doc.Body[..Math.Min(doc.Body.Length, 400)] + " " + string.Join(" \n- ", doc.Headings)
: string.Empty;
doc.Summary = summary;
doc.Headings = headings;
ApplyApiPlainText(doc, PlainTextExporter.ConvertToPlainText(document, _context));
CommonEnrichments(doc, null);
AssignContentHash(doc);
AssignDocumentMetadata(doc);
Expand All @@ -301,6 +286,19 @@ public async ValueTask<bool> FinishExportAsync(IDirectoryInfo outputFolder, Canc
return true;
}

/// <summary>
/// Keeps the tag names <see cref="OpenApiDocumentExporter"/> put in <c>Headings</c>. The generated body's
/// own headings are only the title and "Parameters", so they would say nothing about the operation.
/// </summary>
internal static void ApplyApiPlainText(DocumentationDocument doc, string plainTextBody)
{
doc.Body = plainTextBody;
doc.Summary = BuildSummary(plainTextBody, doc.Headings);
}

private static string BuildSummary(string body, IEnumerable<string> headings) =>
string.IsNullOrEmpty(body) ? string.Empty : body[..Math.Min(body.Length, 400)] + " " + string.Join(" \n- ", headings);

private async IAsyncEnumerable<DocumentationDocument> ExportApiDocuments(
OpenApiDocumentExporter exporter,
[EnumeratorCancellation] Cancel ctx
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,40 @@ describe('navigationSearchBreadcrumbs', () => {
).toEqual(['API', 'Kibana API'])
})

it('keeps the group crumb after the product as written', () => {
expect(
navigationSearchBreadcrumbs(
[
{ url: '/docs/api', title: 'API' },
{
url: '/docs/api/doc/elasticsearch',
title: 'elasticsearch',
},
{
url: '/docs/api/doc/elasticsearch/group/endpoint-ml-anomaly',
title: 'Machine learning anomaly detection',
},
],
'api',
'assembler'
)
).toEqual([
'API',
'Elasticsearch API',
'Machine learning anomaly detection',
])
})

it('returns only API when the product crumb is missing', () => {
expect(
navigationSearchBreadcrumbs(
[{ url: '/docs/api', title: 'API' }],
'api',
'assembler'
)
).toEqual(['API'])
})

it('keeps the Docs prefix and drops the first parent when type is omitted', () => {
expect(
navigationSearchBreadcrumbs(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,11 @@ export const navigationSearchBreadcrumbs = (
buildType: string
) => {
if (typeFilter === 'api') {
const [, product, ...rest] = parents
return [
'API',
...parents
.slice(1)
.map((parent) => formatApiProductCrumb(parent.title)),
...(product ? [formatApiProductCrumb(product.title)] : []),
...rest.map((parent) => parent.title),
]
}

Expand Down
Loading
Loading