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
Original file line number Diff line number Diff line change
Expand Up @@ -163,9 +163,7 @@ public async Task<AutocompleteResponse<TDocument>> AutocompleteAsync(Autocomplet
var options = new HighlightOptions
{
ApiLookup = apiLookup,
ListChildren = apiLookup
? ApiLookupQueryBuilder.ExpandsChildren(request.Query)
: SearchQueryBuilder.ExpandsChildren(request.Query, request.TypeFilter)
ListChildren = apiLookup && ApiLookupQueryBuilder.ExpandsChildren(request.Query)
};
var results = response
.Hits
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ public static bool IsApiPropertyHits(string innerHitsName) =>
StringComparer.OrdinalIgnoreCase
);
private static readonly string[] ApiPropertySourceIncludes = [$"{QueryFieldNames.ApiProperties}.*"];
private static readonly PropertyLookup DocsWideLookup = new(AllowPrefix: false, ExpandChildren: false);

/// <summary>
/// Rank-feature and term boosts applied as <c>should</c> clauses on top of the base query.
Expand All @@ -72,22 +73,16 @@ public static bool IsApiPropertyHits(string innerHitsName) =>

/// <summary>The nested field query for the query's first reading, see <see cref="ParseApiPropertyQuery"/>.</summary>
public static Query? BuildApiPropertyQuery(string searchQuery, string? typeFilter) =>
ParseApiPropertyQuery(searchQuery, typeFilter) is { Readings: [var first, ..] } parsed
? BuildNestedPropertyQuery(first.Property, ApiPropertyHits, Lookup(parsed, typeFilter))
ParseApiPropertyQuery(searchQuery, typeFilter) is { Readings: [var first, ..] }
? BuildNestedPropertyQuery(first.Property, ApiPropertyHits, DocsWideLookup)
: null;

/// <summary>A trailing dot on an API-filtered field, as in <c>retriever.</c>, asks for its children.</summary>
public static bool ExpandsChildren(string searchQuery, string? typeFilter) =>
Lookup(ParseApiPropertyQuery(searchQuery, typeFilter), typeFilter).ExpandChildren;

private static bool IsApiLookup(string? typeFilter) => typeFilter == "api";

public static Query ApplyApiPropertyQuery(Query query, string searchQuery, string? typeFilter)
{
var parsed = ParseApiPropertyQuery(searchQuery, typeFilter);
var branches = parsed
.Readings
.Select((r, i) => BuildReadingQuery(r, InnerHitsName(i), parsed.EndpointRequired, Lookup(parsed, typeFilter)))
.Select((r, i) => BuildReadingQuery(r, InnerHitsName(i), parsed.EndpointRequired))
.OfType<Query>()
.ToList();
if (branches.Count == 0)
Expand All @@ -97,14 +92,9 @@ public static Query ApplyApiPropertyQuery(Query query, string searchQuery, strin
return new BoolQuery { Should = [query, properties], MinimumShouldMatch = 1, Filter = [DocumentFilter] };
}

private static Query? BuildReadingQuery(
(string Operation, string Property) reading,
string innerHitsName,
bool endpointRequired,
PropertyLookup lookup
)
private static Query? BuildReadingQuery((string Operation, string Property) reading, string innerHitsName, bool endpointRequired)
{
var properties = BuildNestedPropertyQuery(reading.Property, innerHitsName, lookup);
var properties = BuildNestedPropertyQuery(reading.Property, innerHitsName, DocsWideLookup);
var endpoint = reading.Operation.Length == 0 ? null : BuildEndpointHalfQuery(reading.Operation);
if (endpoint is null && endpointRequired)
return null;
Expand All @@ -113,10 +103,8 @@ PropertyLookup lookup
// branch alone matched carries no name. The name sits on the whole reading, as Elasticsearch reports a named
// clause that matched even when its parent did not.
List<Query> must = endpoint is not null && endpointRequired ? [properties, endpoint] : [properties];
List<Query> should = endpoint is not null && !endpointRequired ? [endpoint] : [];
if (lookup.AllowPrefix)
should.Add(BuildListsFieldsUnderTypedPathBoost(reading.Property));
return new BoolQuery { Must = must, Should = should.Count == 0 ? null : should, QueryName = innerHitsName };
List<Query>? should = endpoint is not null && !endpointRequired ? [endpoint] : null;
return new BoolQuery { Must = must, Should = should, QueryName = innerHitsName };
}

/// <summary>
Expand Down Expand Up @@ -160,15 +148,13 @@ private static TermQuery BuildParentTermQuery(string typedPath) =>
private static ApiPropertyReadings ParseApiPropertyQuery(string searchQuery, string? typeFilter)
{
var input = searchQuery.Trim();
if (input.Length == 0 || typeFilter is not (null or "" or "all" or "api"))
if (input.Length == 0 || typeFilter is not (null or "" or "all"))
return ApiPropertyReadings.None;
var parsed = WithoutTrailingDots(ParseReadings(input.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)));
// The docs-wide search only tries a field word that looks like an identifier; a plain word would lift every
// API operation that happens to have a field of that name above the pages about it. Dropping a reading
// leaves the others as demanding as the query made them.
return IsApiLookup(typeFilter)
? parsed
: parsed with { Readings = parsed.Readings.Where(r => r.Property.Contains('.') || r.Property.Contains('_')).ToArray() };
return parsed with { Readings = parsed.Readings.Where(r => r.Property.Contains('.') || r.Property.Contains('_')).ToArray() };
}

