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 @@ -25,10 +25,18 @@ public required IReadOnlyDictionary<string, string[]> Synonyms
var targets = new List<string[]>();
foreach (var s in a)
{
if (s.Contains(' ') || s.Contains("=>"))
if (s.Contains(' '))
continue;

List<string> newTarget = [s];
if (s.Contains("=>"))
{
var tokens = s.Split("=>");
if (tokens.Length > 1)
newTarget = [tokens[0].Trim()];
else
continue;
}
newTarget.AddRange(a.Except([s]));
targets.Add(newTarget.ToArray());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,9 +143,7 @@ export function SearchResultListItem({
`}
>
<SanitizedHtmlContent
htmlContent={
result.highlightedTitle ?? result.title
}
htmlContent={result.title}
ellipsis={false}
/>
</div>
Expand All @@ -164,14 +162,10 @@ export function SearchResultListItem({
//width: 90%;
`}
>
{result.highlightedBody ? (
<SanitizedHtmlContent
htmlContent={result.highlightedBody}
ellipsis={true}
/>
) : (
<span>{result.description}</span>
)}
<SanitizedHtmlContent
htmlContent={result.description}
ellipsis={true}
/>
</div>
</EuiText>
{result.parents.length > 0 && (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,6 @@ const SearchResultItem = z.object({
description: z.string(),
score: z.number(),
parents: z.array(SearchResultItemParent),
highlightedTitle: z.string().nullish(),
highlightedBody: z.string().nullish(),
})

export type SearchResultItem = z.infer<typeof SearchResultItem>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,5 @@ public record SearchResultItem
public required string Title { get; init; }
public required string Description { get; init; }
public required SearchResultItemParent[] Parents { get; init; }
public string[]? Headings { get; init; }
public float Score { get; init; }
public string? HighlightedBody { get; init; }

public string? HighlightedTitle { get; init; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -276,18 +276,13 @@ public async Task<SearchResult> SearchImplementation(string query, int pageNumbe
)
)
.Highlight(h => h
.RequireFieldMatch(true)
.Fields(f => f
.Add(Infer.Field<DocumentationDocument>(d => d.SearchTitle.Suffix("completion")), hf => hf
.Add(Infer.Field<DocumentationDocument>(d => d.Title), hf => hf
.FragmentSize(150)
.NumberOfFragments(3)
.NoMatchSize(150)
.BoundaryChars(":.!?\t\n")
.BoundaryScanner(BoundaryScanner.Sentence)
.BoundaryMaxScan(15)
.FragmentOffset(0)
.HighlightQuery(q => q.Match(m => m
.Field(d => d.SearchTitle.Suffix("completion"))
.Field(d => d.Title)
.Query(searchQuery)
.Analyzer("highlight_analyzer")
))
Expand All @@ -297,15 +292,6 @@ public async Task<SearchResult> SearchImplementation(string query, int pageNumbe
.FragmentSize(150)
.NumberOfFragments(3)
.NoMatchSize(150)
.BoundaryChars(":.!?\t\n")
.BoundaryScanner(BoundaryScanner.Sentence)
.BoundaryMaxScan(15)
.FragmentOffset(0)
.HighlightQuery(q => q.Match(m => m
.Field(d => d.StrippedBody)
.Query(searchQuery)
.Analyzer("highlight_analyzer")
))
.PreTags(preTag)
.PostTags(postTag))
)
Expand All @@ -324,7 +310,7 @@ public async Task<SearchResult> SearchImplementation(string query, int pageNumbe
else
_logger.LogInformation("RRF search completed for '{Query}'. Total hits: {TotalHits}", query, response.Total);

return ProcessSearchResponse(response);
return ProcessSearchResponse(response, searchQuery, _searchConfiguration.SynonymBiDirectional);
}
catch (Exception ex)
{
Expand All @@ -333,9 +319,13 @@ public async Task<SearchResult> SearchImplementation(string query, int pageNumbe
}
}

private static SearchResult ProcessSearchResponse(SearchResponse<DocumentationDocument> response)
private static SearchResult ProcessSearchResponse(
SearchResponse<DocumentationDocument> response,
string searchQuery,
IReadOnlyDictionary<string, string[]> synonyms)
{
var totalHits = (int)response.Total;
var searchTokens = searchQuery.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);

var results = response.Documents.Select((doc, index) =>
{
Expand All @@ -348,36 +338,42 @@ private static SearchResult ProcessSearchResponse(SearchResponse<DocumentationDo
if (highlights != null)
{
if (highlights.TryGetValue("stripped_body", out var bodyHighlights) && bodyHighlights.Count > 0)
highlightedBody = string.Join(". ", bodyHighlights.Select(h => h.TrimEnd('.', ' ', '-')));
highlightedBody = string.Join(". ", bodyHighlights.Select(h => h.Trim(['|', ' ', '.', '-'])));

if (highlights.TryGetValue("search_title.completion", out var titleHighlights) && titleHighlights.Count > 0)
highlightedTitle = string.Join(". ", titleHighlights.Select(h => h.TrimEnd('.', ' ', '-')));
if (highlights.TryGetValue("title", out var titleHighlights) && titleHighlights.Count > 0)
highlightedTitle = string.Join(". ", titleHighlights.Select(h => h.Trim(['|', ' ', '.', '-'])));
}

var title = (highlightedTitle ?? doc.Title).HighlightTokens(searchTokens, synonyms);
var description = (!string.IsNullOrWhiteSpace(highlightedBody) ? highlightedBody : doc.Description ?? string.Empty)
.Replace("\r\n", " ")
.Replace("\n", " ")
.Replace("\r", " ")
.Trim(['|', ' '])
.HighlightTokens(searchTokens, synonyms);

return new SearchResultItem
{
Url = doc.Url,
Title = doc.Title,
Title = title,
Type = doc.Type,
Description = doc.Description ?? string.Empty,
Headings = doc.Headings,
Description = description,
Parents = doc.Parents.Select(parent => new SearchResultItemParent
{
Title = parent.Title,
Url = parent.Url
}).ToArray(),
Score = (float)(hit?.Score ?? 0.0),
HighlightedTitle = highlightedTitle,
HighlightedBody = highlightedBody
Score = (float)(hit?.Score ?? 0.0)
};
}).ToList();

// Extract aggregations
var aggregations = new Dictionary<string, long>();
if (response.Aggregations?.TryGetValue("type", out var typeAgg) == true && typeAgg is StringTermsAggregate stringTermsAgg)
var terms = response.Aggregations?.GetStringTerms("type");
if (terms is not null)
{
foreach (var bucket in stringTermsAgg.Buckets)
aggregations[bucket.Key.ToString()!] = bucket.DocCount;
foreach (var bucket in terms.Buckets)
aggregations[bucket.Key.ToString()] = bucket.DocCount;
}

return new SearchResult
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
// 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;

namespace Elastic.Documentation.Api.Infrastructure.Adapters.Search;

public static class StringHighlightExtensions
{
private const string MarkOpen = "<mark>";
private const string MarkClose = "</mark>";

/// <summary>
/// Highlights search tokens in text by wrapping them with &lt;mark&gt; tags.
/// Skips tokens that are already highlighted or are inside existing mark tags.
/// </summary>
/// <param name="text">The text to highlight tokens in</param>
/// <param name="tokens">The search tokens to highlight</param>
/// <param name="synonyms">Optional dictionary of synonyms to also highlight</param>
/// <returns>Text with highlighted tokens</returns>
public static string HighlightTokens(
this string text,
ReadOnlySpan<string> tokens,
IReadOnlyDictionary<string, string[]>? synonyms = null)
{
if (tokens.Length == 0 || string.IsNullOrEmpty(text))
return text;

var result = text;

foreach (var token in tokens)
{
if (string.IsNullOrEmpty(token))
continue;

// Highlight the token itself
result = HighlightSingleToken(result, token);

if (synonyms == null)
continue;

// Highlight synonyms for this token (direct lookup)
if (synonyms.TryGetValue(token, out var tokenSynonyms))
{
foreach (var synonym in tokenSynonyms)
{
var synonymToHighlight = ExtractSynonymTarget(synonym);
if (!string.IsNullOrEmpty(synonymToHighlight))
result = HighlightSingleToken(result, synonymToHighlight);
}
}

// Also check for hard replacements where this token is the source
// Format: "source => target" means when searching for "source", also highlight "target"
foreach (var kvp in synonyms)
{
foreach (var synonym in kvp.Value)
{
if (string.IsNullOrEmpty(synonym) || !synonym.Contains("=>"))
continue;

var (source, target) = ParseHardReplacement(synonym);
if (!string.IsNullOrEmpty(source) &&
!string.IsNullOrEmpty(target) &&
source.Equals(token, StringComparison.OrdinalIgnoreCase))
{
result = HighlightSingleToken(result, target);
}
}
}
}

return result;
}

/// <summary>
/// Extracts the target from a synonym entry, handling hard replacement format.
/// For "source => target" returns "target", otherwise returns the original synonym.
/// </summary>
private static string? ExtractSynonymTarget(string? synonym)
{
if (string.IsNullOrEmpty(synonym))
return null;

if (!synonym.Contains("=>"))
return synonym;

var (_, target) = ParseHardReplacement(synonym);
return target;
}

/// <summary>
/// Parses a hard replacement synonym format: "source => target"
/// </summary>
private static (string? Source, string? Target) ParseHardReplacement(string synonym)
{
var arrowIndex = synonym.IndexOf("=>", StringComparison.Ordinal);
if (arrowIndex < 0)
return (null, null);

var source = synonym[..arrowIndex].Trim();
var target = synonym[(arrowIndex + 2)..].Trim();

return (source, target);
}

private static string HighlightSingleToken(string text, string token)
{
// Check if this exact token is already fully highlighted somewhere
// This prevents double-highlighting
if (text.Contains($"{MarkOpen}{token}{MarkClose}", StringComparison.OrdinalIgnoreCase))
return text;

var sb = new StringBuilder(text.Length + 26); // Room for a couple of mark tags
var textSpan = text.AsSpan();
var tokenSpan = token.AsSpan();
var pos = 0;

while (pos < textSpan.Length)
{
var remaining = textSpan[pos..];
var matchIndex = remaining.IndexOf(tokenSpan, StringComparison.OrdinalIgnoreCase);

if (matchIndex < 0)
{
// No more matches, append rest and exit
_ = sb.Append(remaining);
break;
}

var absoluteIndex = pos + matchIndex;

// Check if we're inside mark tag syntax or inside mark tag content
if (IsInsideMarkTagSyntax(textSpan, absoluteIndex, tokenSpan.Length) || IsInsideMarkTagContent(textSpan, absoluteIndex))
{
// Append up to and including this match without highlighting
_ = sb.Append(remaining[..(matchIndex + tokenSpan.Length)]);
pos = absoluteIndex + token.Length;
continue;
}

// Append text before match, then highlighted token (preserving original case)
_ = sb.Append(remaining[..matchIndex])
.Append(MarkOpen)
.Append(remaining.Slice(matchIndex, tokenSpan.Length))
.Append(MarkClose);

pos = absoluteIndex + token.Length;
}

return sb.ToString();
}

private static bool IsInsideMarkTagSyntax(ReadOnlySpan<char> text, int position, int tokenLength)
{
// Check if the match position overlaps with <mark> or </mark> tag syntax
// We want to protect the literal tag strings, not arbitrary HTML

var matchEnd = position + tokenLength;

// Look for <mark> that contains our position
var searchStart = Math.Max(0, position - 5); // <mark> is 6 chars, so look back 5
var searchEnd = Math.Min(text.Length, matchEnd + 6);
var searchRegion = text[searchStart..searchEnd];

var markOpenIdx = searchRegion.IndexOf(MarkOpen.AsSpan(), StringComparison.OrdinalIgnoreCase);
if (markOpenIdx >= 0)
{
var absoluteMarkStart = searchStart + markOpenIdx;
var absoluteMarkEnd = absoluteMarkStart + MarkOpen.Length;
// Check if our match overlaps with this <mark> tag
if (position < absoluteMarkEnd && matchEnd > absoluteMarkStart)
return true;
}

// Look for </mark> that contains our position
searchStart = Math.Max(0, position - 6); // </mark> is 7 chars
searchEnd = Math.Min(text.Length, matchEnd + 7);
searchRegion = text[searchStart..searchEnd];

var markCloseIdx = searchRegion.IndexOf(MarkClose.AsSpan(), StringComparison.OrdinalIgnoreCase);
if (markCloseIdx >= 0)
{
var absoluteMarkStart = searchStart + markCloseIdx;
var absoluteMarkEnd = absoluteMarkStart + MarkClose.Length;
// Check if our match overlaps with this </mark> tag
if (position < absoluteMarkEnd && matchEnd > absoluteMarkStart)
return true;
}

return false;
}

private static bool IsInsideMarkTagContent(ReadOnlySpan<char> text, int position)
{
// Look backwards from position to find the last <mark> or </mark>
var beforePosition = text[..position];

var lastOpen = beforePosition.LastIndexOf(MarkOpen.AsSpan(), StringComparison.OrdinalIgnoreCase);
var lastClose = beforePosition.LastIndexOf(MarkClose.AsSpan(), StringComparison.OrdinalIgnoreCase);

// If we found an opening tag after the last closing tag, we're inside a mark's content
return lastOpen > lastClose;
}
}
Loading
Loading