diff --git a/Directory.Packages.props b/Directory.Packages.props
index 6cea4748e3..945e1c4873 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -59,8 +59,7 @@
-
-
+
+ true
+ $(NoWarn);CS1591
Exe
enable
enable
@@ -32,6 +35,10 @@
+
+
+
+
<_Parameter1>Elastic.Documentation.Api.Tests
diff --git a/src/api/Elastic.Documentation.Api/MappingsExtensions.cs b/src/api/Elastic.Documentation.Api/MappingsExtensions.cs
index 84d3fda199..a7d2d65c5f 100644
--- a/src/api/Elastic.Documentation.Api/MappingsExtensions.cs
+++ b/src/api/Elastic.Documentation.Api/MappingsExtensions.cs
@@ -98,7 +98,7 @@ Cancel ctx
.WithTags(AskAiTag)
.WithName("ask-ai-stream")
.WithSummary("Stream an Ask AI answer as server-sent events")
- .Produces(StatusCodes.Status200OK, contentType: "text/event-stream")
+ .Produces(StatusCodes.Status200OK, "text/event-stream")
.ProducesErrors(StatusCodes.Status400BadRequest);
// UUID validation is automatic via Guid type deserialization (returns 400 if invalid)
diff --git a/src/api/Elastic.Documentation.Api/OpenApi/ApiDescriptions.cs b/src/api/Elastic.Documentation.Api/OpenApi/ApiDescriptions.cs
new file mode 100644
index 0000000000..a22481dfd6
--- /dev/null
+++ b/src/api/Elastic.Documentation.Api/OpenApi/ApiDescriptions.cs
@@ -0,0 +1,251 @@
+// 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.Nodes;
+using Elastic.Documentation.Api.AskAi;
+using Elastic.Documentation.Api.PageFeedback;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.OpenApi;
+using Microsoft.OpenApi;
+
+namespace Elastic.Documentation.Api.OpenApi;
+
+///
+/// The prose of the OpenAPI document that doc comments can't carry: tags, operations, their parameters and responses, and the
+/// problem schema. The endpoints are lambdas, and belongs to ASP.NET; the response and request
+/// types describe themselves through their doc comments.
+///
+internal static class ApiDescriptions
+{
+ internal static readonly IReadOnlyDictionary Tags = new Dictionary(StringComparer.Ordinal)
+ {
+ ["Search"] = "Search the documentation on elastic.co/docs, by full text or by page title.",
+ ["Ask AI"] = "Ask questions about Elastic in plain language and rate the answers.",
+ ["Changes"] = "Follow which documentation pages changed, to keep a copy or an index up to date.",
+ ["Page feedback"] = "Ratings that readers leave on documentation pages. Browser only: requests need an AWS WAF token.",
+ ["API reference"] = "The REST APIs that API Explorer documents, and their operations. Every operation lookup names its API: "
+ + "many operation ids and routes exist in several APIs, such as elasticsearch and elasticsearch-serverless."
+ };
+
+ internal static readonly IReadOnlyDictionary Operations = new Dictionary(StringComparer.Ordinal)
+ {
+ ["search"] = "Searches every documentation page by full text, combining keyword and semantic ranking. "
+ + "Filter by type, navigation section, deployment, product or version, and sort by relevance, date or title. "
+ + "Matched words come back wrapped in `` tags.",
+ ["navigation-search"] = "Searches page titles and the navigation, as the docs site's search box does. "
+ + "On an API Explorer page, pass `api_key` and `api_tree` to rank that API's operations first.",
+ ["list-changes"] = "Lists the pages whose content changed since a date, a batch at a time. "
+ + "Pass the `nextCursor` of a reply as `cursor` to read the next batch, until `hasMore` is false.",
+ ["ask-ai-stream"] = "Answers a question with Elastic's documentation, as a stream of server-sent events. "
+ + "Each `data:` line is a JSON event: `conversation_start`, search and tool calls, `message_chunk` parts of the answer, "
+ + "and `conversation_end`. Pass the conversation id to ask a follow-up.",
+ ["ask-ai-message-feedback"] = "Records whether an Ask AI answer helped.",
+ ["put-page-feedback"] = "Records or replaces a reader's rating of a page. The id is chosen by the client, so sending it again "
+ + "updates the same feedback.",
+ ["delete-page-feedback"] = "Deletes a reader's rating of a page.",
+ ["list-apis"] = "Lists every API that API Explorer documents, with the keys and versions the other requests take.",
+ ["get-api"] = "Reads one API by its key.",
+ ["list-api-groups"] = "Counts an API's operations by group, without listing them. Deprecated operations count only with "
+ + "`include_deprecated=true`, as in a listing, so a group's count is its listing's `totalHits`.",
+ ["list-api-operations"] = "Reads an API's operations in one of three ways. With `q`, it searches them by words, a route such as "
+ + "`GET /_cluster/health`, or a field path. With `endpoint`, it finds the operations that serve a request, such as "
+ + "`GET /my-index/_search`, best route first; add `view=full` for their fields. With neither, it lists them by path, "
+ + "one `group` at a time if you like.",
+ ["get-api-operation"] = "Reads one operation of an API, with its routes, versions and every documented field."
+ };
+
+ // Parameters by name; an operation can override one for its own meaning.
+ private static readonly Dictionary Parameters = new(StringComparer.Ordinal)
+ {
+ ["q"] = "The search terms.",
+ ["page"] = "The page to return, from 1.",
+ ["size"] = "The number of results per page, from 1 to 50.",
+ ["type"] = "Only results of this type, such as `docs` or `api`. Repeat it to allow several.",
+ ["section"] = "Only pages in this navigation section, such as `reference`. Repeat it to allow several.",
+ ["deployment"] = "Only pages that apply to this deployment type. Repeat it to allow several.",
+ ["product"] = "Only pages about this product id, such as `elasticsearch`. Repeat it to require several.",
+ ["version"] = "The version to read, such as `main` or `9`. Without it, the current version.",
+ ["sort"] = "`relevance` (the default), `recent` or `alpha`.",
+ ["api_key"] = "The API of the API Explorer page the search runs on, such as `elasticsearch`.",
+ ["api_tree"] = "The version tree of that page, `main` or a major such as `9`. It needs `api_key`.",
+ ["since"] = "Pages changed at or after this date and time, in ISO 8601.",
+ ["cursor"] = "The `nextCursor` of the previous reply.",
+ ["api"] = "The API key, such as `elasticsearch`. `GET /docs/_api/v1/apis` lists them.",
+ ["group"] = "Only the operations of this group, such as `Cluster`. Case doesn't matter.",
+ ["endpoint"] = "A request as you would send it, such as `GET /my-index/_search`, with or without the method.",
+ ["include_deprecated"] = "Include deprecated operations. The default is `false`.",
+ ["view"] = "`basic` (the default) or `full`, which adds each result's versions and fields. It needs `endpoint`.",
+ ["include_body"] = "Include the operation page's text. In a lookup by endpoint, it needs `view=full`.",
+ ["operationId"] = "The operation id, such as `cluster-health`, unique within the API.",
+ ["feedbackId"] = "The id of the feedback, a UUID the client chooses."
+ };
+
+ private static readonly Dictionary<(string Operation, string Parameter), string> ParameterOverrides = new()
+ {
+ [("list-api-operations", "q")] = "Words, a route such as `GET /_cluster/health`, or a field path. End a field with `.`, "
+ + "as in `retriever.`, to list its child fields.",
+ [("list-api-operations", "size")] = "The number of operations per page, from 1 to 50.",
+ [("list-api-operations", "page")] = "The page of a search or listing to return, from 1.",
+ [("navigation-search", "type")] = "Only results of this type, such as `docs` or `api`.",
+ [("list-changes", "size")] = "The number of pages per batch."
+ };
+
+ // A value for every parameter; an example request in ApiExamples replaces it with the value that request sends.
+ private static readonly Dictionary> ParameterExamples = new(StringComparer.Ordinal)
+ {
+ ["q"] = () => "cluster health",
+ ["page"] = () => 1,
+ ["size"] = () => 10,
+ ["type"] = () => "docs",
+ ["section"] = () => new JsonArray((JsonNode)"reference"),
+ ["deployment"] = () => new JsonArray((JsonNode)"self"),
+ ["product"] = () => new JsonArray((JsonNode)"elasticsearch"),
+ ["version"] = () => "9",
+ ["sort"] = () => "relevance",
+ ["api_key"] = () => "elasticsearch",
+ ["api_tree"] = () => "9",
+ ["since"] = () => "2026-11-17T00:00:00Z",
+ ["cursor"] = () => "WzE3OTQ4OTYyMTE3NzIsIi9kb2NzL3JlZmVyZW5jZS9vcGVudGVsZW1ldHJ5L2Vkb3Qtc2Rrcy9qYXZhL21pZ3JhdGlvbiJd",
+ ["api"] = () => "elasticsearch",
+ ["group"] = () => "Cluster",
+ ["endpoint"] = () => "GET /_cluster/health",
+ ["include_deprecated"] = () => false,
+ ["view"] = () => "full",
+ ["include_body"] = () => true,
+ ["operationId"] = () => "cluster-health",
+ ["feedbackId"] = () => "4f9d2c1a-7b3e-4c6d-9a8f-2e1b0c5d7a63"
+ };
+
+ // The search's type filter takes several values; navigation search's takes one.
+ private static readonly Dictionary<(string Operation, string Parameter), Func> ParameterExampleOverrides = new()
+ {
+ [("search", "type")] = () => new JsonArray((JsonNode)"docs")
+ };
+
+ private static readonly Dictionary SuccessByOperation = new(StringComparer.Ordinal)
+ {
+ ["search"] = "The matching pages, best first.",
+ ["navigation-search"] = "The matching pages and API operations, best first.",
+ ["list-changes"] = "A batch of changed pages.",
+ ["ask-ai-stream"] = "The answer, as server-sent events.",
+ ["ask-ai-message-feedback"] = "The rating was stored.",
+ ["put-page-feedback"] = "The feedback was stored.",
+ ["delete-page-feedback"] = "The feedback was deleted.",
+ ["list-apis"] = "Every API.",
+ ["get-api"] = "The API.",
+ ["list-api-groups"] = "The API's groups with their operation counts.",
+ ["list-api-operations"] = "A page of operations. A lookup that matches nothing is an empty page, not a 404.",
+ ["get-api-operation"] = "The operation with its fields."
+ };
+
+ private static readonly Dictionary ErrorByStatus = new(StringComparer.Ordinal)
+ {
+ ["400"] = "A parameter is missing, doesn't parse, or contradicts another one: an `invalid-arguments` problem.",
+ ["404"] = "Nothing matches: an `api-not-found`, `group-not-found` or `operation-not-found` problem.",
+ ["500"] = "An unexpected failure: an `internal-error` problem. Its detail never names the cause; quote the `traceId`.",
+ ["503"] = "A backend is temporarily unavailable: a `search-unavailable` or `feedback-unavailable` problem. "
+ + "Retry after the `Retry-After` seconds."
+ };
+
+ /// Adds the tag descriptions.
+ public static void ApplyToDocument(OpenApiDocument document)
+ {
+ foreach (var tag in document.Tags ?? Enumerable.Empty())
+ {
+ if (tag.Name is { } name && Tags.TryGetValue(name, out var description))
+ tag.Description = description;
+ }
+ }
+
+ /// Adds the operation, parameter and response descriptions.
+ public static void ApplyToOperation(OpenApiOperation operation)
+ {
+ if (operation.OperationId is not { } id)
+ return;
+ if (Operations.TryGetValue(id, out var description))
+ operation.Description = description;
+
+ foreach (var parameter in (operation.Parameters ?? []).OfType())
+ {
+ if (parameter.Name is not { } name)
+ continue;
+ if (ParameterOverrides.TryGetValue((id, name), out var text) || Parameters.TryGetValue(name, out text))
+ parameter.Description = text;
+ if (ParameterExampleOverrides.TryGetValue((id, name), out var example) || ParameterExamples.TryGetValue(name, out example))
+ parameter.Example = example();
+ }
+
+ foreach (var (status, response) in operation.Responses ?? [])
+ {
+ if (response is not OpenApiResponse openApiResponse)
+ continue;
+ if (status.StartsWith('2') && SuccessByOperation.TryGetValue(id, out var success))
+ openApiResponse.Description = success;
+ else if (ErrorByStatus.TryGetValue(status, out var error))
+ openApiResponse.Description = error;
+ }
+ }
+
+ // Examples for types whose properties can't carry an doc comment: positional records and ASP.NET's
+ // ProblemDetails. The values match the request examples in ApiExamples.
+ private static readonly Dictionary> PropertyExamples = new()
+ {
+ [typeof(AskAiRequest)] = new()
+ {
+ ["message"] = "How do I check the health of a cluster?",
+ ["conversationId"] = "7c8d9e0f-1a2b-4c3d-9e4f-5a6b7c8d9e0f"
+ },
+ [typeof(AskAiMessageFeedbackRequest)] = new()
+ {
+ ["messageId"] = "0b6f1e2d-3c4a-4b5d-8e7f-9a0b1c2d3e4f",
+ ["conversationId"] = "7c8d9e0f-1a2b-4c3d-9e4f-5a6b7c8d9e0f"
+ },
+ [typeof(PageFeedbackRequest)] = new()
+ {
+ ["pageUrl"] = "/docs/deploy-manage/monitor/cluster-health",
+ ["pageTitle"] = "Cluster health",
+ ["reasons"] = new JsonArray((JsonNode)"missingInformation"),
+ ["reasonSetVersion"] = 1,
+ ["comment"] = "An example of the yellow status would help."
+ },
+ [typeof(ProblemDetails)] = new()
+ {
+ ["type"] = ApiProblems.TypeUri(ApiProblems.InvalidArguments),
+ ["title"] = ApiProblems.TitleOf(ApiProblems.InvalidArguments),
+ ["status"] = 400,
+ ["detail"] = "Pass q or endpoint, not both.",
+ ["instance"] = "/docs/_api/v1/apis/elasticsearch/operations"
+ }
+ };
+
+ /// Adds the examples that doc comments can't carry, and describes the RFC 9457 problem every error answers with.
+ public static Task ApplyToSchema(OpenApiSchema schema, OpenApiSchemaTransformerContext context, CancellationToken _)
+ {
+ if (schema.Properties is not { } properties)
+ return Task.CompletedTask;
+ if (PropertyExamples.TryGetValue(context.JsonTypeInfo.Type, out var examples))
+ {
+ foreach (var (name, example) in examples)
+ {
+ if (properties.TryGetValue(name, out var property) && property is OpenApiSchema propertySchema)
+ propertySchema.Examples = [example.DeepClone()];
+ }
+ }
+ if (context.JsonTypeInfo.Type != typeof(ProblemDetails))
+ return Task.CompletedTask;
+ schema.Description = "An RFC 9457 problem. Match on `type`; `title` and `detail` are for people.";
+ Describe(properties, "type", "The problem type, a URI that resolves to its description on the REST API page.");
+ Describe(properties, "title", "The problem type's name; the same for every occurrence.");
+ Describe(properties, "status", "The HTTP status code of the response.");
+ Describe(properties, "detail", "What went wrong in this request.");
+ Describe(properties, "instance", "The request the problem is about, when known.");
+ return Task.CompletedTask;
+ }
+
+ private static void Describe(IDictionary properties, string name, string description)
+ {
+ if (properties.TryGetValue(name, out var property) && property is OpenApiSchema schema)
+ schema.Description = description;
+ }
+}
diff --git a/src/api/Elastic.Documentation.Api/OpenApi/ApiExamples.cs b/src/api/Elastic.Documentation.Api/OpenApi/ApiExamples.cs
new file mode 100644
index 0000000000..403a00278d
--- /dev/null
+++ b/src/api/Elastic.Documentation.Api/OpenApi/ApiExamples.cs
@@ -0,0 +1,318 @@
+// 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;
+using System.Text.Json;
+using System.Text.Json.Nodes;
+using Elastic.Documentation.Api.AskAi;
+using Microsoft.AspNetCore.OpenApi;
+using Microsoft.AspNetCore.WebUtilities;
+using Microsoft.OpenApi;
+
+namespace Elastic.Documentation.Api.OpenApi;
+
+///
+/// Adds examples to the OpenAPI document: one or more example requests per operation, each with its response and a curl
+/// x-codeSamples entry, example values on the parameters, and a problem example on every error response.
+/// Response examples are real replies, trimmed, kept in OpenApi/Examples and checked against the response types by tests.
+///
+internal static class ApiExamples
+{
+ /// The public host the examples call.
+ internal const string Server = "https://www.elastic.co";
+
+ private const string ResourcePrefix = "openapi-examples/";
+
+ /// One example request of an operation, with what it answers.
+ internal sealed record Example(string Title, string Method, string PathAndQuery)
+ {
+ /// The JSON request body, for POST and PUT.
+ public JsonNode? Body { get; init; }
+
+ /// The embedded response example, a file name in OpenApi/Examples without .json.
+ public string? Response { get; init; }
+
+ /// A response that isn't JSON, such as the Ask AI event stream.
+ public string? ResponseText { get; init; }
+
+ /// The released Elastic CLI command that sends the same request, if there is one.
+ public string? Cli { get; init; }
+ }
+
+ private const string FeedbackId = "4f9d2c1a-7b3e-4c6d-9a8f-2e1b0c5d7a63";
+ private const string MessageId = "0b6f1e2d-3c4a-4b5d-8e7f-9a0b1c2d3e4f";
+ private const string ConversationId = "7c8d9e0f-1a2b-4c3d-9e4f-5a6b7c8d9e0f";
+
+ internal static readonly IReadOnlyDictionary ByOperation = new Dictionary(StringComparer.Ordinal)
+ {
+ ["search"] =
+ [
+ new("Search the documentation", "GET", "/docs/_api/v1/search?q=cluster%20health&size=1")
+ {
+ Response = "search",
+ Cli = "elastic docs search \"cluster health\""
+ }
+ ],
+ ["navigation-search"] =
+ [
+ new("Search page titles", "GET", "/docs/_api/v1/navigation-search?q=cluster%20health") { Response = "navigation-search" }
+ ],
+ ["list-changes"] =
+ [
+ new("Pages changed since a date", "GET", "/docs/_api/v1/changes?since=2026-11-17T00:00:00Z&size=1")
+ {
+ Response = "list-changes"
+ }
+ ],
+ ["ask-ai-stream"] =
+ [
+ new("Ask a question", "POST", "/docs/_api/v1/ask-ai/stream")
+ {
+ Body = new JsonObject { ["message"] = "How do I check the health of a cluster?", ["conversationId"] = null },
+ ResponseText = AskAiStream(),
+ Cli = "elastic docs ask \"How do I check the health of a cluster?\""
+ }
+ ],
+ ["ask-ai-message-feedback"] =
+ [
+ new("Rate an answer", "POST", "/docs/_api/v1/ask-ai/message-feedback")
+ {
+ Body = new JsonObject { ["messageId"] = MessageId, ["conversationId"] = ConversationId, ["reaction"] = "thumbsUp" }
+ }
+ ],
+ ["put-page-feedback"] =
+ [
+ new("Rate a page", "PUT", $"/docs/_api/v1/page-feedback/{FeedbackId}")
+ {
+ Body = new JsonObject
+ {
+ ["pageUrl"] = "/docs/deploy-manage/monitor/cluster-health",
+ ["pageTitle"] = "Cluster health",
+ ["reaction"] = "thumbsDown",
+ ["reasons"] = new JsonArray("missingInformation"),
+ ["reasonSetVersion"] = 1,
+ ["comment"] = "An example of the yellow status would help."
+ }
+ }
+ ],
+ ["delete-page-feedback"] = [new("Withdraw page feedback", "DELETE", $"/docs/_api/v1/page-feedback/{FeedbackId}")],
+ ["list-apis"] = [new("Every API", "GET", "/docs/_api/v1/apis") { Response = "list-apis" }],
+ ["get-api"] = [new("One API", "GET", "/docs/_api/v1/apis/elasticsearch") { Response = "get-api" }],
+ ["list-api-groups"] = [new("Groups of an API", "GET", "/docs/_api/v1/apis/elasticsearch/groups") { Response = "list-api-groups" }],
+ ["list-api-operations"] =
+ [
+ new("Search an API", "GET", "/docs/_api/v1/apis/elasticsearch/operations?q=cluster%20health&size=1")
+ {
+ Response = "list-api-operations.search"
+ },
+ new("Look up an endpoint", "GET", "/docs/_api/v1/apis/elasticsearch/operations?endpoint=GET%20%2F_cluster%2Fhealth&view=full")
+ {
+ Response = "list-api-operations.endpoint"
+ },
+ new("List a group", "GET", "/docs/_api/v1/apis/elasticsearch/operations?group=Cluster%20-%20Health")
+ {
+ Response = "list-api-operations.group"
+ }
+ ],
+ ["get-api-operation"] =
+ [
+ new("One operation", "GET", "/docs/_api/v1/apis/elasticsearch/operations/cluster-health") { Response = "get-api-operation" }
+ ]
+ };
+
+ // The problem each error status answers with, unless the operation answers that status with its own type or detail
+ // below. Clients match on the type, so an example shows a type the operation really returns. ApiProblems defines them.
+ private static readonly Dictionary ProblemByStatus = new()
+ {
+ [StatusCodes.Status400BadRequest] = (ApiProblems.InvalidArguments, "A parameter is missing or does not parse."),
+ [StatusCodes.Status404NotFound] = ("api-not-found", "No operations found for API 'nope'."),
+ [StatusCodes.Status500InternalServerError] = (ApiProblems.InternalError, "An unexpected error occurred."),
+ [StatusCodes.Status503ServiceUnavailable] =
+ (ApiProblems.SearchUnavailable, "Search backend is temporarily unavailable (MaxTimeoutReached). Transient — retry in a few seconds.")
+ };
+
+ private const string FeedbackUnavailable = "The feedback could not be stored. Try again later.";
+
+ private static readonly Dictionary<(string Operation, int Status), (string Type, string Detail)> ProblemByOperation = new()
+ {
+ [("search", 400)] = (ApiProblems.InvalidArguments, "Required parameter \"string query\" was not provided from query string."),
+ [("navigation-search", 400)] =
+ (ApiProblems.InvalidArguments, "api_key must be a lowercase API key, and api_tree 'main' or a major version with api_key."),
+ [("list-changes", 400)] = (ApiProblems.InvalidArguments, "cursor is not a nextCursor that /changes returned."),
+ [("ask-ai-stream", 400)] =
+ (ApiProblems.InvalidArguments, "Failed to read parameter \"AskAiRequest askAiRequest\" from the request body as JSON."),
+ [("ask-ai-message-feedback", 400)] =
+ (ApiProblems.InvalidArguments, "Failed to read parameter \"AskAiMessageFeedbackRequest request\" from the request body as JSON."),
+ [("ask-ai-message-feedback", 503)] = (ApiProblems.FeedbackUnavailable, FeedbackUnavailable),
+ [("put-page-feedback", 400)] =
+ (ApiProblems.InvalidArguments, "The page feedback is invalid. Check pageUrl, pageTitle, reaction, reasons and comment."),
+ [("put-page-feedback", 503)] = (ApiProblems.FeedbackUnavailable, FeedbackUnavailable),
+ [("delete-page-feedback", 503)] = (ApiProblems.FeedbackUnavailable, FeedbackUnavailable),
+ [("get-api", 404)] = ("api-not-found", "No API 'nope'."),
+ [("list-api-groups", 400)] = (ApiProblems.InvalidArguments, "Pass an API key, such as 'elasticsearch'."),
+ [("list-api-operations", 400)] = (ApiProblems.InvalidArguments, "Pass q or endpoint, not both."),
+ [("get-api-operation", 400)] = (ApiProblems.InvalidArguments, "Pass an API key, such as 'elasticsearch'."),
+ [("get-api-operation", 404)] = ("operation-not-found", "No API operation matches nope in elasticsearch.")
+ };
+
+ /// The operation transformer that adds the examples.
+ public static Task Apply(OpenApiOperation operation, OpenApiOperationTransformerContext context, CancellationToken _)
+ {
+ AddProblemExamples(operation, operation.OperationId);
+ if (operation.OperationId is not { } id || !ByOperation.TryGetValue(id, out var examples))
+ return Task.CompletedTask;
+
+ AddParameterExamples(operation, context.Description.RelativePath, examples[0].PathAndQuery);
+ AddRequestBodyExamples(operation, examples);
+ AddResponseExamples(operation, examples);
+ operation.Extensions ??= new Dictionary(StringComparer.Ordinal);
+ operation.Extensions["x-codeSamples"] = new JsonNodeExtension(CodeSamples(examples));
+ return Task.CompletedTask;
+ }
+
+ /// The x-codeSamples of the examples: a curl per example, and the Elastic CLI command where one exists.
+ internal static JsonArray CodeSamples(IReadOnlyList examples)
+ {
+ var samples = new JsonArray();
+ foreach (var example in examples)
+ {
+ // API Explorer ties a curl to its example by label once the operation has more than one.
+ // JsonNode, not a generic Add: the generic one can serialize any type, which trimming can't follow.
+ samples.Add((JsonNode)new JsonObject { ["lang"] = "curl", ["label"] = example.Title, ["source"] = Curl(example) });
+ if (example.Cli is { } cli)
+ samples.Add((JsonNode)new JsonObject { ["lang"] = "Shell", ["label"] = "Elastic CLI", ["source"] = cli });
+ }
+ return samples;
+ }
+
+ /// A curl command for an example request, against .
+ internal static string Curl(Example example)
+ {
+ var curl = new StringBuilder("curl");
+ if (example.Method != "GET")
+ _ = curl.Append(" -X ").Append(example.Method);
+ _ = curl.Append(" '").Append(Server).Append(example.PathAndQuery).Append('\'');
+ if (example.Body is { } body)
+ _ = curl.Append(" \\\n -H 'Content-Type: application/json' \\\n -d '").Append(body.ToJsonString()).Append('\'');
+ return curl.ToString();
+ }
+
+ /// Reads a response example from the files embedded from OpenApi/Examples.
+ internal static JsonNode ReadResponse(string name)
+ {
+ using var stream = typeof(ApiExamples).Assembly.GetManifestResourceStream(ResourcePrefix + name + ".json")
+ ?? throw new InvalidOperationException($"No OpenAPI response example '{name}' is embedded.");
+ return JsonNode.Parse(stream) ?? throw new InvalidOperationException($"The OpenAPI response example '{name}' is empty.");
+ }
+
+ private static void AddParameterExamples(OpenApiOperation operation, string? template, string pathAndQuery)
+ {
+ if (operation.Parameters is not { Count: > 0 } parameters)
+ return;
+ var separator = pathAndQuery.IndexOf('?');
+ var path = separator < 0 ? pathAndQuery : pathAndQuery[..separator];
+ var values = separator < 0
+ ? []
+ : QueryHelpers.ParseQuery(pathAndQuery[separator..]).ToDictionary(p => p.Key, p => p.Value.ToString());
+
+ // Route values sit where the template has {name} or {name:constraint}.
+ var templateSegments = (template ?? "").Trim('/').Split('/');
+ var pathSegments = path.Trim('/').Split('/');
+ for (var i = 0; i < templateSegments.Length && i < pathSegments.Length; i++)
+ {
+ if (templateSegments[i] is ['{', .., '}'] segment)
+ values[segment[1..^1].Split(':')[0]] = Uri.UnescapeDataString(pathSegments[i]);
+ }
+
+ foreach (var parameter in parameters.OfType())
+ {
+ if (parameter.Name is { } name && values.TryGetValue(name, out var value))
+ parameter.Example = int.TryParse(value, out var number) ? JsonValue.Create(number) : JsonValue.Create(value);
+ }
+ }
+
+ private static void AddRequestBodyExamples(OpenApiOperation operation, IReadOnlyList examples)
+ {
+ if (operation.RequestBody?.Content is not { } content || !content.TryGetValue("application/json", out var media))
+ return;
+ if (examples.FirstOrDefault(e => e.Body is not null)?.Body is { } body && media is OpenApiMediaType mediaType)
+ mediaType.Example = body.DeepClone();
+ }
+
+ private static void AddResponseExamples(OpenApiOperation operation, IReadOnlyList examples)
+ {
+ if (operation.Responses is null)
+ return;
+ foreach (var (status, response) in operation.Responses)
+ {
+ if (!status.StartsWith('2') || response.Content is not { } content)
+ continue;
+ foreach (var (contentType, media) in content)
+ {
+ if (media is not OpenApiMediaType mediaType)
+ continue;
+ var values = examples
+ .Select(
+ e =>
+ (e.Title, Value: contentType == "application/json" && e.Response is { } file
+ ? ReadResponse(file)
+ : e.ResponseText is { } text ? JsonValue.Create(text) : null)
+ )
+ .Where(e => e.Value is not null)
+ .ToList();
+ if (values.Count == 1)
+ mediaType.Example = values[0].Value;
+ else if (values.Count > 1)
+ {
+ mediaType.Examples = new Dictionary(StringComparer.Ordinal);
+ foreach (var (title, value) in values)
+ mediaType.Examples[title] = new OpenApiExample { Summary = title, Value = value };
+ }
+ }
+ }
+ }
+
+ private static void AddProblemExamples(OpenApiOperation operation, string? operationId)
+ {
+ if (operation.Responses is null)
+ return;
+ foreach (var (status, response) in operation.Responses)
+ {
+ if (!int.TryParse(status, out var code) || response.Content is not { } content)
+ continue;
+ if (
+ !(operationId is not null && ProblemByOperation.TryGetValue((operationId, code), out var problem))
+ && !ProblemByStatus.TryGetValue(code, out problem)
+ )
+ continue;
+ if (content.TryGetValue("application/problem+json", out var media) && media is OpenApiMediaType mediaType)
+ mediaType.Example = Problem(code, problem.Type, problem.Detail);
+ }
+ }
+
+ /// An RFC 9457 problem as the API writes it.
+ internal static JsonObject Problem(int status, string type, string detail) =>
+ new()
+ {
+ ["type"] = ApiProblems.TypeUri(type),
+ ["title"] = ApiProblems.TitleOf(type),
+ ["status"] = status,
+ ["detail"] = detail,
+ ["traceId"] = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"
+ };
+
+ // The events a short answer streams, written by the same JSON context as the API's stream transformer.
+ private static string AskAiStream()
+ {
+ AskAiEvent[] events =
+ [
+ new AskAiEvent.ConversationStart("1", 1763380000000, ConversationId),
+ new AskAiEvent.SearchToolCall("2", 1763380000400, "call_1", "check cluster health"),
+ new AskAiEvent.MessageChunk("3", 1763380001200, "Call `GET /_cluster/health`. "),
+ new AskAiEvent.MessageChunk("4", 1763380001300, "A `green` status means every shard is assigned."),
+ new AskAiEvent.ConversationEnd("5", 1763380001500)
+ ];
+ return string.Concat(events.Select(e => $"data: {JsonSerializer.Serialize(e, AskAiEventJsonContext.Default.AskAiEvent)}\n\n"));
+ }
+}
diff --git a/src/api/Elastic.Documentation.Api/OpenApi/Examples/get-api-operation.json b/src/api/Elastic.Documentation.Api/OpenApi/Examples/get-api-operation.json
new file mode 100644
index 0000000000..9606472714
--- /dev/null
+++ b/src/api/Elastic.Documentation.Api/OpenApi/Examples/get-api-operation.json
@@ -0,0 +1,48 @@
+{
+ "operation": {
+ "api": "elasticsearch",
+ "title": "Get the cluster health status",
+ "url": "/docs/api/doc/elasticsearch/operation/operation-cluster-health",
+ "description": "You can also use the API to get the health status of only specified data streams and indices.\nFor data streams, the API retrieves the health status of the st…",
+ "method": "GET",
+ "path": "/_cluster/health/{index}",
+ "operationId": "cluster-health",
+ "group": "Cluster",
+ "deprecated": false,
+ "endpoints": [
+ "GET /_cluster/health/{index}",
+ "GET /_cluster/health"
+ ]
+ },
+ "versions": [
+ "main"
+ ],
+ "fields": [
+ {
+ "name": "index",
+ "path": "index",
+ "type": "union string | string[]",
+ "location": "path",
+ "description": "A comma-separated list of data streams, indices, and index aliases that limit the request. Wildcard expressions () are supported. To target all data streams…"
+ },
+ {
+ "name": "expand_wildcards",
+ "path": "expand_wildcards",
+ "type": "union oneOf · default: all",
+ "location": "query",
+ "description": "Expand wildcard expression to concrete indices that are open, closed or both. Supported values include: - all: Match any data stream or index, including hidd…"
+ },
+ {
+ "name": "level",
+ "path": "level",
+ "type": "enum · default: cluster",
+ "location": "query",
+ "description": "Return health information at a specific level of detail."
+ }
+ ],
+ "aiShortSummary": "Check Elasticsearch cluster health status via API.",
+ "body": null,
+ "bodyLength": 3639,
+ "bodyNote": null,
+ "otherMatches": []
+}
diff --git a/src/api/Elastic.Documentation.Api/OpenApi/Examples/get-api.json b/src/api/Elastic.Documentation.Api/OpenApi/Examples/get-api.json
new file mode 100644
index 0000000000..e91f546e61
--- /dev/null
+++ b/src/api/Elastic.Documentation.Api/OpenApi/Examples/get-api.json
@@ -0,0 +1,10 @@
+{
+ "key": "elasticsearch",
+ "title": "Elasticsearch API",
+ "url": "/docs/api/doc/elasticsearch",
+ "description": "Elasticsearch provides REST APIs that are used by the UI components and can be called directly to configure and access Elasticsearch features.",
+ "versions": [
+ "main",
+ "9"
+ ]
+}
diff --git a/src/api/Elastic.Documentation.Api/OpenApi/Examples/list-api-groups.json b/src/api/Elastic.Documentation.Api/OpenApi/Examples/list-api-groups.json
new file mode 100644
index 0000000000..d548808508
--- /dev/null
+++ b/src/api/Elastic.Documentation.Api/OpenApi/Examples/list-api-groups.json
@@ -0,0 +1,23 @@
+{
+ "api": "elasticsearch",
+ "version": null,
+ "totalOperations": 549,
+ "groups": [
+ {
+ "name": "Cluster",
+ "count": 20,
+ "operations": null
+ },
+ {
+ "name": "Cluster - Health",
+ "count": 1,
+ "operations": null
+ },
+ {
+ "name": "Compact and aligned text (CAT)",
+ "count": 27,
+ "operations": null
+ }
+ ],
+ "note": null
+}
diff --git a/src/api/Elastic.Documentation.Api/OpenApi/Examples/list-api-operations.endpoint.json b/src/api/Elastic.Documentation.Api/OpenApi/Examples/list-api-operations.endpoint.json
new file mode 100644
index 0000000000..17affdf8a3
--- /dev/null
+++ b/src/api/Elastic.Documentation.Api/OpenApi/Examples/list-api-operations.endpoint.json
@@ -0,0 +1,51 @@
+{
+ "totalHits": 1,
+ "results": [
+ {
+ "operation": {
+ "api": "elasticsearch",
+ "title": "Get the cluster health status",
+ "url": "/docs/api/doc/elasticsearch/operation/operation-cluster-health",
+ "description": "You can also use the API to get the health status of only specified data streams and indices.\nFor data streams, the API retrieves the health status of the st…",
+ "method": "GET",
+ "path": "/_cluster/health/{index}",
+ "operationId": "cluster-health",
+ "group": "Cluster",
+ "deprecated": false,
+ "endpoints": [
+ "GET /_cluster/health/{index}",
+ "GET /_cluster/health"
+ ]
+ },
+ "score": null,
+ "matchedFields": null,
+ "versions": [
+ "main"
+ ],
+ "fields": [
+ {
+ "name": "index",
+ "path": "index",
+ "type": "union string | string[]",
+ "location": "path",
+ "description": "A comma-separated list of data streams, indices, and index aliases that limit the request. Wildcard expressions () are supported. To target all data streams…"
+ },
+ {
+ "name": "expand_wildcards",
+ "path": "expand_wildcards",
+ "type": "union oneOf · default: all",
+ "location": "query",
+ "description": "Expand wildcard expression to concrete indices that are open, closed or both. Supported values include: - all: Match any data stream or index, including hidd…"
+ },
+ {
+ "name": "level",
+ "path": "level",
+ "type": "enum · default: cluster",
+ "location": "query",
+ "description": "Return health information at a specific level of detail."
+ }
+ ],
+ "body": null
+ }
+ ]
+}
diff --git a/src/api/Elastic.Documentation.Api/OpenApi/Examples/list-api-operations.group.json b/src/api/Elastic.Documentation.Api/OpenApi/Examples/list-api-operations.group.json
new file mode 100644
index 0000000000..e34868c269
--- /dev/null
+++ b/src/api/Elastic.Documentation.Api/OpenApi/Examples/list-api-operations.group.json
@@ -0,0 +1,27 @@
+{
+ "totalHits": 1,
+ "results": [
+ {
+ "operation": {
+ "api": "elasticsearch",
+ "title": "Get the cluster health",
+ "url": "/docs/api/doc/elasticsearch/operation/operation-health-report",
+ "description": "Get a report with the health status of an Elasticsearch cluster.\nThe report contains a list of indicators that compose Elasticsearch functionality.\n\nEach ind…",
+ "method": "GET",
+ "path": "/_health_report/{feature}",
+ "operationId": "health-report",
+ "group": "Cluster - Health",
+ "deprecated": false,
+ "endpoints": [
+ "GET /_health_report/{feature}",
+ "GET /_health_report"
+ ]
+ },
+ "score": null,
+ "matchedFields": null,
+ "versions": null,
+ "fields": null,
+ "body": null
+ }
+ ]
+}
diff --git a/src/api/Elastic.Documentation.Api/OpenApi/Examples/list-api-operations.search.json b/src/api/Elastic.Documentation.Api/OpenApi/Examples/list-api-operations.search.json
new file mode 100644
index 0000000000..3861226670
--- /dev/null
+++ b/src/api/Elastic.Documentation.Api/OpenApi/Examples/list-api-operations.search.json
@@ -0,0 +1,27 @@
+{
+ "totalHits": 9,
+ "results": [
+ {
+ "operation": {
+ "api": "elasticsearch",
+ "title": "Get the cluster health status",
+ "url": "/docs/api/doc/elasticsearch/operation/operation-cluster-health",
+ "description": "You can also use the API to get the health status of only specified data streams and indices.\nFor data streams, the API retrieves the health status of the st…",
+ "method": "GET",
+ "path": "/_cluster/health/{index}",
+ "operationId": "cluster-health",
+ "group": "Cluster",
+ "deprecated": false,
+ "endpoints": [
+ "GET /_cluster/health/{index}",
+ "GET /_cluster/health"
+ ]
+ },
+ "score": 11.618973,
+ "matchedFields": [],
+ "versions": null,
+ "fields": null,
+ "body": null
+ }
+ ]
+}
diff --git a/src/api/Elastic.Documentation.Api/OpenApi/Examples/list-apis.json b/src/api/Elastic.Documentation.Api/OpenApi/Examples/list-apis.json
new file mode 100644
index 0000000000..0f6eb38d46
--- /dev/null
+++ b/src/api/Elastic.Documentation.Api/OpenApi/Examples/list-apis.json
@@ -0,0 +1,31 @@
+{
+ "apis": [
+ {
+ "key": "cloud",
+ "title": "Elastic Cloud API",
+ "url": "/docs/api/doc/cloud",
+ "description": "This RESTful API enables you to perform most of the operations available in the UI console through API calls.",
+ "versions": [
+ "main"
+ ]
+ },
+ {
+ "key": "cloud-billing",
+ "title": "Cloud Billing API",
+ "url": "/docs/api/doc/cloud-billing",
+ "description": "The Cloud Billing API enables you to retrieve cost and usage information.",
+ "versions": [
+ "main"
+ ]
+ },
+ {
+ "key": "cloud-connect",
+ "title": "Elastic Cloud Connected API",
+ "url": "/docs/api/doc/cloud-connect",
+ "description": "This API enables you to use Elastic Cloud services in your ECE, ECK, or self-managed cluster without having to install and maintain their infrastructure...",
+ "versions": [
+ "main"
+ ]
+ }
+ ]
+}
diff --git a/src/api/Elastic.Documentation.Api/OpenApi/Examples/list-changes.json b/src/api/Elastic.Documentation.Api/OpenApi/Examples/list-changes.json
new file mode 100644
index 0000000000..8617511fe7
--- /dev/null
+++ b/src/api/Elastic.Documentation.Api/OpenApi/Examples/list-changes.json
@@ -0,0 +1,11 @@
+{
+ "pages": [
+ {
+ "url": "/docs/reference/opentelemetry/edot-sdks/java/configuration",
+ "title": "Configure the EDOT Java agent",
+ "lastUpdated": "2026-11-17T06:16:51.7648902+00:00"
+ }
+ ],
+ "hasMore": true,
+ "nextCursor": "WzE3OTQ4OTYyMTE3NzIsIi9kb2NzL3JlZmVyZW5jZS9vcGVudGVsZW1ldHJ5L2Vkb3Qtc2Rrcy9qYXZhL21pZ3JhdGlvbiJd"
+}
diff --git a/src/api/Elastic.Documentation.Api/OpenApi/Examples/navigation-search.json b/src/api/Elastic.Documentation.Api/OpenApi/Examples/navigation-search.json
new file mode 100644
index 0000000000..e8d0b50c5a
--- /dev/null
+++ b/src/api/Elastic.Documentation.Api/OpenApi/Examples/navigation-search.json
@@ -0,0 +1,33 @@
+{
+ "results": [
+ {
+ "properties": [],
+ "routes": [],
+ "deprecated": false,
+ "landing": false,
+ "apiKey": null,
+ "product": "elasticsearch",
+ "type": "docs",
+ "url": "/docs/troubleshoot/elasticsearch/red-yellow-cluster-status",
+ "title": "Red or yellow cluster health status",
+ "description": "and cleanup activities until the cluster returns to green health status. In many cases, your cluster will recover to g…",
+ "parents": [
+ {
+ "title": "Docs",
+ "url": "/docs"
+ }
+ ],
+ "score": 4.7976103
+ }
+ ],
+ "totalResults": 314,
+ "pageNumber": 1,
+ "pageSize": 20,
+ "aggregations": {
+ "type": {
+ "docs": 306,
+ "api": 8
+ }
+ },
+ "pageCount": 16
+}
diff --git a/src/api/Elastic.Documentation.Api/OpenApi/Examples/search.json b/src/api/Elastic.Documentation.Api/OpenApi/Examples/search.json
new file mode 100644
index 0000000000..7de22a585c
--- /dev/null
+++ b/src/api/Elastic.Documentation.Api/OpenApi/Examples/search.json
@@ -0,0 +1,62 @@
+{
+ "results": [
+ {
+ "type": "docs",
+ "url": "/docs/troubleshoot/elasticsearch/red-yellow-cluster-status",
+ "title": "Red or yellow cluster health status",
+ "description": "and cleanup activities until the cluster returns to green health status. In many cases, your cluster will recover to g…",
+ "parents": [
+ {
+ "title": "Docs",
+ "url": "/docs"
+ }
+ ],
+ "score": 4.7976103,
+ "aiShortSummary": "Fix red or yellow Elasticsearch cluster health status.",
+ "aiRagOptimizedSummary": "A red Elasticsearch cluster health status indicates unassigned primary shards causing potential search and indexing failures, while yellow status means unass…",
+ "navigationSection": "troubleshoot",
+ "lastUpdated": "2026-11-17T19:20:53.9554741+00:00",
+ "product": {
+ "id": "elasticsearch",
+ "displayName": "Elasticsearch"
+ },
+ "relatedProducts": [
+ {
+ "id": "elasticsearch",
+ "displayName": "Elasticsearch"
+ }
+ ]
+ }
+ ],
+ "totalResults": 314,
+ "pageNumber": 1,
+ "pageSize": 1,
+ "aggregations": {
+ "type": {
+ "docs": 306,
+ "api": 8
+ },
+ "navigationSection": {
+ "reference": 150,
+ "deploy and manage": 78,
+ "troubleshoot": 33
+ },
+ "deploymentType": {},
+ "product": {
+ "elastic docs": {
+ "count": 155,
+ "displayName": "elastic docs"
+ },
+ "elasticsearch": {
+ "count": 99,
+ "displayName": "Elasticsearch"
+ },
+ "cloud kubernetes": {
+ "count": 62,
+ "displayName": "cloud kubernetes"
+ }
+ }
+ },
+ "isSemanticQuery": false,
+ "pageCount": 314
+}
diff --git a/src/api/Elastic.Documentation.Api/PageFeedback/PageFeedbackRequest.cs b/src/api/Elastic.Documentation.Api/PageFeedback/PageFeedbackRequest.cs
index 4ab6284c32..e2e3b6ef07 100644
--- a/src/api/Elastic.Documentation.Api/PageFeedback/PageFeedbackRequest.cs
+++ b/src/api/Elastic.Documentation.Api/PageFeedback/PageFeedbackRequest.cs
@@ -6,6 +6,13 @@
namespace Elastic.Documentation.Api.PageFeedback;
+/// A reader's rating of a documentation page.
+/// The page's path, starting with /, at most 2048 characters.
+/// The page's title, at most 500 characters.
+/// thumbsUp or thumbsDown.
+/// Why, from the reasons that fit the reaction; omit with reasonSetVersion for a reaction alone.
+/// The version of the reason set the reasons come from; required with reasons.
+/// Free text, at most 2000 characters; it needs reasons.
public record PageFeedbackRequest(
string PageUrl,
string PageTitle,
@@ -15,6 +22,7 @@ public record PageFeedbackRequest(
string? Comment
);
+/// How a reader rated a page: thumbsUp or thumbsDown.
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum PageFeedbackReaction
{
@@ -28,6 +36,11 @@ public enum PageFeedbackReaction
ThumbsDown
}
+///
+/// Why a reader rated a page. For thumbsUp: accurate, solvedProblem, easyToUnderstand,
+/// helpfulExamples, easyToFind. For thumbsDown: inaccurate, missingInformation,
+/// hardToUnderstand, codeSampleErrors, outOfDate. anotherReason fits either.
+///
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum PageFeedbackReason
{
diff --git a/src/api/Elastic.Documentation.Api/ServicesExtension.cs b/src/api/Elastic.Documentation.Api/ServicesExtension.cs
index 7d29a728b1..a9c3dbd689 100644
--- a/src/api/Elastic.Documentation.Api/ServicesExtension.cs
+++ b/src/api/Elastic.Documentation.Api/ServicesExtension.cs
@@ -65,18 +65,30 @@ private static void AddElasticDocsApiServices(this IServiceCollection services,
// Every error answers RFC 9457 problem details; binding failures throw, so they get a precise detail.
_ = services.AddProblemDetails(options => options.CustomizeProblemDetails = ApiProblems.Customize);
_ = services.Configure(options => options.ThrowOnBadRequest = true);
- _ = services.AddOpenApi(options => options.AddDocumentTransformer((document, _, _) =>
- {
- document.Info = new OpenApiInfo
+ _ = services.AddOpenApi(options => options
+ .AddOperationTransformer((operation, _, _) =>
+ {
+ OpenApi.ApiDescriptions.ApplyToOperation(operation);
+ return Task.CompletedTask;
+ })
+ .AddOperationTransformer(OpenApi.ApiExamples.Apply)
+ .AddSchemaTransformer(OpenApi.ApiDescriptions.ApplyToSchema)
+ .AddDocumentTransformer((document, _, _) =>
{
- Title = "Elastic Docs API",
- Version = "v1",
- Description = "Search, Ask AI, change feeds, feedback and the API reference behind elastic.co/docs. "
- + "Requests through www.elastic.co need the cookie feature_search_or_askai_enabled=true; without it the CDN answers 403."
- };
- document.Servers = [new OpenApiServer { Url = "https://www.elastic.co" }];
- return Task.CompletedTask;
- }));
+ OpenApi.ApiDescriptions.ApplyToDocument(document);
+ return Task.CompletedTask;
+ })
+ .AddDocumentTransformer((document, _, _) =>
+ {
+ document.Info = new OpenApiInfo
+ {
+ Title = "Elastic Docs API",
+ Version = "v1",
+ Description = "Search, Ask AI, change feeds, feedback and the API reference behind elastic.co/docs."
+ };
+ document.Servers = [new OpenApiServer { Url = OpenApi.ApiExamples.Server }];
+ return Task.CompletedTask;
+ }));
// Register AppEnvironment as a singleton for dependency injection
_ = services.AddSingleton(new AppEnvironment { Current = appEnv });
diff --git a/src/services/search/Elastic.Documentation.Search.Contract/Common/IProductNameLookup.cs b/src/services/search/Elastic.Documentation.Search.Contract/Common/IProductNameLookup.cs
index f7ccec0bde..1472ac33ce 100644
--- a/src/services/search/Elastic.Documentation.Search.Contract/Common/IProductNameLookup.cs
+++ b/src/services/search/Elastic.Documentation.Search.Contract/Common/IProductNameLookup.cs
@@ -6,7 +6,7 @@ namespace Elastic.Documentation.Search.Contract;
///
/// Resolves a product id (e.g. elasticsearch, kibana) to a human-friendly display
-/// name. Injected into (or its equivalents) to
+/// name. Injected into DefaultSearchService<TDocument> (or its equivalents) to
/// enrich product aggregation buckets and per-hit product references during result post-processing.
/// Consumers without product metadata can omit the dependency — DefaultSearchService treats it as
/// optional and emits null DisplayName values when no lookup is wired.
diff --git a/src/services/search/Elastic.Documentation.Search.Contract/Common/SearchDocumentBase.cs b/src/services/search/Elastic.Documentation.Search.Contract/Common/SearchDocumentBase.cs
index ffad7544f8..1156a51acd 100644
--- a/src/services/search/Elastic.Documentation.Search.Contract/Common/SearchDocumentBase.cs
+++ b/src/services/search/Elastic.Documentation.Search.Contract/Common/SearchDocumentBase.cs
@@ -167,7 +167,7 @@ public string ContentType
/// Editorial weight — one of . Used to demote low-value content
/// (marketing, legal, downloads) without a hand-maintained downstream section list.
/// Defaults to — a NEUTRAL default, unlike
- /// / which default to a
+ /// NavigationDepth/NavigationTableOfContents which default to a
/// penalty value. Every producer (essc and docs-builder) sets its own value on this shared field.
///
[Keyword]
diff --git a/src/services/search/Elastic.Documentation.Search.Contract/Common/SearchDocumentPolymorphism.cs b/src/services/search/Elastic.Documentation.Search.Contract/Common/SearchDocumentPolymorphism.cs
index 0792c135d7..7dc2b64c6a 100644
--- a/src/services/search/Elastic.Documentation.Search.Contract/Common/SearchDocumentPolymorphism.cs
+++ b/src/services/search/Elastic.Documentation.Search.Contract/Common/SearchDocumentPolymorphism.cs
@@ -118,7 +118,7 @@ public static Action WithFallback() =>
///
/// Combines the contract's source-gen resolver with one or more consumer contexts and
/// applies in order via
- /// .
+ /// JsonTypeInfoResolver.WithAddedModifier.
///
/// Typical docs search call site:
///
diff --git a/src/services/search/Elastic.Documentation.Search.Contract/Docs/ApiRouteEntry.cs b/src/services/search/Elastic.Documentation.Search.Contract/Docs/ApiRouteEntry.cs
index c31f381df1..59e35d0910 100644
--- a/src/services/search/Elastic.Documentation.Search.Contract/Docs/ApiRouteEntry.cs
+++ b/src/services/search/Elastic.Documentation.Search.Contract/Docs/ApiRouteEntry.cs
@@ -11,11 +11,13 @@ namespace Elastic.Documentation.Search.Contract;
public record ApiRouteEntry
{
/// Spec path, verbatim, e.g. /{index}/_search.
+ /// "/_cluster/health/{index}"
[Keyword(Index = false)]
[JsonPropertyName("path")]
public required string Path { get; init; }
/// Upper-case HTTP methods, the one the page leads with first, e.g. POST, GET.
+ /// ["GET"]
[Keyword(Index = false)]
[JsonPropertyName("methods")]
public required string[] Methods { get; init; }
diff --git a/src/services/search/Elastic.Documentation.Search.Contract/Elastic.Documentation.Search.Contract.csproj b/src/services/search/Elastic.Documentation.Search.Contract/Elastic.Documentation.Search.Contract.csproj
index 3e694606d4..0c88ab50c3 100644
--- a/src/services/search/Elastic.Documentation.Search.Contract/Elastic.Documentation.Search.Contract.csproj
+++ b/src/services/search/Elastic.Documentation.Search.Contract/Elastic.Documentation.Search.Contract.csproj
@@ -1,6 +1,9 @@
+
+ true
+ $(NoWarn);CS1591
enable
enable
Elastic.Documentation.Search.Contract
diff --git a/src/services/search/Elastic.Documentation.Search.Contract/Search/ProductAggregationBucket.cs b/src/services/search/Elastic.Documentation.Search.Contract/Search/ProductAggregationBucket.cs
index d087e13a11..8dfec2e3f5 100644
--- a/src/services/search/Elastic.Documentation.Search.Contract/Search/ProductAggregationBucket.cs
+++ b/src/services/search/Elastic.Documentation.Search.Contract/Search/ProductAggregationBucket.cs
@@ -7,6 +7,10 @@ namespace Elastic.Documentation.Search.Contract;
/// Product facet bucket — doc count plus the display name resolved by the consumer.
public record ProductAggregationBucket
{
+ /// The number of results for the product.
+ /// 155
public required long Count { get; init; }
+ /// The product's name for display.
+ /// "elastic docs"
public string? DisplayName { get; init; }
}
diff --git a/src/services/search/Elastic.Documentation.Search/ApiReference/ApiReferenceService.cs b/src/services/search/Elastic.Documentation.Search/ApiReference/ApiReferenceService.cs
index 3cd90a0b48..778f704c7f 100644
--- a/src/services/search/Elastic.Documentation.Search/ApiReference/ApiReferenceService.cs
+++ b/src/services/search/Elastic.Documentation.Search/ApiReference/ApiReferenceService.cs
@@ -332,64 +332,117 @@ public sealed record ApiOperationQuery
/// A page of one API's operations.
public sealed record ApiOperationCollectionResponse
{
+ /// Every operation that matches, across pages.
+ /// 9
public required long TotalHits { get; init; }
+ /// The operations on this page.
public required IReadOnlyList Results { get; init; }
}
/// One operation in a page. Search adds a score and the matched fields; the full view adds versions, fields and the body.
public sealed record ApiOperationItem
{
+ /// The operation.
public required ApiOperationSummary Operation { get; init; }
+ /// The relevance score of a search result; null outside a search.
+ /// 11.618973
public float? Score { get; init; }
+ /// The fields of the operation that match the search; null outside a search.
public IReadOnlyList? MatchedFields { get; init; }
+ /// The API versions that document the operation; only with view=full.
+ /// ["main"]
public string[]? Versions { get; init; }
+ /// Every documented field of the operation; only with view=full.
public IReadOnlyList? Fields { get; init; }
+ /// The operation page's text; only with include_body=true.
+ /// "Returns the health status of a cluster, or of the data streams and indices you name."
public string? Body { get; init; }
}
/// One operation with its routes, versions and documented fields.
public sealed record ApiOperationResponse
{
+ /// The operation.
public required ApiOperationSummary Operation { get; init; }
+ /// The API versions that document the operation.
+ /// ["main"]
public required string[] Versions { get; init; }
+ /// Every documented parameter, header, and request and response field.
public required IReadOnlyList Fields { get; init; }
+ /// A one-sentence summary of the operation, generated by AI, when there is one.
+ /// "Check Elasticsearch cluster health status via API."
public string? AiShortSummary { get; init; }
+ /// The operation page's text; only with include_body=true.
+ /// "Returns the health status of a cluster, or of the data streams and indices you name."
public string? Body { get; init; }
+ /// The length of the page's text, also when it isn't included.
+ /// 3639
public int BodyLength { get; init; }
/// Set by callers that can tell the reader how to ask for an omitted body.
+ /// "The body is omitted by default. Call this tool again with includeBody=true to read it."
public string? BodyNote { get; init; }
+ /// Other operations the lookup matched.
public required IReadOnlyList OtherMatches { get; init; }
}
/// Every API with its key and versions.
public sealed record ApiListResponse
{
+ /// Every API, by key.
public required IReadOnlyList Apis { get; init; }
}
/// The operations of one API, by group.
public sealed record ApiOperationListResponse
{
+ /// The API key.
+ /// "elasticsearch"
public required string Api { get; init; }
+ /// The version read; null for the current one.
+ /// "9"
public string? Version { get; init; }
+ /// The number of operations counted.
+ /// 549
public required int TotalOperations { get; init; }
+ /// The API's groups, by name.
public required IReadOnlyList Groups { get; init; }
+ /// A hint about the reply, such as how to list a large API; null when there is none.
+ /// "This API has 549 operations. Pass group to list the operations of one group."
public string? Note { get; init; }
}
+/// A group of an API's operations.
public sealed record ApiOperationGroupDto
{
+ /// The group's name, such as Cluster.
+ /// "Cluster"
public required string Name { get; init; }
+ /// The number of operations in the group.
+ /// 20
public required int Count { get; init; }
+ /// The group's operations; null when only counts are asked for.
public IReadOnlyList? Operations { get; init; }
}
+/// An operation in a group listing.
public sealed record ApiOperationListItemDto
{
+ /// The operation's title.
+ /// "Get the cluster health status"
public required string Title { get; init; }
+ /// The operation's page on www.elastic.co.
+ /// "/docs/api/doc/elasticsearch/operation/operation-cluster-health"
public required string Url { get; init; }
+ /// The HTTP method of the operation's main route.
+ /// "GET"
public required string Method { get; init; }
+ /// The path of the operation's main route.
+ /// "/_cluster/health"
public required string Path { get; init; }
+ /// The operation id, unique within the API.
+ /// "cluster-health"
public required string OperationId { get; init; }
+ /// True when the spec marks the operation deprecated.
+ /// false
public bool Deprecated { get; init; }
}
diff --git a/src/services/search/Elastic.Documentation.Search/ApiReference/IApiGateway.cs b/src/services/search/Elastic.Documentation.Search/ApiReference/IApiGateway.cs
index 2f0007b97e..4110f628ae 100644
--- a/src/services/search/Elastic.Documentation.Search/ApiReference/IApiGateway.cs
+++ b/src/services/search/Elastic.Documentation.Search/ApiReference/IApiGateway.cs
@@ -44,20 +44,40 @@ public sealed record ApiOperationPage(long Total, IReadOnlyList
/// A search hit, with the request and response fields the query named.
public sealed record ApiOperationHit(ApiOperationSummary Operation, float Score, IReadOnlyList MatchedFields);
+/// An operation of an API, as API Explorer documents it.
public sealed record ApiOperationSummary
{
+ /// The key of the API the operation belongs to, such as elasticsearch.
+ /// "elasticsearch"
public required string Api { get; init; }
+ /// The operation's title.
+ /// "Get the cluster health status"
public required string Title { get; init; }
+ /// The operation's page on www.elastic.co.
+ /// "/docs/api/doc/elasticsearch/operation/operation-cluster-health"
public required string Url { get; init; }
+ /// What the operation does.
+ /// "You can also use the API to get the health status of only specified data streams and indices.\nFor data streams, the API retrieves the health status of the st…"
public string? Description { get; init; }
+ /// The HTTP method of the operation's main route.
+ /// "GET"
public required string Method { get; init; }
+ /// The path of the operation's main route, such as /_cluster/health/{index}.
+ /// "/_cluster/health/{index}"
public required string Path { get; init; }
+ /// The operation id from the API's spec, unique within the API.
+ /// "cluster-health"
public required string OperationId { get; init; }
+ /// The group the operation is listed under, such as Cluster.
+ /// "Cluster"
public string? Group { get; init; }
+ /// True when the spec marks the operation deprecated.
+ /// false
public bool Deprecated { get; init; }
/// Every route the page lists as METHOD /spec/path.
+ /// ["GET /_cluster/health/{index}", "GET /_cluster/health"]
public required string[] Endpoints { get; init; }
}
@@ -79,21 +99,41 @@ public sealed record ApiOperationDetail
/// A parameter, request body field or response field of an operation.
public sealed record ApiField
{
+ /// The field's name.
+ /// "index"
public required string Name { get; init; }
+ /// The field's dotted path, such as query.match.
+ /// "index"
public required string Path { get; init; }
+ /// The field's type, such as string or object.
+ /// "union string | string[]"
public required string Type { get; init; }
/// Where the field lives: path, query, header, request or response.
+ /// "path"
public required string Location { get; init; }
+ /// The field's description.
+ /// "A comma-separated list of data streams, indices, and index aliases that limit the request. Wildcard expressions () are supported. To target all data streams…"
public required string Description { get; init; }
}
+/// An API that API Explorer publishes.
public sealed record ApiSummary
{
+ /// The API key that the other requests take, such as elasticsearch.
+ /// "cloud"
public required string Key { get; init; }
+ /// The API's title.
+ /// "Elastic Cloud API"
public required string Title { get; init; }
+ /// The API's landing page on www.elastic.co.
+ /// "/docs/api/doc/cloud"
public required string Url { get; init; }
+ /// What the API is for.
+ /// "This RESTful API enables you to perform most of the operations available in the UI console through API calls."
public string? Description { get; init; }
+ /// The versions you can pass as version, such as main or 9.
+ /// ["main"]
public required string[] Versions { get; init; }
}
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 6c9733821f..a994ce03a0 100644
--- a/src/services/search/Elastic.Documentation.Search/Elastic.Documentation.Search.csproj
+++ b/src/services/search/Elastic.Documentation.Search/Elastic.Documentation.Search.csproj
@@ -1,6 +1,9 @@
+
+ true
+ $(NoWarn);CS1591
enable
enable
Elastic.Documentation.Search
diff --git a/src/services/search/Elastic.Documentation.Search/IChangesService.cs b/src/services/search/Elastic.Documentation.Search/IChangesService.cs
index 73c67703a0..d264370578 100644
--- a/src/services/search/Elastic.Documentation.Search/IChangesService.cs
+++ b/src/services/search/Elastic.Documentation.Search/IChangesService.cs
@@ -21,8 +21,13 @@ public record ChangesRequest
/// API response for the changes feed endpoint.
public record ChangesResponse
{
+ /// The changed pages in this batch.
public required IReadOnlyList Pages { get; init; }
+ /// True when more changed pages follow. Pass nextCursor as cursor to read them.
+ /// true
public required bool HasMore { get; init; }
+ /// The cursor of the next batch; null on the last one.
+ /// "WzE3OTQ4OTYyMTE3NzIsIi9kb2NzL3JlZmVyZW5jZS9vcGVudGVsZW1ldHJ5L2Vkb3Qtc2Rrcy9qYXZhL21pZ3JhdGlvbiJd"
public string? NextCursor { get; init; }
}
@@ -54,7 +59,13 @@ public static class ChangesDefaults
/// A single changed page in the API response.
public record ChangedPageDto
{
+ /// The page's path on www.elastic.co.
+ /// "/docs/reference/opentelemetry/edot-sdks/java/configuration"
public required string Url { get; init; }
+ /// The page title.
+ /// "Configure the EDOT Java agent"
public required string Title { get; init; }
+ /// When the page's content last changed.
+ /// "2026-11-17T06:16:51.7648902+00:00"
public required DateTimeOffset LastUpdated { get; init; }
}
diff --git a/src/services/search/Elastic.Documentation.Search/IFullSearchService.cs b/src/services/search/Elastic.Documentation.Search/IFullSearchService.cs
index 608d5e149b..969051c36c 100644
--- a/src/services/search/Elastic.Documentation.Search/IFullSearchService.cs
+++ b/src/services/search/Elastic.Documentation.Search/IFullSearchService.cs
@@ -35,12 +35,24 @@ public record FullSearchRequest
///
public record FullSearchResponse
{
+ /// The results on this page.
public required IReadOnlyList Results { get; init; }
+ /// Every result the query matches, across pages.
+ /// 314
public required int TotalResults { get; init; }
+ /// The page returned, from 1.
+ /// 1
public required int PageNumber { get; init; }
+ /// The number of results per page, from 1 to 50.
+ /// 1
public required int PageSize { get; init; }
+ /// Result counts by type, navigation section, deployment type and product, for building filters.
public FullSearchAggregations Aggregations { get; init; } = new();
+ /// True when the query also ran as a semantic search and both rankings were combined.
+ /// false
public bool IsSemanticQuery { get; init; }
+ /// The number of pages at this page size.
+ /// 314
public int PageCount => TotalResults > 0 ? (int)Math.Ceiling((double)TotalResults / PageSize) : 0;
}
@@ -60,9 +72,17 @@ public record FullSearchResult
///
public record FullSearchAggregations
{
+ /// Result counts by result type, such as docs or api.
+ /// {"docs": 306, "api": 8}
public IReadOnlyDictionary Type { get; init; } = new Dictionary();
+ /// Result counts by top-level navigation section, such as reference.
+ /// {"reference": 150, "deploy and manage": 78, "troubleshoot": 33}
public IReadOnlyDictionary NavigationSection { get; init; } = new Dictionary();
+ /// Result counts by the deployment types the pages apply to.
+ /// {}
public IReadOnlyDictionary DeploymentType { get; init; } = new Dictionary();
+ /// Result counts by product id, with each product's display name.
+ /// {"elastic docs": {"count": 155, "displayName": "elastic docs"}, "elasticsearch": {"count": 99, "displayName": "Elasticsearch"}, "cloud kubernetes": {"count": 62, "displayName": "cloud kubernetes"}}
public IReadOnlyDictionary Product
{
get;
@@ -75,7 +95,11 @@ public IReadOnlyDictionary Product
///
public record ProductAggregationBucket
{
+ /// The number of results for the product.
+ /// 155
public required long Count { get; init; }
+ /// The product's name for display.
+ /// "elastic docs"
public required string DisplayName { get; init; }
}
@@ -84,17 +108,38 @@ public record ProductAggregationBucket
///
public record FullSearchResultItem
{
+ /// docs for a documentation page, api for an API reference page.
+ /// "docs"
public required string Type { get; init; }
+ /// The page's path on www.elastic.co, such as /docs/deploy-manage.
+ /// "/docs/troubleshoot/elasticsearch/red-yellow-cluster-status"
public required string Url { get; init; }
+ /// The page title, with matched words in <mark> tags.
+ /// "Red or yellow <mark>cluster</mark> <mark>health</mark> status"
public required string Title { get; init; }
+ /// A passage of the page, with matched words in <mark> tags.
+ /// "and cleanup activities until the <mark>cluster</mark> returns to green <mark>health</mark> status. In many cases, your <mark>cluster</mark> will recover to g…"
public required string Description { get; init; }
+ /// The page's breadcrumb, from the docs root down.
public required FullSearchResultParent[] Parents { get; init; }
+ /// The relevance score. Compare it only within one response.
+ /// 4.7976103
public float Score { get; init; }
+ /// A one-sentence summary of the page, generated by AI, when there is one.
+ /// "Fix red or yellow Elasticsearch cluster health status."
public string? AiShortSummary { get; init; }
+ /// A longer AI-generated summary of the page, written for answer generation, when there is one.
+ /// "A red Elasticsearch cluster health status indicates unassigned primary shards causing potential search and indexing failures, while yellow status means unass…"
public string? AiRagOptimizedSummary { get; init; }
+ /// The top-level navigation section the page is in.
+ /// "troubleshoot"
public string? NavigationSection { get; init; }
+ /// When the page's content last changed.
+ /// "2026-11-17T19:20:53.9554741+00:00"
public DateTimeOffset? LastUpdated { get; init; }
+ /// The product the page is about.
public FullSearchProduct? Product { get; init; }
+ /// Other products the page applies to.
public FullSearchProduct[]? RelatedProducts { get; init; }
}
@@ -103,7 +148,11 @@ public record FullSearchResultItem
///
public record FullSearchProduct
{
+ /// The product id, such as elasticsearch.
+ /// "elasticsearch"
public required string Id { get; init; }
+ /// The product's name for display.
+ /// "Elasticsearch"
public required string DisplayName { get; init; }
}
@@ -112,6 +161,10 @@ public record FullSearchProduct
///
public record FullSearchResultParent
{
+ /// The parent page's title.
+ /// "Docs"
public required string Title { get; init; }
+ /// The parent page's path.
+ /// "/docs"
public required string Url { get; init; }
}
diff --git a/src/services/search/Elastic.Documentation.Search/INavigationSearchService.cs b/src/services/search/Elastic.Documentation.Search/INavigationSearchService.cs
index 032c82055e..e94801e697 100644
--- a/src/services/search/Elastic.Documentation.Search/INavigationSearchService.cs
+++ b/src/services/search/Elastic.Documentation.Search/INavigationSearchService.cs
@@ -22,18 +22,32 @@ public record NavigationSearchRequest
public ApiPageContext? ApiPage { get; init; }
}
+/// Pages and API operations whose title or navigation entry matches the query.
public record NavigationSearchResponse
{
+ /// The results on this page.
public required IEnumerable Results { get; init; }
+ /// Every result the query matches, across pages.
+ /// 314
public required int TotalResults { get; init; }
+ /// The page returned, from 1.
+ /// 1
public required int PageNumber { get; init; }
+ /// The number of results per page.
+ /// 20
public required int PageSize { get; init; }
+ /// Result counts by type, for building filters.
public NavigationSearchAggregations Aggregations { get; init; } = new();
+ /// The number of pages at this page size.
+ /// 16
public int PageCount => TotalResults > 0 ? (int)Math.Ceiling((double)TotalResults / PageSize) : 0;
}
+/// Result counts for building filters.
public record NavigationSearchAggregations
{
+ /// Result counts by result type, such as docs or api.
+ /// {"docs": 306, "api": 8}
public IReadOnlyDictionary Type { get; init; } = new Dictionary();
}
@@ -44,45 +58,82 @@ public record NavigationSearchResult
public IReadOnlyDictionary Aggregations { get; init; } = new Dictionary();
}
+/// One step of a result's breadcrumb.
public record NavigationSearchResultItemParent
{
+ /// The parent page's title.
+ /// "Docs"
public required string Title { get; init; }
+ /// The parent page's path.
+ /// "/docs"
public required string Url { get; init; }
}
+/// A page or an API operation that matches the query.
public record NavigationSearchResultItem
{
+ /// The operation's request and response fields that match the query; empty for a docs page.
public NavigationSearchProperty[] Properties { get; init; } = [];
/// The operation's routes with their methods; empty for a docs page.
public ApiRouteEntry[] Routes { get; init; } = [];
/// True when the result is an API operation the spec marks deprecated; false for a docs page.
+ /// false
public bool Deprecated { get; init; }
/// True when the result is an API's landing page, which has no operation.
+ /// false
public bool Landing { get; init; }
/// Key of the API the result belongs to, e.g. kibana; null for a docs page.
+ /// "elasticsearch"
public string? ApiKey { get; init; }
/// Product id the page was inferred to, e.g. cloud-hosted. Picks the landing row's icon, as it does on the catalog.
+ /// "elasticsearch"
public string? Product { get; init; }
+ /// docs for a documentation page, api for an API reference page.
+ /// "docs"
public required string Type { get; init; }
+ /// The page's path on www.elastic.co.
+ /// "/docs/troubleshoot/elasticsearch/red-yellow-cluster-status"
public required string Url { get; init; }
+ /// The page title, with matched words in <mark> tags.
+ /// "Red or yellow <mark>cluster</mark> <mark>health</mark> status"
public required string Title { get; init; }
+ /// A passage of the page, with matched words in <mark> tags.
+ /// "and cleanup activities until the <mark>cluster</mark> returns to green <mark>health</mark> status. In many cases, your <mark>cluster</mark> will recover to g…"
public required string Description { get; init; }
+ /// The page's breadcrumb, from the docs root down.
public required NavigationSearchResultItemParent[] Parents { get; init; }
+ /// The relevance score. Compare it only within one response.
+ /// 4.7976103
public float Score { get; init; }
}
+/// A request or response field of an API operation that matches the query.
public record NavigationSearchProperty
{
+ /// The field name.
+ /// "wait_for_status"
public required string Name { get; init; }
+ /// The field's dotted path, such as query.match.
+ /// "wait_for_status"
public required string Path { get; init; }
+ /// The field's type, such as string or object.
+ /// "enum"
public required string Type { get; init; }
+ /// The field's description.
+ /// "Wait (until the timeout expires) for the cluster to reach a specific health status (or a better status)."
public required string Description { get; init; }
+ /// The field's anchor on the operation page.
+ /// "query-wait_for_status"
public required string Anchor { get; init; }
+ /// Where the field is: path, query, header, request or response.
+ /// "query"
public required string Location { get; init; }
+ /// The operation page, with the field's anchor.
+ /// "/docs/api/doc/elasticsearch/operation/operation-cluster-health#query-wait_for_status"
public required string Url { get; init; }
}
diff --git a/tests/Elastic.ApiExplorer.Tests/ExampleScenarioTests.cs b/tests/Elastic.ApiExplorer.Tests/ExampleScenarioTests.cs
index 5f037bf515..35fb47b9e4 100644
--- a/tests/Elastic.ApiExplorer.Tests/ExampleScenarioTests.cs
+++ b/tests/Elastic.ApiExplorer.Tests/ExampleScenarioTests.cs
@@ -77,6 +77,77 @@ public void BuildExampleScenarios_LabelledSampleBecomesItsOwnExampleSharingTheRe
scenarios[1].Responses.Should().HaveCount(scenarios[0].Responses.Count);
}
+ [Test]
+ public void BuildExampleScenarios_ResponseOnlyExamplesThatSamplesName_KeepTheirOwnResponses()
+ {
+ // A GET has no request examples; its samples, one per example, are what tells the examples apart.
+ ExampleDisplay[] responses =
+ [
+ new("Search an API", null, /*lang=json,strict*/ """{"results":["search"]}""", null, "200"),
+ new("Look up an endpoint", null, /*lang=json,strict*/ """{"results":["endpoint"]}""", null, "200"),
+ new("List a group", null, /*lang=json,strict*/ """{"results":["group"]}""", null, "200")
+ ];
+ CodeSample[] samples =
+ [
+ new("curl", "curl '/x?q=health'", "language-curl") { ExampleTitle = "Search an API" },
+ new("curl", "curl '/x?endpoint=GET%20/_cluster/health'", "language-curl") { ExampleTitle = "Look up an endpoint" },
+ new("curl", "curl '/x?group=Cluster'", "language-curl") { ExampleTitle = "List a group" }
+ ];
+
+ var scenarios = OperationPageModel.BuildExampleScenarios([], responses, samples);
+
+ scenarios.Select(s => s.Title).Should().Equal("Search an API", "Look up an endpoint", "List a group");
+ scenarios
+ .Select(s => s.Responses.Should().ContainSingle().Subject.Examples.Should().ContainSingle().Subject.JsonValue)
+ .Should()
+ .Equal("""{"results":["search"]}""", """{"results":["endpoint"]}""", """{"results":["group"]}""");
+ scenarios
+ .Select(s => s.CodeSamples.Should().ContainSingle().Subject.Source)
+ .Should()
+ .Equal("curl '/x?q=health'", "curl '/x?endpoint=GET%20/_cluster/health'", "curl '/x?group=Cluster'");
+ }
+
+ [Test]
+ public void BuildExampleScenarios_ResponseOnlyExamplesThatSamplesName_ShareTheUnnamedErrorStatuses()
+ {
+ ExampleDisplay[] responses =
+ [
+ new("Search an API", null, /*lang=json,strict*/ """{"results":["search"]}""", null, "200"),
+ new("Look up an endpoint", null, /*lang=json,strict*/ """{"results":["endpoint"]}""", null, "200"),
+ new("400", null, /*lang=json,strict*/ """{"status":400}""", null, "400"),
+ new("404", null, /*lang=json,strict*/ """{"status":404}""", null, "404")
+ ];
+ CodeSample[] samples =
+ [
+ new("curl", "curl '/x?q=health'", "language-curl") { ExampleTitle = "Search an API" },
+ new("curl", "curl '/x?endpoint=GET%20/_cluster/health'", "language-curl") { ExampleTitle = "Look up an endpoint" }
+ ];
+
+ var scenarios = OperationPageModel.BuildExampleScenarios([], responses, samples);
+
+ scenarios.Select(s => s.Title).Should().Equal("Search an API", "Look up an endpoint");
+ scenarios
+ .Select(s => s.Responses.Single(r => r.StatusCode == "200").Examples.Should().ContainSingle().Subject.JsonValue)
+ .Should()
+ .Equal("""{"results":["search"]}""", """{"results":["endpoint"]}""");
+ scenarios.Should().AllSatisfy(s => s.Responses.Select(r => r.StatusCode).Should().Equal("200", "400", "404"));
+ }
+
+ [Test]
+ public void BuildExampleScenarios_ResponseOnlyExamplesNoSampleNames_ShowAsOneExample()
+ {
+ ExampleDisplay[] responses =
+ [
+ new("First", null, /*lang=json,strict*/ """{"r":1}""", null, "200"),
+ new("Second", null, /*lang=json,strict*/ """{"r":2}""", null, "200")
+ ];
+ CodeSample[] samples = [new("curl", "curl '/x'", "language-curl")];
+
+ var scenarios = OperationPageModel.BuildExampleScenarios([], responses, samples);
+
+ scenarios.Should().ContainSingle();
+ }
+
[Test]
public void BuildExampleScenarios_SuffixMatchesTheHumanizedKeyOfAnExampleWithoutSummary()
{
diff --git a/tests/Elastic.Documentation.Api.Tests/OpenApiDescriptionsTests.cs b/tests/Elastic.Documentation.Api.Tests/OpenApiDescriptionsTests.cs
new file mode 100644
index 0000000000..cd95253c1a
--- /dev/null
+++ b/tests/Elastic.Documentation.Api.Tests/OpenApiDescriptionsTests.cs
@@ -0,0 +1,145 @@
+// 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.Net;
+using System.Text.Json;
+using AwesomeAssertions;
+using Elastic.Documentation.Api.Tests.Fixtures;
+
+namespace Elastic.Documentation.Api.Tests;
+
+/// Everything a reader of the OpenAPI document sees has a description, so a new field or endpoint can't ship without one.
+public class OpenApiDescriptionsTests
+{
+ private static readonly Lazy SharedFactory = new(() => new ApiWebApplicationFactory());
+
+ [After(Class)]
+ public static void DisposeSharedFactory()
+ {
+ if (SharedFactory.IsValueCreated)
+ SharedFactory.Value.Dispose();
+ }
+
+ // What ASP.NET writes when nothing describes a response.
+ private static readonly string[] StatusPhrases =
+ [
+ "OK",
+ "No Content",
+ "Bad Request",
+ "Not Found",
+ "Internal Server Error",
+ "Service Unavailable"
+ ];
+
+ private static async Task Document()
+ {
+ using var client = SharedFactory.Value.CreateClient();
+ using var response = await client.GetAsync("/docs/_api/v1/openapi.json", TestContext.Current!.Execution.CancellationToken);
+ response.StatusCode.Should().Be(HttpStatusCode.OK);
+ return JsonElement.Parse(await response.Content.ReadAsStringAsync(TestContext.Current!.Execution.CancellationToken));
+ }
+
+ private static bool Described(JsonElement element) =>
+ element.TryGetProperty("description", out var description) && !string.IsNullOrWhiteSpace(description.GetString());
+
+ // A nullable reference is written as oneOf [null, {$ref, description}].
+ private static bool DescribedProperty(JsonElement property) =>
+ Described(property) || (property.TryGetProperty("oneOf", out var branches) && branches.EnumerateArray().Any(Described));
+
+ [Test]
+ public async Task EveryOperationParameterResponseAndTag_IsDescribed()
+ {
+ var document = await Document();
+ var missing = new List();
+ foreach (var path in document.GetProperty("paths").EnumerateObject())
+ {
+ foreach (var operation in path.Value.EnumerateObject().Where(o => o.Name is "get" or "post" or "put" or "delete"))
+ {
+ var name = $"{operation.Name.ToUpperInvariant()} {path.Name}";
+ if (!Described(operation.Value))
+ missing.Add(name);
+ foreach (var parameter in operation.Value.TryGetProperty("parameters", out var parameters)
+ ? parameters.EnumerateArray()
+ : [])
+ {
+ if (!Described(parameter))
+ missing.Add($"{name} parameter {parameter.GetProperty("name").GetString()}");
+ }
+ foreach (var response in operation.Value.GetProperty("responses").EnumerateObject())
+ {
+ if (StatusPhrases.Contains(response.Value.GetProperty("description").GetString()))
+ missing.Add($"{name} response {response.Name}");
+ }
+ }
+ }
+ missing.AddRange(
+ document.GetProperty("tags").EnumerateArray().Where(t => !Described(t)).Select(t => $"tag {t.GetProperty("name").GetString()}")
+ );
+
+ missing.Should().BeEmpty();
+ }
+
+ private static bool HasExample(JsonElement element) =>
+ element.TryGetProperty("example", out _) || (element.TryGetProperty("examples", out var examples) && examples.GetArrayLength() > 0);
+
+ // A property that points to another schema gets its example from that schema's own fields.
+ private static bool IsReference(JsonElement property) =>
+ property.TryGetProperty("$ref", out _)
+ || (property.TryGetProperty("oneOf", out var branches) && branches.EnumerateArray().Any(b => b.TryGetProperty("$ref", out _)))
+ || (property.TryGetProperty("items", out var items) && items.TryGetProperty("$ref", out _))
+ || (property.TryGetProperty("additionalProperties", out var values)
+ && values.ValueKind == JsonValueKind.Object
+ && values.TryGetProperty("$ref", out _));
+
+ [Test]
+ public async Task EveryFieldAndParameter_HasAnExample()
+ {
+ var document = await Document();
+ var missing = new List();
+ foreach (var schema in document.GetProperty("components").GetProperty("schemas").EnumerateObject())
+ {
+ foreach (var property in schema.Value.TryGetProperty("properties", out var properties) ? properties.EnumerateObject() : [])
+ {
+ if (!IsReference(property.Value) && !HasExample(property.Value))
+ missing.Add($"{schema.Name}.{property.Name}");
+ }
+ }
+ foreach (var path in document.GetProperty("paths").EnumerateObject())
+ {
+ foreach (var operation in path.Value.EnumerateObject().Where(o => o.Name is "get" or "post" or "put" or "delete"))
+ {
+ foreach (var parameter in operation.Value.TryGetProperty("parameters", out var parameters)
+ ? parameters.EnumerateArray()
+ : [])
+ {
+ if (!HasExample(parameter))
+ missing.Add(
+ $"{operation.Name.ToUpperInvariant()} {path.Name} parameter {parameter.GetProperty("name").GetString()}"
+ );
+ }
+ }
+ }
+
+ missing.Should().BeEmpty();
+ }
+
+ [Test]
+ public async Task EverySchemaAndProperty_IsDescribed()
+ {
+ var document = await Document();
+ var missing = new List();
+ foreach (var schema in document.GetProperty("components").GetProperty("schemas").EnumerateObject())
+ {
+ if (!Described(schema.Value))
+ missing.Add(schema.Name);
+ foreach (var property in schema.Value.TryGetProperty("properties", out var properties) ? properties.EnumerateObject() : [])
+ {
+ if (!DescribedProperty(property.Value))
+ missing.Add($"{schema.Name}.{property.Name}");
+ }
+ }
+
+ missing.Should().BeEmpty();
+ }
+}
diff --git a/tests/Elastic.Documentation.Api.Tests/OpenApiDocumentTests.cs b/tests/Elastic.Documentation.Api.Tests/OpenApiDocumentTests.cs
index 3cc492a413..0124cb9ea9 100644
--- a/tests/Elastic.Documentation.Api.Tests/OpenApiDocumentTests.cs
+++ b/tests/Elastic.Documentation.Api.Tests/OpenApiDocumentTests.cs
@@ -120,7 +120,8 @@ public async Task Document_NamesTheApiAndThePublicServer()
var document = await Document();
document.GetProperty("info").GetProperty("title").GetString().Should().Be("Elastic Docs API");
- document.GetProperty("info").GetProperty("description").GetString().Should().Contain("feature_search_or_askai_enabled=true");
+ // The CDN no longer gates the API behind a cookie, so the description names none.
+ document.GetProperty("info").GetProperty("description").GetString().Should().NotContainEquivalentOf("cookie");
document.GetProperty("servers")[0].GetProperty("url").GetString().Should().Be("https://www.elastic.co");
}
}
diff --git a/tests/Elastic.Documentation.Api.Tests/OpenApiExamplesTests.cs b/tests/Elastic.Documentation.Api.Tests/OpenApiExamplesTests.cs
new file mode 100644
index 0000000000..790d3eec60
--- /dev/null
+++ b/tests/Elastic.Documentation.Api.Tests/OpenApiExamplesTests.cs
@@ -0,0 +1,288 @@
+// 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.Net;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using AwesomeAssertions;
+using Elastic.Documentation.Api.AskAi;
+using Elastic.Documentation.Api.OpenApi;
+using Elastic.Documentation.Api.PageFeedback;
+using Elastic.Documentation.Api.Tests.Fixtures;
+using Elastic.Documentation.Search;
+using Elastic.Documentation.Search.ApiReference;
+
+namespace Elastic.Documentation.Api.Tests;
+
+/// The examples in the OpenAPI document must stay true to the API they describe.
+public class OpenApiExamplesTests
+{
+ private static readonly Lazy SharedFactory = new(() => new ApiWebApplicationFactory());
+
+ [After(Class)]
+ public static void DisposeSharedFactory()
+ {
+ if (SharedFactory.IsValueCreated)
+ SharedFactory.Value.Dispose();
+ }
+
+ // The type each operation answers with on success.
+ private static readonly Dictionary ResponseTypes = new(StringComparer.Ordinal)
+ {
+ ["search"] = typeof(FullSearchResponse),
+ ["navigation-search"] = typeof(NavigationSearchResponse),
+ ["list-changes"] = typeof(ChangesResponse),
+ ["list-apis"] = typeof(ApiListResponse),
+ ["get-api"] = typeof(ApiSummary),
+ ["list-api-groups"] = typeof(ApiOperationListResponse),
+ ["list-api-operations"] = typeof(ApiOperationCollectionResponse),
+ ["get-api-operation"] = typeof(ApiOperationResponse)
+ };
+
+ private static readonly Dictionary RequestTypes = new(StringComparer.Ordinal)
+ {
+ ["ask-ai-stream"] = typeof(AskAiRequest),
+ ["ask-ai-message-feedback"] = typeof(AskAiMessageFeedbackRequest),
+ ["put-page-feedback"] = typeof(PageFeedbackRequest)
+ };
+
+ // The API's own JSON options, refusing a property its types don't have, so an example can't carry a stale field.
+ private static readonly JsonSerializerOptions Strict = new(ApiJsonContext.Default.Options)
+ {
+ UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow
+ };
+
+ private static async Task> Operations()
+ {
+ using var client = SharedFactory.Value.CreateClient();
+ using var response = await client.GetAsync("/docs/_api/v1/openapi.json", TestContext.Current!.Execution.CancellationToken);
+ response.StatusCode.Should().Be(HttpStatusCode.OK);
+ var document = JsonElement.Parse(await response.Content.ReadAsStringAsync(TestContext.Current!.Execution.CancellationToken));
+ return [
+ .. document
+ .GetProperty("paths")
+ .EnumerateObject()
+ .SelectMany(
+ path => path
+ .Value
+ .EnumerateObject()
+ .Where(op => op.Name is "get" or "post" or "put" or "delete")
+ .Select(op => (op.Name.ToUpperInvariant(), path.Name, op.Value))
+ )
+ ];
+ }
+
+ private static IEnumerable ExamplesOf(JsonElement media) =>
+ media.TryGetProperty("example", out var example)
+ ? [example]
+ : media.TryGetProperty("examples", out var examples) ? examples.EnumerateObject().Select(e => e.Value.GetProperty("value")) : [];
+
+ [Test]
+ public async Task EveryOperation_HasACurlSampleForItsOwnRoute()
+ {
+ foreach (var (method, path, operation) in await Operations())
+ {
+ var samples = operation.GetProperty("x-codeSamples").EnumerateArray().ToList();
+ var curls = samples
+ .Where(s => s.GetProperty("lang").GetString() == "curl")
+ .Select(s => s.GetProperty("source").GetString()!)
+ .ToList();
+ curls.Should().NotBeEmpty(path);
+
+ // The route template, with each {parameter} as one segment, against the public server.
+ var route = new System.Text.RegularExpressions.Regex(
+ "^curl" + (method == "GET" ? "" : $" -X {method}") + " '" + System
+ .Text
+ .RegularExpressions
+ .Regex
+ .Escape(ApiExamples.Server) + System
+ .Text
+ .RegularExpressions
+ .Regex
+ .Replace(System.Text.RegularExpressions.Regex.Escape(path), @"\\\{[^/]+?}", "[^/?']+") + @"(\?[^']*)?'"
+ );
+ curls.Should().AllSatisfy(curl => route.IsMatch(curl).Should().BeTrue($"{curl} calls {method} {path}"));
+ }
+ }
+
+ [Test]
+ public async Task EveryResponseExample_ReadsAsItsOperationsResponseType()
+ {
+ var checkedOperations = new List();
+ foreach (var (_, _, operation) in await Operations())
+ {
+ var id = operation.GetProperty("operationId").GetString()!;
+ if (
+ !operation.GetProperty("responses").TryGetProperty("200", out var ok)
+ || !ok.TryGetProperty("content", out var content)
+ || !content.TryGetProperty("application/json", out var media)
+ )
+ continue;
+
+ ResponseTypes.Should().ContainKey(id, "every JSON response needs an example type to check it against");
+ var examples = ExamplesOf(media).ToList();
+ examples.Should().NotBeEmpty(id);
+ foreach (var example in examples)
+ {
+ var read = () => example.Deserialize(Strict.GetTypeInfo(ResponseTypes[id]));
+ read.Should().NotThrow($"the {id} example must match {ResponseTypes[id].Name}").Which.Should().NotBeNull();
+ }
+ checkedOperations.Add(id);
+ }
+ checkedOperations.Should().BeEquivalentTo(ResponseTypes.Keys);
+ }
+
+ [Test]
+ public async Task EveryRequestBodyExample_ReadsAsItsRequestType()
+ {
+ var checkedOperations = new List();
+ foreach (var (_, _, operation) in await Operations())
+ {
+ if (!operation.TryGetProperty("requestBody", out var body))
+ continue;
+ var id = operation.GetProperty("operationId").GetString()!;
+ var example = body.GetProperty("content").GetProperty("application/json").GetProperty("example");
+ var read = () => example.Deserialize(Strict.GetTypeInfo(RequestTypes[id]));
+ read.Should().NotThrow($"the {id} body must match {RequestTypes[id].Name}");
+ checkedOperations.Add(id);
+ }
+ checkedOperations.Should().BeEquivalentTo(RequestTypes.Keys);
+ }
+
+ [Test]
+ public async Task AskAiStreamExample_IsServerSentEventsTheApiWrites()
+ {
+ var stream =
+ (await Operations())
+ .Single(o => o.Operation.GetProperty("operationId").GetString() == "ask-ai-stream")
+ .Operation
+ .GetProperty("responses")
+ .GetProperty("200")
+ .GetProperty("content")
+ .GetProperty("text/event-stream")
+ .GetProperty("example")
+ .GetString()!;
+
+ var events = stream.Split("\n\n", StringSplitOptions.RemoveEmptyEntries);
+ events.Should().NotBeEmpty();
+ events.Should().AllSatisfy(e => e.Should().StartWith("data: "));
+ var parsed = events.Select(
+ e => JsonSerializer.Deserialize(e["data: ".Length..], AskAiEventJsonContext.Default.AskAiEvent)
+ ).ToList();
+ parsed[0].Should().BeOfType();
+ parsed[^1].Should().BeOfType();
+ }
+
+ [Test]
+ public async Task EveryErrorExample_IsAProblemOfThisApiWithItsStatus()
+ {
+ foreach (var (_, path, operation) in await Operations())
+ {
+ foreach (var response in operation.GetProperty("responses").EnumerateObject().Where(r => r.Name[0] is '4' or '5'))
+ {
+ var problem = response.Value.GetProperty("content").GetProperty("application/problem+json").GetProperty("example");
+ problem.GetProperty("type").GetString().Should().StartWith(ApiProblems.TypeUri(""), path);
+ problem
+ .GetProperty("status")
+ .GetInt32()
+ .Should()
+ .Be(int.Parse(response.Name, System.Globalization.CultureInfo.InvariantCulture), path);
+ }
+ }
+ }
+
+ private static JsonElement ProblemExample(
+ IReadOnlyList<(string Method, string Path, JsonElement Operation)> operations,
+ string operationId,
+ string status
+ ) =>
+ operations
+ .Single(o => o.Operation.GetProperty("operationId").GetString() == operationId)
+ .Operation
+ .GetProperty("responses")
+ .GetProperty(status)
+ .GetProperty("content")
+ .GetProperty("application/problem+json")
+ .GetProperty("example");
+
+ [Test]
+ [Arguments("put-page-feedback", "503", "feedback-unavailable")]
+ [Arguments("delete-page-feedback", "503", "feedback-unavailable")]
+ [Arguments("ask-ai-message-feedback", "503", "feedback-unavailable")]
+ [Arguments("search", "503", "search-unavailable")]
+ [Arguments("get-api-operation", "404", "operation-not-found")]
+ [Arguments("get-api", "404", "api-not-found")]
+ [Arguments("list-api-operations", "404", "api-not-found")]
+ public async Task ErrorExamples_ShowTheTypeTheOperationReturns(string operationId, string status, string type)
+ {
+ var problem = ProblemExample(await Operations(), operationId, status);
+
+ problem.GetProperty("type").GetString().Should().Be(ApiProblems.TypeUri(type));
+ problem.GetProperty("title").GetString().Should().Be(ApiProblems.TitleOf(type));
+ }
+
+ [Test]
+ public async Task SearchBadRequestExample_IsWhatTheApiAnswersWithoutAQuery()
+ {
+ var example = ProblemExample(await Operations(), "search", "400");
+ using var client = SharedFactory.Value.CreateClient();
+
+ using var response = await client.GetAsync("/docs/_api/v1/search", TestContext.Current!.Execution.CancellationToken);
+
+ response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
+ var actual = JsonElement.Parse(await response.Content.ReadAsStringAsync(TestContext.Current!.Execution.CancellationToken));
+ actual.GetProperty("type").GetString().Should().Be(example.GetProperty("type").GetString());
+ actual.GetProperty("detail").GetString().Should().Be(example.GetProperty("detail").GetString());
+ }
+
+ [Test]
+ public async Task CurlSamples_SendNoCookie()
+ {
+ var curls = (await Operations())
+ .SelectMany(o => o.Operation.GetProperty("x-codeSamples").EnumerateArray())
+ .Where(s => s.GetProperty("lang").GetString() == "curl")
+ .Select(s => s.GetProperty("source").GetString());
+
+ // The CDN no longer gates the API behind a cookie (elastic/docs-infra#523).
+ curls.Should().AllSatisfy(curl => curl.Should().NotContain(" -b ").And.NotContainEquivalentOf("cookie"));
+ }
+
+ [Test]
+ [Arguments("search", "q", "cluster health")]
+ [Arguments("get-api-operation", "operationId", "cluster-health")]
+ [Arguments("put-page-feedback", "feedbackId", "4f9d2c1a-7b3e-4c6d-9a8f-2e1b0c5d7a63")]
+ public async Task Parameters_TakeTheirExampleFromTheFirstExampleRequest(string operationId, string parameter, string value)
+ {
+ var operation = (await Operations()).Single(o => o.Operation.GetProperty("operationId").GetString() == operationId).Operation;
+
+ operation
+ .GetProperty("parameters")
+ .EnumerateArray()
+ .Single(p => p.GetProperty("name").GetString() == parameter)
+ .GetProperty("example")
+ .GetString()
+ .Should()
+ .Be(value);
+ }
+
+ [Test]
+ public async Task ReleasedCliCommands_AreSamplesOfTheirOperation()
+ {
+ var operations = await Operations();
+
+ string? Cli(string id) =>
+ operations
+ .Single(o => o.Operation.GetProperty("operationId").GetString() == id)
+ .Operation
+ .GetProperty("x-codeSamples")
+ .EnumerateArray()
+ .SingleOrDefault(s => s.GetProperty("label").GetString() == "Elastic CLI") is { ValueKind: JsonValueKind.Object } s
+ ? s.GetProperty("source").GetString()
+ : null;
+
+ Cli("search").Should().Be("elastic docs search \"cluster health\"");
+ Cli("ask-ai-stream").Should().StartWith("elastic docs ask ");
+ Cli("list-api-operations").Should().BeNull("elastic docs api is not released yet");
+ }
+}