private static ApiPropertyReadings ParseReadings(string[] words)
Expand All @@ -195,27 +181,18 @@ private static ApiPropertyReadings WithoutTrailingDots(ApiPropertyReadings parse
.Select(r => r with { Property = r.Property.TrimEnd('.') })
.Where(r => r.Property.Length > 0)
.ToArray();
return readings.Length == 0
? ApiPropertyReadings.None
: parsed with { Readings = readings, ExpandsChildren = parsed.Readings.Any(r => r.Property.EndsWith('.')) };
return readings.Length == 0 ? ApiPropertyReadings.None : parsed with { Readings = readings };
}

/// <summary>The readings of a query, and whether each must match its endpoint rather than only be lifted by it.</summary>
private sealed record ApiPropertyReadings(IReadOnlyList<(string Operation, string Property)> Readings, bool EndpointRequired)
{
public static readonly ApiPropertyReadings None = new([], EndpointRequired: false);

public bool ExpandsChildren { get; init; }
}

/// <summary>Only an API-filtered lookup matches by prefix, and only one ending in a dot lists the typed path's children.</summary>
internal sealed record PropertyLookup(bool AllowPrefix, bool ExpandChildren);

private static PropertyLookup Lookup(ApiPropertyReadings parsed, string? typeFilter) =>
IsApiLookup(typeFilter)
? new(AllowPrefix: true, ExpandChildren: parsed.ExpandsChildren)
: new(AllowPrefix: false, ExpandChildren: false);

