|
| 1 | +// Copyright (c) Microsoft. All rights reserved. |
| 2 | +using System.Diagnostics; |
| 3 | +using KernelMemory.Core.Search.Models; |
| 4 | +using KernelMemory.Core.Search.Query.Ast; |
| 5 | +using KernelMemory.Core.Storage; |
| 6 | + |
| 7 | +namespace KernelMemory.Core.Search; |
| 8 | + |
| 9 | +/// <summary> |
| 10 | +/// Per-node search service. |
| 11 | +/// Executes searches within a single node's indexes. |
| 12 | +/// Handles query parsing, FTS query execution, and result filtering. |
| 13 | +/// </summary> |
| 14 | +public sealed class NodeSearchService |
| 15 | +{ |
| 16 | + private readonly string _nodeId; |
| 17 | + private readonly IFtsIndex _ftsIndex; |
| 18 | + private readonly IContentStorage _contentStorage; |
| 19 | + |
| 20 | + /// <summary> |
| 21 | + /// Initialize a new NodeSearchService. |
| 22 | + /// </summary> |
| 23 | + /// <param name="nodeId">The node ID this service operates on.</param> |
| 24 | + /// <param name="ftsIndex">The FTS index for this node.</param> |
| 25 | + /// <param name="contentStorage">The content storage for loading full records.</param> |
| 26 | + public NodeSearchService(string nodeId, IFtsIndex ftsIndex, IContentStorage contentStorage) |
| 27 | + { |
| 28 | + this._nodeId = nodeId; |
| 29 | + this._ftsIndex = ftsIndex; |
| 30 | + this._contentStorage = contentStorage; |
| 31 | + } |
| 32 | + |
| 33 | + /// <summary> |
| 34 | + /// Search this node using a parsed query AST. |
| 35 | + /// </summary> |
| 36 | + /// <param name="queryNode">The parsed query AST.</param> |
| 37 | + /// <param name="request">The search request with options.</param> |
| 38 | + /// <param name="cancellationToken">Cancellation token.</param> |
| 39 | + /// <returns>Search results from this node.</returns> |
| 40 | + public async Task<(SearchIndexResult[] Results, TimeSpan SearchTime)> SearchAsync( |
| 41 | + QueryNode queryNode, |
| 42 | + SearchRequest request, |
| 43 | + CancellationToken cancellationToken = default) |
| 44 | + { |
| 45 | + var stopwatch = Stopwatch.StartNew(); |
| 46 | + |
| 47 | + try |
| 48 | + { |
| 49 | + // Apply timeout |
| 50 | + var timeout = request.TimeoutSeconds ?? SearchConstants.DefaultSearchTimeoutSeconds; |
| 51 | + using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); |
| 52 | + cts.CancelAfter(TimeSpan.FromSeconds(timeout)); |
| 53 | + |
| 54 | + // Query the FTS index |
| 55 | + var maxResults = request.MaxResultsPerNode ?? SearchConstants.DefaultMaxResultsPerNode; |
| 56 | + |
| 57 | + // Convert QueryNode to FTS query string |
| 58 | + var ftsQuery = this.ExtractFtsQuery(queryNode); |
| 59 | + |
| 60 | + // Search the FTS index |
| 61 | + var ftsMatches = await this._ftsIndex.SearchAsync( |
| 62 | + ftsQuery, |
| 63 | + maxResults, |
| 64 | + cts.Token).ConfigureAwait(false); |
| 65 | + |
| 66 | + // Load full ContentRecords from storage |
| 67 | + var results = new List<SearchIndexResult>(); |
| 68 | + foreach (var match in ftsMatches) |
| 69 | + { |
| 70 | + var content = await this._contentStorage.GetByIdAsync(match.ContentId, cts.Token).ConfigureAwait(false); |
| 71 | + if (content != null) |
| 72 | + { |
| 73 | + results.Add(new SearchIndexResult |
| 74 | + { |
| 75 | + RecordId = content.Id, |
| 76 | + NodeId = this._nodeId, |
| 77 | + IndexId = "fts-main", // TODO: Get from index config |
| 78 | + ChunkId = null, |
| 79 | + BaseRelevance = (float)match.Score, |
| 80 | + Title = content.Title, |
| 81 | + Description = content.Description, |
| 82 | + Content = content.Content, |
| 83 | + CreatedAt = content.ContentCreatedAt, |
| 84 | + MimeType = content.MimeType, |
| 85 | + Tags = content.Tags ?? [], |
| 86 | + Metadata = content.Metadata ?? new Dictionary<string, string>() |
| 87 | + }); |
| 88 | + } |
| 89 | + } |
| 90 | + |
| 91 | + stopwatch.Stop(); |
| 92 | + return ([.. results], stopwatch.Elapsed); |
| 93 | + } |
| 94 | + catch (OperationCanceledException) |
| 95 | + { |
| 96 | + stopwatch.Stop(); |
| 97 | + throw new Exceptions.SearchException( |
| 98 | + $"Node '{this._nodeId}' search timed out after {stopwatch.Elapsed.TotalSeconds:F2} seconds", |
| 99 | + Exceptions.SearchErrorType.NodeTimeout, |
| 100 | + this._nodeId); |
| 101 | + } |
| 102 | + catch (Exception ex) |
| 103 | + { |
| 104 | + stopwatch.Stop(); |
| 105 | + throw new Exceptions.SearchException( |
| 106 | + $"Failed to search node '{this._nodeId}': {ex.Message}", |
| 107 | + Exceptions.SearchErrorType.NodeUnavailable, |
| 108 | + this._nodeId); |
| 109 | + } |
| 110 | + } |
| 111 | + |
| 112 | + /// <summary> |
| 113 | + /// Extract FTS query string from query AST. |
| 114 | + /// Converts the AST to SQLite FTS5 query syntax. |
| 115 | + /// Only includes text search terms; filtering is done via LINQ on results. |
| 116 | + /// </summary> |
| 117 | + private string ExtractFtsQuery(QueryNode queryNode) |
| 118 | + { |
| 119 | + var visitor = new FtsQueryExtractor(); |
| 120 | + return visitor.Extract(queryNode); |
| 121 | + } |
| 122 | + |
| 123 | + /// <summary> |
| 124 | + /// Visitor that extracts FTS query terms from the AST. |
| 125 | + /// Focuses only on TextSearchNode and field-specific text searches. |
| 126 | + /// Logical operators are preserved for FTS query syntax. |
| 127 | + /// </summary> |
| 128 | + private sealed class FtsQueryExtractor |
| 129 | + { |
| 130 | + public string Extract(QueryNode node) |
| 131 | + { |
| 132 | + var terms = this.ExtractTerms(node); |
| 133 | + return string.IsNullOrEmpty(terms) ? "*" : terms; |
| 134 | + } |
| 135 | + |
| 136 | + private string ExtractTerms(QueryNode node) |
| 137 | + { |
| 138 | + return node switch |
| 139 | + { |
| 140 | + TextSearchNode textNode => this.ExtractTextSearch(textNode), |
| 141 | + LogicalNode logicalNode => this.ExtractLogical(logicalNode), |
| 142 | + ComparisonNode comparisonNode => this.ExtractComparison(comparisonNode), |
| 143 | + _ => string.Empty |
| 144 | + }; |
| 145 | + } |
| 146 | + |
| 147 | + private string ExtractTextSearch(TextSearchNode node) |
| 148 | + { |
| 149 | + // Escape FTS5 special characters and quote the term |
| 150 | + var escapedText = this.EscapeFtsText(node.SearchText); |
| 151 | + |
| 152 | + // If specific field, prefix with field name (SQLite FTS5 syntax) |
| 153 | + if (node.Field != null && this.IsFtsField(node.Field.FieldPath)) |
| 154 | + { |
| 155 | + return $"{node.Field.FieldPath}:{escapedText}"; |
| 156 | + } |
| 157 | + |
| 158 | + // Default field: search all FTS fields (title, description, content) |
| 159 | + // FTS5 syntax: {title description content}:term |
| 160 | + return $"{{title description content}}:{escapedText}"; |
| 161 | + } |
| 162 | + |
| 163 | + private string ExtractLogical(LogicalNode node) |
| 164 | + { |
| 165 | + var childTerms = node.Children |
| 166 | + .Select(this.ExtractTerms) |
| 167 | + .Where(t => !string.IsNullOrEmpty(t)) |
| 168 | + .ToArray(); |
| 169 | + |
| 170 | + if (childTerms.Length == 0) |
| 171 | + { |
| 172 | + return string.Empty; |
| 173 | + } |
| 174 | + |
| 175 | + return node.Operator switch |
| 176 | + { |
| 177 | + LogicalOperator.And => string.Join(" AND ", childTerms.Select(t => $"({t})")), |
| 178 | + LogicalOperator.Or => string.Join(" OR ", childTerms.Select(t => $"({t})")), |
| 179 | + LogicalOperator.Not => childTerms.Length > 0 ? $"NOT ({childTerms[0]})" : string.Empty, |
| 180 | + LogicalOperator.Nor => string.Join(" AND ", childTerms.Select(t => $"NOT ({t})")), |
| 181 | + _ => string.Empty |
| 182 | + }; |
| 183 | + } |
| 184 | + |
| 185 | + private string ExtractComparison(ComparisonNode node) |
| 186 | + { |
| 187 | + // Only extract text search from Contains operator on FTS fields |
| 188 | + if (node.Operator == ComparisonOperator.Contains && |
| 189 | + node.Field?.FieldPath != null && |
| 190 | + this.IsFtsField(node.Field.FieldPath) && |
| 191 | + node.Value != null) |
| 192 | + { |
| 193 | + var searchText = node.Value.AsString(); |
| 194 | + var escapedText = this.EscapeFtsText(searchText); |
| 195 | + return $"{node.Field.FieldPath}:{escapedText}"; |
| 196 | + } |
| 197 | + |
| 198 | + // Other comparison operators (==, !=, >=, etc.) are handled by LINQ filtering |
| 199 | + // Return empty string as these don't contribute to FTS query |
| 200 | + return string.Empty; |
| 201 | + } |
| 202 | + |
| 203 | + private bool IsFtsField(string? fieldPath) |
| 204 | + { |
| 205 | + if (fieldPath == null) |
| 206 | + { |
| 207 | + return false; |
| 208 | + } |
| 209 | + |
| 210 | + var normalized = fieldPath.ToLowerInvariant(); |
| 211 | + return normalized == "title" || normalized == "description" || normalized == "content"; |
| 212 | + } |
| 213 | + |
| 214 | + private string EscapeFtsText(string text) |
| 215 | + { |
| 216 | + // FTS5 special characters that need escaping: " * ( ) |
| 217 | + // Wrap in quotes to handle spaces and special characters |
| 218 | + var escaped = text.Replace("\"", "\"\"", StringComparison.Ordinal); // Escape quotes by doubling |
| 219 | + return $"\"{escaped}\""; |
| 220 | + } |
| 221 | + } |
| 222 | +} |
0 commit comments