feat(search): relevance ranking + websearch_to_tsquery (#13)
CI / backend (push) Successful in 1m13s
CI / frontend (push) Successful in 27s
Deploy Staging / deploy (push) Successful in 44s
CI / backend (pull_request) Successful in 1m12s
CI / frontend (pull_request) Successful in 21s
Security / secrets (push) Successful in 5s
Security / dependencies (push) Successful in 1m3s
Security / secrets (pull_request) Successful in 4s
Security / dependencies (pull_request) Successful in 1m3s

This commit was merged in pull request #13.
This commit is contained in:
2026-07-01 21:08:53 +02:00
parent dfd8579899
commit a9be48daee
6 changed files with 128 additions and 48 deletions
@@ -10,7 +10,9 @@ namespace InboxIntel.Infrastructure.Search;
/// <summary>
/// Structured + full-text search. Structured filters compose as SQL WHERE
/// clauses; free text uses PostgreSQL FTS via the generated SearchVector column
/// (EF.Functions.ToTsVector/Matches translate to @@ / to_tsquery).
/// (websearch_to_tsquery / @@ / ts_rank_cd). Results are relevance-ranked when a
/// free-text query is present, date-ordered otherwise. See
/// docs/discovery/05-search-redesign.md for the full multi-layer search design.
/// </summary>
public class SearchService : ISearchService
{
@@ -58,16 +60,24 @@ public class SearchService : ISearchService
return new PagedResult<EmailSummaryDto> { Items = [], Page = r.Page, PageSize = r.PageSize, TotalCount = 0 };
}
if (!string.IsNullOrWhiteSpace(r.Query))
{
// PostgreSQL full-text match against the generated tsvector.
var term = r.Query.Trim();
q = q.Where(e => e.SearchVector!.Matches(EF.Functions.PlainToTsQuery("english", term)));
}
// websearch_to_tsquery (vs. plainto_tsquery) understands quotes ("exact phrase"),
// OR, and -exclusions — the syntax users already expect from web search boxes.
var hasFreeTextQuery = !string.IsNullOrWhiteSpace(r.Query);
var term = r.Query?.Trim() ?? string.Empty;
if (hasFreeTextQuery)
q = q.Where(e => e.SearchVector!.Matches(EF.Functions.WebSearchToTsQuery("english", term)));
var total = await q.CountAsync(ct);
var items = await q
.OrderByDescending(e => e.SentAtUtc)
// Relevance-ranked when there's a free-text query (ts_rank_cd via RankCoverDensity,
// recency as a tiebreaker); date-only otherwise — matches the existing browse
// behaviour when the user isn't searching for anything in particular.
var ranked = hasFreeTextQuery
? q.OrderByDescending(e => e.SearchVector!.RankCoverDensity(EF.Functions.WebSearchToTsQuery("english", term)))
.ThenByDescending(e => e.SentAtUtc)
: q.OrderByDescending(e => e.SentAtUtc);
var items = await ranked
.Skip((r.Page - 1) * r.PageSize)
.Take(r.PageSize)
.Select(e => new EmailSummaryDto(
@@ -79,7 +89,10 @@ public class SearchService : ISearchService
return new PagedResult<EmailSummaryDto>
{
Items = items, Page = r.Page, PageSize = r.PageSize, TotalCount = total
Items = items,
Page = r.Page,
PageSize = r.PageSize,
TotalCount = total
};
}
}