internal static Query BuildNestedPropertyQuery(
string property,
string innerHitsName,
Expand Down Expand Up @@ -388,50 +365,6 @@ public static Query WrapWithRuleQuery(Query query, string searchQuery, string? r
return word.StartsWith('_') ? word : "_" + word;
}

/// <summary>
/// Partial-match fallback for API lookups. The strict lexical query needs every typed word, so
/// <c>create deployment cloud</c> finds only operations that contain all three. From three words on, this
/// clause also matches operations that contain 75% of them, at a lower weight than a full match.
/// </summary>
public static Query? BuildLoosePartialMatchQuery(string searchQuery)
{
if (searchQuery.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length < 3)
return null;

return new BoolQuery
{
Must =
[
new MultiMatchQuery
{
Query = searchQuery,
Operator = Operator.Or,
MinimumShouldMatch = "75%",
Type = TextQueryType.BestFields,
Analyzer = "synonyms_analyzer",
Boost = 0.5f,
Fields = new[] { QueryFieldNames.SearchTitle, QueryFieldNames.Body }
}
],
Filter = [DocumentFilter]
};
}

/// <summary>
/// API-filtered lookups only: widens the match set with <see cref="BuildLoosePartialMatchQuery"/> and lifts the
/// endpoint of a bare word. Both are no-ops for queries they don't apply to.
/// </summary>
public static Query ApplyApiRanking(Query lexicalQuery, string searchQuery)
{
var query = BuildLoosePartialMatchQuery(searchQuery) is { } loose
? new BoolQuery { Should = [lexicalQuery, loose], MinimumShouldMatch = 1 }
: lexicalQuery;

return BuildBareWordEndpointQuery(searchQuery) is { } bareWordEndpoint
? new BoolQuery { Must = [query], Should = [bareWordEndpoint] }
: query;
}

public static Query BuildSemanticQuery(string searchQuery) =>
(Query)new SemanticQuery(QueryFieldNames.TitleSemanticText, searchQuery) { Boost = 5.0f }
|| new SemanticQuery(QueryFieldNames.SummarySemanticText, searchQuery) { Boost = 3.0f }
Expand Down
150 changes: 150 additions & 0 deletions tests/Elastic.Documentation.Api.Tests/ApiLookupQueryBuilderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,156 @@ public void Build_TrailingDot_AddsTheChildrenOptionAndWidensInnerHits()
ApiLookupQueryBuilder.ExpandsChildren("retriever.standard").Should().BeFalse();
}

[Test]
[Arguments("knn", 0, "knn")]
[Arguments("GET /_search knn", 1, "knn")]
[Arguments("knn /_search", 0, "knn")]
[Arguments("options", 0, "options")]
[Arguments("track_total", 0, "track_total")]
public void Build_FieldWord_MatchesOnlyItsOwnNameWithBoundedScores(string query, int index, string name)
{
using var json = Json(ApiLookupQueryBuilder.Build(query));
var fieldQuery = OptionsByName(TokenClause(json, index))[$"field_{index}"].GetProperty("query");
var options = fieldQuery.GetProperty("dis_max").GetProperty("queries");
options.GetArrayLength().Should().Be(1);
var matches = options[0].GetProperty("dis_max").GetProperty("queries");
matches.GetArrayLength().Should().Be(2);
matches[0]
.GetProperty("constant_score")
.GetProperty("filter")
.GetProperty("term")
.GetProperty("api.properties.name")
.GetProperty("value")
.GetString()
.Should()
.Be(name);
matches[1]
.GetProperty("constant_score")
.GetProperty("filter")
.GetProperty("prefix")
.GetProperty("api.properties.name")
.GetProperty("value")
.GetString()
.Should()
.Be(name);
fieldQuery.GetRawText().Should().NotContain("api.properties.description").And.NotContain("api.properties.path");
var scores = matches.EnumerateArray().Select(q => q.GetProperty("constant_score").GetProperty("boost").GetSingle()).ToArray();
scores.Should().OnlyContain(score => score > 0 && score <= 1);
scores[0].Should().BeGreaterThan(scores[1], "an exact field name ranks ahead of a prefix");
}

[Test]
public void Build_QualifiedPath_FieldOptionRequiresMatchingLeafAndPath()
{
using var json = Json(ApiLookupQueryBuilder.Build("_search knn.field"));
var qualified = OptionsByName(TokenClause(json, 1))["field_1"]
.GetProperty("query")
.GetProperty("dis_max")
.GetProperty("queries")[1]
.GetProperty("bool");
var leaf = qualified
.GetProperty("must")
.GetProperty("dis_max")
.GetProperty("queries")[0]
.GetProperty("constant_score")
.GetProperty("filter");
leaf.GetProperty("term").GetProperty("api.properties.name").GetProperty("value").GetString().Should().Be("field");
var path = qualified.GetProperty("filter").GetProperty("match_bool_prefix").GetProperty("api.properties.path.match");
path.GetProperty("query").GetString().Should().Be("knn.field");
path.GetProperty("operator").GetString().Should().Be("and");
}

[Test]
[Arguments("retriever.", "retriever")]
[Arguments("pets[].owner.", "pets.owner")]
[Arguments("labels.<string>.", "labels")]
public void Build_TrailingDot_ChildrenOptionNamesTheParentKey(string query, string parent)
{
using var json = Json(ApiLookupQueryBuilder.Build(query));
var term = OptionsByName(TokenClause(json, 0))["field_0"]
.GetProperty("query")
.GetProperty("dis_max")
.GetProperty("queries")
.EnumerateArray()
.Select(o => o.EnumerateObject().Single().Value)
.Single(o => o.TryGetProperty("_name", out var name) && name.GetString() == "api_children")
.GetProperty("filter")
.GetProperty("term")
.GetProperty("api.properties.parent");
term.GetProperty("value").GetString().Should().Be(parent);
term.GetProperty("case_insensitive").GetBoolean().Should().BeTrue();
}

[Test]
[Arguments("retriever")]
[Arguments("retriever.standard")]
public void Build_TrailingDot_KeepsTheNameOptions(string path)
{
static string[] Options(string query)
{
using var json = Json(ApiLookupQueryBuilder.Build(query));
return OptionsByName(TokenClause(json, 0))["field_0"]
.GetProperty("query")
.GetProperty("dis_max")
.GetProperty("queries")
.EnumerateArray()
.Select(q => q.GetRawText())
.ToArray();
}

Options(path + ".")[..^1].Should().Equal(Options(path)).And.NotBeEmpty();
}

[Test]
public void Build_NoTrailingDot_FieldOptionHasNoChildrenOption()
{
using var json = Json(ApiLookupQueryBuilder.Build("retriever"));
var field = OptionsByName(TokenClause(json, 0))["field_0"];

field.GetProperty("query").GetRawText().Should().NotContain("api_children").And.NotContain("api.properties.parent");
}

[Test]
[Arguments("retriever", "retriever")]
[Arguments("retriever.standard.", "retriever.standard")]
[Arguments("GET /_search retriever", "retriever")]
[Arguments("pets[].owner.", "pets.owner")]
[Arguments("labels.<string>.", "labels")]
public void Build_PlainWord_LiftsOperationsThatListChildrenOfTheTypedPath(string query, string field)
{
using var json = Json(ApiLookupQueryBuilder.Build(query));
var lift = json
.RootElement
.GetProperty("bool")
.GetProperty("should")
.EnumerateArray()
.Where(l => l.TryGetProperty("nested", out _))
.Select(l => l.GetProperty("nested"))
.Single(
l => l
.GetProperty("query")
.GetProperty("constant_score")
.GetProperty("filter")
.GetProperty("term")
.GetProperty("api.properties.parent")
.GetProperty("value")
.GetString() == field
);
lift.GetProperty("path").GetString().Should().Be("api.properties");
lift.GetProperty("score_mode").GetString().Should().Be("max");
lift.TryGetProperty("inner_hits", out _).Should().BeFalse();
var constantScore = lift.GetProperty("query").GetProperty("constant_score");
constantScore.GetProperty("boost").GetSingle().Should().Be(0.5f);
constantScore
.GetProperty("filter")
.GetProperty("term")
.GetProperty("api.properties.parent")
.GetProperty("case_insensitive")
.GetBoolean()
.Should()
.BeTrue();
}

[Test]
public void Build_PathToken_OffersOnlyTheEndpointKey()
{
Expand Down
Loading
Loading