From 61feaae782a4b3eaf5f0b063bc3ea6413303366e Mon Sep 17 00:00:00 2001 From: "Eric J. Smith" Date: Wed, 24 Jun 2026 23:38:56 -0500 Subject: [PATCH 01/10] M1: harden core parser and lexer for 1.0 - Add LuceneParser.MaxDepth (default 100) bounding group recursion to prevent a StackOverflow DoS from deeply nested input. Over-depth records a MaxDepthExceeded ParseError and the group is discarded iteratively. - Parse boost (^) and fuzzy/slop (~N) with InvariantCulture so values such as 2.5 do not change meaning on comma-decimal locales. - Fix a lexer trailing-backslash overrun in quoted-string and regex scanning that advanced past the end of the buffer (could throw inside Slice). - Add a Code (QueryErrorCode) field to ParseError and classify depth, bracket, range and unexpected-character errors. - Remove the dead ParseNumberTerm method. --- src/Foundatio.Lucene/LuceneLexer.cs | 28 +++- src/Foundatio.Lucene/LuceneParser.cs | 158 +++++++++++--------- src/Foundatio.Lucene/ParseError.cs | 4 +- tests/Foundatio.Lucene.Tests/ParserTests.cs | 78 ++++++++++ 4 files changed, 194 insertions(+), 74 deletions(-) diff --git a/src/Foundatio.Lucene/LuceneLexer.cs b/src/Foundatio.Lucene/LuceneLexer.cs index 13fb18c..403adb2 100644 --- a/src/Foundatio.Lucene/LuceneLexer.cs +++ b/src/Foundatio.Lucene/LuceneLexer.cs @@ -122,7 +122,7 @@ public Token NextToken() private void AddError(char c) { _errors ??= new List(4); - _errors.Add(new ParseError(string.Concat("Unexpected character: '", c.ToString(), "'"), _position, 1, _line, _column)); + _errors.Add(new ParseError(string.Concat("Unexpected character: '", c.ToString(), "'"), _position, 1, _line, _column, QueryErrorCode.UnexpectedToken)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -174,8 +174,17 @@ private Token ConsumeQuotedString() if (c == '\\') { hasEscapes = true; - _position += 2; - _column += 2; + // Guard against a trailing backslash running past the end of the buffer. + if (_position + 1 < _sourceMemory.Length) + { + _position += 2; + _column += 2; + } + else + { + _position++; + _column++; + } } else if (c == '"') { @@ -268,8 +277,17 @@ private Token ConsumeRegex() char c = Source[_position]; if (c == '\\') { - _position += 2; - _column += 2; + // Guard against a trailing backslash running past the end of the buffer. + if (_position + 1 < _sourceMemory.Length) + { + _position += 2; + _column += 2; + } + else + { + _position++; + _column++; + } } else if (c == '/') { diff --git a/src/Foundatio.Lucene/LuceneParser.cs b/src/Foundatio.Lucene/LuceneParser.cs index ed5bcdb..f5baf3f 100644 --- a/src/Foundatio.Lucene/LuceneParser.cs +++ b/src/Foundatio.Lucene/LuceneParser.cs @@ -1,3 +1,4 @@ +using System.Globalization; using System.Runtime.CompilerServices; using Foundatio.Lucene.Ast; @@ -11,6 +12,7 @@ public class LuceneParser { private readonly List _tokens; private int _position; + private int _depth; private List? _errors; /// @@ -18,6 +20,13 @@ public class LuceneParser /// public BooleanOperator DefaultOperator { get; set; } = BooleanOperator.Or; + /// + /// The maximum nesting depth of grouped expressions the parser will recurse into. + /// Input exceeding this depth records a and stops recursing, + /// guarding against stack-overflow denial-of-service from deeply nested queries. + /// + public int MaxDepth { get; set; } = 100; + /// /// Whether to split on whitespace when parsing groups. /// When false, consecutive terms in a group are combined into a MultiTermNode. @@ -358,53 +367,97 @@ private GroupNode ParseGroup() var startToken = CurrentToken; Advance(); // Skip ( - SkipWhitespace(); + _depth++; + try + { + // Guard against stack-overflow from deeply nested groups. Recursion only + // ever re-enters ParseQuery via ParseGroup, so bounding it here is sufficient. + if (_depth > MaxDepth) + { + Errors.Add(new ParseError($"Query nesting depth exceeds the maximum of {MaxDepth}.", startToken.Position, startToken.Length, startToken.Line, startToken.Column, QueryErrorCode.MaxDepthExceeded)); + ConsumeBalancedGroup(); + return new GroupNode + { + Query = null, + StartPosition = startToken.Position, + EndPosition = CurrentToken.Position, + StartLine = startToken.Line, + StartColumn = startToken.Column + }; + } + + SkipWhitespace(); - QueryNode? innerQuery; + QueryNode? innerQuery; - if (!SplitOnWhitespace) - { - // Try to parse as MultiTerm first (consecutive simple terms without operators) - innerQuery = TryParseMultiTerm(); - if (innerQuery == null) + if (!SplitOnWhitespace) + { + // Try to parse as MultiTerm first (consecutive simple terms without operators) + innerQuery = TryParseMultiTerm(); + if (innerQuery == null) + { + // Fall back to normal query parsing + innerQuery = ParseQuery(); + } + } + else { - // Fall back to normal query parsing innerQuery = ParseQuery(); } - } - else - { - innerQuery = ParseQuery(); - } - SkipWhitespace(); + SkipWhitespace(); - if (CurrentToken.Type == TokenType.RightParen) - { - Advance(); // Skip ) + if (CurrentToken.Type == TokenType.RightParen) + { + Advance(); // Skip ) + } + else + { + Errors.Add(new ParseError("Expected ')'", CurrentToken.Position, CurrentToken.Length, CurrentToken.Line, CurrentToken.Column, QueryErrorCode.UnmatchedBracket)); + } + + var group = new GroupNode + { + Query = innerQuery, + StartPosition = startToken.Position, + EndPosition = CurrentToken.Position, + StartLine = startToken.Line, + StartColumn = startToken.Column + }; + + // Check for boost + SkipWhitespace(); + if (CurrentToken.Type == TokenType.Caret) + { + group.Boost = ParseBoost(); + } + + return group; } - else + finally { - Errors.Add(new ParseError("Expected ')'", CurrentToken.Position, CurrentToken.Length, CurrentToken.Line, CurrentToken.Column)); + _depth--; } + } - var group = new GroupNode + /// + /// Consumes tokens up to and including the closing parenthesis that matches the + /// already-consumed opening parenthesis, balancing nested parentheses iteratively. + /// Used to discard an over-deep group without further recursion. + /// + private void ConsumeBalancedGroup() + { + int balance = 1; + while (!IsAtEnd() && balance > 0) { - Query = innerQuery, - StartPosition = startToken.Position, - EndPosition = CurrentToken.Position, - StartLine = startToken.Line, - StartColumn = startToken.Column - }; + var type = CurrentToken.Type; + Advance(); - // Check for boost - SkipWhitespace(); - if (CurrentToken.Type == TokenType.Caret) - { - group.Boost = ParseBoost(); + if (type == TokenType.LeftParen) + balance++; + else if (type == TokenType.RightParen) + balance--; } - - return group; } /// @@ -758,37 +811,6 @@ private TermNode ParseTermNode() return node; } - /// - /// Parses a number as a term. - /// - private TermNode ParseNumberTerm() - { - var startToken = CurrentToken; - var term = CurrentToken.Value; - - Advance(); - - var node = new TermNode - { - TermMemory = term, - UnescapedTermMemory = term, - StartPosition = startToken.Position, - EndPosition = startToken.Position + startToken.Length, - StartLine = startToken.Line, - StartColumn = startToken.Column - }; - - // Check for boost - SkipWhitespace(); - if (CurrentToken.Type == TokenType.Caret) - { - node.Boost = ParseBoost(); - node.EndPosition = CurrentToken.Position; - } - - return node; - } - /// /// Parses a quoted phrase. /// @@ -881,7 +903,7 @@ private RangeNode ParseRange() // Expect TO if (CurrentToken.Type != TokenType.To) { - Errors.Add(new ParseError("Expected 'TO' in range query", CurrentToken.Position, CurrentToken.Length, CurrentToken.Line, CurrentToken.Column)); + Errors.Add(new ParseError("Expected 'TO' in range query", CurrentToken.Position, CurrentToken.Length, CurrentToken.Line, CurrentToken.Column, QueryErrorCode.InvalidRange)); } else { @@ -907,7 +929,7 @@ private RangeNode ParseRange() } else { - Errors.Add(new ParseError("Expected ']' or '}' to close range query", CurrentToken.Position, CurrentToken.Length, CurrentToken.Line, CurrentToken.Column)); + Errors.Add(new ParseError("Expected ']' or '}' to close range query", CurrentToken.Position, CurrentToken.Length, CurrentToken.Line, CurrentToken.Column, QueryErrorCode.UnmatchedBracket)); } var node = new RangeNode @@ -1040,7 +1062,7 @@ private float ParseBoost() if (CurrentToken.Type == TokenType.Term) { - if (float.TryParse(CurrentToken.Span, out float boost)) + if (float.TryParse(CurrentToken.Span, NumberStyles.Float, CultureInfo.InvariantCulture, out float boost)) { Advance(); return boost; @@ -1064,7 +1086,7 @@ private int ParseFuzzyDistance() if (CurrentToken.Type == TokenType.Term) { - if (int.TryParse(CurrentToken.Span, out int distance)) + if (int.TryParse(CurrentToken.Span, NumberStyles.Integer, CultureInfo.InvariantCulture, out int distance)) { Advance(); return distance; diff --git a/src/Foundatio.Lucene/ParseError.cs b/src/Foundatio.Lucene/ParseError.cs index 999769d..cd7edbb 100644 --- a/src/Foundatio.Lucene/ParseError.cs +++ b/src/Foundatio.Lucene/ParseError.cs @@ -8,12 +8,14 @@ namespace Foundatio.Lucene; /// The length of the error span in characters. /// The line number where the error occurred (1-based). /// The column number where the error occurred (1-based). +/// The error code classifying the parse error. Defaults to . public readonly record struct ParseError( string Message, int Position, int Length, int Line, - int Column) + int Column, + QueryErrorCode Code = QueryErrorCode.ParseError) { /// /// The end position of the error (Position + Length). diff --git a/tests/Foundatio.Lucene.Tests/ParserTests.cs b/tests/Foundatio.Lucene.Tests/ParserTests.cs index 799a307..61b00cd 100644 --- a/tests/Foundatio.Lucene.Tests/ParserTests.cs +++ b/tests/Foundatio.Lucene.Tests/ParserTests.cs @@ -1,3 +1,4 @@ +using System.Globalization; using Foundatio.Lucene.Ast; namespace Foundatio.Lucene.Tests; @@ -435,6 +436,83 @@ public void Parse_UnbalancedParenthesis_ReturnsErrors() Assert.True(result.HasErrors); } + [Fact] + public void Parse_NestingBeyondMaxDepth_ReturnsDepthErrorInsteadOfRecursing() + { + // 200 nested groups exceeds the default max depth (100) but is shallow + // enough to parse without crashing if the bound is missing. + var query = new string('(', 200) + "x" + new string(')', 200); + + var result = LuceneQuery.Parse(query); + + Assert.True(result.HasErrors); + Assert.Contains(result.Errors, e => e.Message.Contains("depth", StringComparison.OrdinalIgnoreCase)); + } + + [Fact] + public void Parse_ExtremelyDeepNesting_DoesNotStackOverflow() + { + // Without a parse-time depth bound this throws an uncatchable StackOverflowException. + var query = new string('(', 50_000) + "x" + new string(')', 50_000); + + var result = LuceneQuery.Parse(query); + + Assert.NotNull(result); + Assert.True(result.HasErrors); + } + + [Fact] + public void Parse_NestingBeyondMaxDepth_ErrorIsClassifiedAsMaxDepthExceeded() + { + var query = new string('(', 200) + "x" + new string(')', 200); + + var result = LuceneQuery.Parse(query); + + Assert.Contains(result.Errors, e => e.Code == QueryErrorCode.MaxDepthExceeded); + } + + [Fact] + public void Parse_UnterminatedPhraseWithTrailingBackslash_DoesNotThrow() + { + // A trailing backslash must not advance the lexer past the end of the buffer. + var result = LuceneQuery.Parse("\"ab\\"); + + Assert.NotNull(result.Document); + Assert.IsType(result.Document.Query); + Assert.Equal("ab", ((PhraseNode)result.Document.Query!).Phrase); + } + + [Fact] + public void Parse_UnterminatedRegexWithTrailingBackslash_DoesNotThrow() + { + var result = LuceneQuery.Parse("/ab\\"); + + Assert.NotNull(result.Document); + Assert.IsType(result.Document.Query); + } + + [Fact] + public void Parse_BoostedTerm_WithCommaDecimalCulture_ParsesInvariant() + { + var original = CultureInfo.CurrentCulture; + try + { + // de-DE uses ',' as the decimal separator and '.' as the group separator, + // so a current-culture parse of "2.5" would yield 25. + CultureInfo.CurrentCulture = new CultureInfo("de-DE"); + + var result = LuceneQuery.Parse("important^2.5"); + + Assert.True(result.IsSuccess); + var term = (TermNode)result.Document.Query!; + Assert.Equal(2.5f, term.Boost); + } + finally + { + CultureInfo.CurrentCulture = original; + } + } + [Fact] public void Parse_OperatorPrecedence_AndBindsTighterThanOr() { From 13444cab2d29b30c44ef2dd95286068d2258b0f4 Mon Sep 17 00:00:00 2001 From: "Eric J. Smith" Date: Wed, 24 Jun 2026 23:42:20 -0500 Subject: [PATCH 02/10] M2: make per-request options the symmetric scope-swap mechanism - Delete the orphaned, untested TenantOptionsCache / EntityOptionsCache / TenantEntityOptionsCache and VisitorPool (~700 lines, zero references). Per-request options (ElasticsearchQueryOptions / EntityFrameworkQueryOptions, both immutable records) are the blessed scope-swap path; apps own caching. - ElasticsearchQueryParser now carries the per-scope field map and includes on the visitor context and reuses singleton FieldResolver/Include visitors instead of allocating a new visitor per query when a scope supplies its own config. Removes per-query visitor allocation on the swap path. - Add ConfigSwapBenchmarks (ES + EF) measuring per-query allocations when each query swaps a different scope against a shared parser. --- .../ConfigSwapBenchmarks.cs | 76 +++ .../Foundatio.Lucene.Benchmarks.csproj | 1 + .../ElasticsearchQueryParser.cs | 47 +- src/Foundatio.Lucene/TenantOptionsCache.cs | 548 ------------------ src/Foundatio.Lucene/VisitorPool.cs | 39 -- 5 files changed, 92 insertions(+), 619 deletions(-) create mode 100644 benchmarks/Foundatio.Lucene.Benchmarks/ConfigSwapBenchmarks.cs delete mode 100644 src/Foundatio.Lucene/TenantOptionsCache.cs delete mode 100644 src/Foundatio.Lucene/VisitorPool.cs diff --git a/benchmarks/Foundatio.Lucene.Benchmarks/ConfigSwapBenchmarks.cs b/benchmarks/Foundatio.Lucene.Benchmarks/ConfigSwapBenchmarks.cs new file mode 100644 index 0000000..cb9824b --- /dev/null +++ b/benchmarks/Foundatio.Lucene.Benchmarks/ConfigSwapBenchmarks.cs @@ -0,0 +1,76 @@ +using BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Configs; +using BenchmarkDotNet.Jobs; +using BenchmarkDotNet.Toolchains.InProcess.Emit; +using Foundatio.Lucene.Elasticsearch; +using Foundatio.Lucene.EntityFramework; + +namespace Foundatio.Lucene.Benchmarks; + +/// +/// Benchmarks the primary high-throughput use case: a single shared parser serving many +/// scopes/tenants, each supplying its own per-request options (field map, default fields, +/// validation) on every call. Measures the per-query cost of swapping scope configuration. +/// +[MemoryDiagnoser] +[Config(typeof(AntiVirusFriendlyConfig))] +public class ConfigSwapBenchmarks +{ + private class AntiVirusFriendlyConfig : ManualConfig + { + public AntiVirusFriendlyConfig() + { + AddJob(Job.ShortRun.WithToolchain(InProcessEmitToolchain.Instance)); + } + } + + private const string Query = "user:john AND created:[2020-01-01 TO *]"; + private const int ScopeCount = 8; + + private ElasticsearchQueryParser _esParser = null!; + private ElasticsearchQueryOptions[] _esScopes = null!; + + private EntityFrameworkQueryParser _efParser = null!; + private EntityFrameworkQueryOptions[] _efScopes = null!; + + private int _index; + + [GlobalSetup] + public void Setup() + { + _esParser = new ElasticsearchQueryParser(c => c.UseScoring = true); + _esScopes = new ElasticsearchQueryOptions[ScopeCount]; + for (int n = 0; n < ScopeCount; n++) + { + _esScopes[n] = new ElasticsearchQueryOptions + { + FieldMap = new FieldMap { { "user", $"tenant{n}.userName" }, { "created", $"tenant{n}.createdAt" } }, + DefaultFields = [$"tenant{n}.title"] + }; + } + + _efParser = new EntityFrameworkQueryParser(); + _efScopes = new EntityFrameworkQueryOptions[ScopeCount]; + for (int n = 0; n < ScopeCount; n++) + { + _efScopes[n] = new EntityFrameworkQueryOptionsBuilder() + .WithFieldMap(new FieldMap { { "user", "Name" }, { "created", "HireDate" } }) + .WithDefaultFields("Name") + .Build(); + } + } + + [Benchmark] + public object Elasticsearch_SwapScopePerQuery() + { + var scope = _esScopes[_index++ % ScopeCount]; + return _esParser.BuildQuery(Query, scope); + } + + [Benchmark] + public object EntityFramework_SwapScopePerQuery() + { + var scope = _efScopes[_index++ % ScopeCount]; + return _efParser.BuildFilter(Query, context: null, options: scope); + } +} diff --git a/benchmarks/Foundatio.Lucene.Benchmarks/Foundatio.Lucene.Benchmarks.csproj b/benchmarks/Foundatio.Lucene.Benchmarks/Foundatio.Lucene.Benchmarks.csproj index c7d98c7..582b6a0 100644 --- a/benchmarks/Foundatio.Lucene.Benchmarks/Foundatio.Lucene.Benchmarks.csproj +++ b/benchmarks/Foundatio.Lucene.Benchmarks/Foundatio.Lucene.Benchmarks.csproj @@ -18,6 +18,7 @@ + diff --git a/src/Foundatio.Lucene.Elasticsearch/ElasticsearchQueryParser.cs b/src/Foundatio.Lucene.Elasticsearch/ElasticsearchQueryParser.cs index 99d8f27..eaa1319 100644 --- a/src/Foundatio.Lucene.Elasticsearch/ElasticsearchQueryParser.cs +++ b/src/Foundatio.Lucene.Elasticsearch/ElasticsearchQueryParser.cs @@ -13,9 +13,11 @@ public class ElasticsearchQueryParser private readonly ElasticsearchQueryParserConfiguration _config; private readonly ConcurrentDictionary _indexOptions = new(StringComparer.OrdinalIgnoreCase); - // Stateless visitors that can be safely reused as singletons - private readonly FieldResolverQueryVisitor? _fieldResolverVisitor; - private readonly IncludeVisitor? _includeVisitor; + // Stateless visitors reused as singletons across all requests. Per-request + // configuration (field map, includes) is carried on the visitor context, so + // no visitor is allocated per query even when each scope supplies its own config. + private readonly FieldResolverQueryVisitor _fieldResolverVisitor = new(); + private readonly IncludeVisitor _includeVisitor = new(); private readonly DateMathEvaluatorVisitor _dateMathVisitor; private readonly ValidationVisitor _validationVisitor = new(); private readonly List _customVisitors; @@ -33,17 +35,6 @@ public ElasticsearchQueryParser(Action? c _config = new ElasticsearchQueryParserConfiguration(); configure?.Invoke(_config); - // Initialize stateless visitors that can be reused across all requests - if (_config.FieldMap is not null) - { - _fieldResolverVisitor = new FieldResolverQueryVisitor(_config.FieldMap); - } - - if (_config.Includes is not null) - { - _includeVisitor = new IncludeVisitor(_config.Includes); - } - _customVisitors = [.. _config.Visitors]; _dateMathVisitor = new DateMathEvaluatorVisitor(_config.TimeProvider); @@ -205,33 +196,25 @@ public Query BuildQuery(QueryDocument document, string? indexName, Elasticsearch // Create the visitor context, merging global config with registered and per-request options var context = CreateContext(registeredOptions, options); - // Build visitor chain for this request + // Build visitor chain for this request. The field map and includes for this + // scope are carried on the context so the singleton visitors can be reused + // without allocating a new visitor per query. QueryNode currentNode = document; - // Determine which field resolver to use (per-request > registered > global) - var fieldMap = options?.FieldMap ?? registeredOptions?.FieldMap; - var fieldResolver = fieldMap is not null - ? new FieldResolverQueryVisitor(fieldMap) - : _fieldResolverVisitor; - - if (fieldResolver is not null) + // Resolve field aliases (per-request > registered > global) + var fieldMap = options?.FieldMap ?? registeredOptions?.FieldMap ?? _config.FieldMap; + if (fieldMap is not null) { - currentNode = fieldResolver.Accept(currentNode, context); + context.SetFieldMap(fieldMap); + currentNode = _fieldResolverVisitor.Accept(currentNode, context); } - // Determine which includes to use (per-request > registered > global) + // Expand includes (per-request > registered > global) var includes = options?.Includes ?? registeredOptions?.Includes ?? _config.Includes; if (includes is not null) { context.SetIncludes(includes); - var includeVisitor = (options?.Includes ?? registeredOptions?.Includes) is not null - ? new IncludeVisitor(includes) - : _includeVisitor; - - if (includeVisitor is not null) - { - currentNode = includeVisitor.Accept(currentNode, context); - } + currentNode = _includeVisitor.Accept(currentNode, context); } currentNode = _dateMathVisitor.Accept(currentNode, context); diff --git a/src/Foundatio.Lucene/TenantOptionsCache.cs b/src/Foundatio.Lucene/TenantOptionsCache.cs deleted file mode 100644 index 1b963ec..0000000 --- a/src/Foundatio.Lucene/TenantOptionsCache.cs +++ /dev/null @@ -1,548 +0,0 @@ -using System.Collections.Concurrent; - -namespace Foundatio.Lucene; - -/// -/// Thread-safe cache for per-tenant query options. -/// Optimizes multi-tenant scenarios by caching pre-configured options per tenant. -/// -/// The tenant identifier type. -/// The options type (must inherit from QueryOptionsBase). -public class TenantOptionsCache - where TKey : notnull - where TOptions : QueryOptionsBase -{ - private readonly ConcurrentDictionary _cache = new(); - private readonly Func _optionsFactory; - - /// - /// Creates a new tenant options cache with the specified factory function. - /// - /// Factory function that creates options for a given tenant. - public TenantOptionsCache(Func optionsFactory) - { - _optionsFactory = optionsFactory ?? throw new ArgumentNullException(nameof(optionsFactory)); - } - - /// - /// Gets or creates options for the specified tenant. - /// - /// The tenant identifier. - /// The cached or newly created options for the tenant. - public TOptions GetOptions(TKey tenantKey) - { - return _cache.GetOrAdd(tenantKey, _optionsFactory); - } - - /// - /// Tries to get cached options for the specified tenant. - /// - /// The tenant identifier. - /// The cached options if found. - /// True if options were found in the cache. - public bool TryGetOptions(TKey tenantKey, out TOptions? options) - { - return _cache.TryGetValue(tenantKey, out options); - } - - /// - /// Sets options for the specified tenant, replacing any existing cached options. - /// - /// The tenant identifier. - /// The options to cache. - public void SetOptions(TKey tenantKey, TOptions options) - { - _cache[tenantKey] = options; - } - - /// - /// Removes cached options for the specified tenant. - /// - /// The tenant identifier. - /// True if options were removed. - public bool RemoveOptions(TKey tenantKey) - { - return _cache.TryRemove(tenantKey, out _); - } - - /// - /// Clears all cached options. - /// - public void Clear() - { - _cache.Clear(); - } - - /// - /// Gets the number of cached tenant options. - /// - public int Count => _cache.Count; - - /// - /// Gets all cached tenant keys. - /// - public IEnumerable CachedTenants => _cache.Keys; - - /// - /// Refreshes options for the specified tenant by invoking the factory function. - /// - /// The tenant identifier. - /// The refreshed options. - public TOptions RefreshOptions(TKey tenantKey) - { - var newOptions = _optionsFactory(tenantKey); - _cache[tenantKey] = newOptions; - return newOptions; - } - - /// - /// Refreshes options for all cached tenants by invoking the factory function. - /// - public void RefreshAll() - { - foreach (var key in _cache.Keys.ToArray()) - { - var newOptions = _optionsFactory(key); - _cache[key] = newOptions; - } - } -} - -/// -/// Thread-safe cache for query options keyed by entity type. -/// Useful when different entity types require different query configurations. -/// -/// The options type (must inherit from QueryOptionsBase). -public class EntityOptionsCache - where TOptions : QueryOptionsBase -{ - private readonly ConcurrentDictionary _cache = new(); - private readonly Func _optionsFactory; - - /// - /// Creates a new entity options cache with the specified factory function. - /// - /// Factory function that creates options for a given entity type. - public EntityOptionsCache(Func optionsFactory) - { - _optionsFactory = optionsFactory ?? throw new ArgumentNullException(nameof(optionsFactory)); - } - - /// - /// Gets or creates options for the specified entity type. - /// - /// The entity type. - /// The cached or newly created options for the entity type. - public TOptions GetOptions() - { - return GetOptions(typeof(TEntity)); - } - - /// - /// Gets or creates options for the specified entity type. - /// - /// The entity type. - /// The cached or newly created options for the entity type. - public TOptions GetOptions(Type entityType) - { - return _cache.GetOrAdd(entityType, _optionsFactory); - } - - /// - /// Sets options for the specified entity type. - /// - /// The entity type. - /// The options to cache. - public void SetOptions(TOptions options) - { - SetOptions(typeof(TEntity), options); - } - - /// - /// Sets options for the specified entity type. - /// - /// The entity type. - /// The options to cache. - public void SetOptions(Type entityType, TOptions options) - { - _cache[entityType] = options; - } - - /// - /// Removes cached options for the specified entity type. - /// - /// The entity type. - /// True if options were removed. - public bool RemoveOptions() - { - return RemoveOptions(typeof(TEntity)); - } - - /// - /// Removes cached options for the specified entity type. - /// - /// The entity type. - /// True if options were removed. - public bool RemoveOptions(Type entityType) - { - return _cache.TryRemove(entityType, out _); - } - - /// - /// Clears all cached options. - /// - public void Clear() - { - _cache.Clear(); - } - - /// - /// Gets the number of cached entity type options. - /// - public int Count => _cache.Count; - - /// - /// Refreshes options for the specified entity type. - /// - /// The entity type. - /// The refreshed options. - public TOptions RefreshOptions() - { - return RefreshOptions(typeof(TEntity)); - } - - /// - /// Refreshes options for the specified entity type. - /// - /// The entity type. - /// The refreshed options. - public TOptions RefreshOptions(Type entityType) - { - var newOptions = _optionsFactory(entityType); - _cache[entityType] = newOptions; - return newOptions; - } -} - -/// -/// Thread-safe cache for query options keyed by both tenant and entity type. -/// Supports scenarios where each tenant may have different configurations per entity type. -/// -/// The tenant identifier type. -/// The options type (must inherit from QueryOptionsBase). -public class TenantEntityOptionsCache - where TTenantKey : notnull - where TOptions : QueryOptionsBase -{ - private readonly ConcurrentDictionary<(TTenantKey, Type), TOptions> _cache = new(); - private readonly Func _optionsFactory; - - /// - /// Creates a new tenant-entity options cache with the specified factory function. - /// - /// Factory function that creates options for a given tenant and entity type. - public TenantEntityOptionsCache(Func optionsFactory) - { - _optionsFactory = optionsFactory ?? throw new ArgumentNullException(nameof(optionsFactory)); - } - - /// - /// Gets or creates options for the specified tenant and entity type. - /// - /// The entity type. - /// The tenant identifier. - /// The cached or newly created options. - public TOptions GetOptions(TTenantKey tenantKey) - { - return GetOptions(tenantKey, typeof(TEntity)); - } - - /// - /// Gets or creates options for the specified tenant and entity type. - /// - /// The tenant identifier. - /// The entity type. - /// The cached or newly created options. - public TOptions GetOptions(TTenantKey tenantKey, Type entityType) - { - return _cache.GetOrAdd((tenantKey, entityType), key => _optionsFactory(key.Item1, key.Item2)); - } - - /// - /// Tries to get cached options for the specified tenant and entity type. - /// - /// The entity type. - /// The tenant identifier. - /// The cached options if found. - /// True if options were found in the cache. - public bool TryGetOptions(TTenantKey tenantKey, out TOptions? options) - { - return TryGetOptions(tenantKey, typeof(TEntity), out options); - } - - /// - /// Tries to get cached options for the specified tenant and entity type. - /// - /// The tenant identifier. - /// The entity type. - /// The cached options if found. - /// True if options were found in the cache. - public bool TryGetOptions(TTenantKey tenantKey, Type entityType, out TOptions? options) - { - return _cache.TryGetValue((tenantKey, entityType), out options); - } - - /// - /// Sets options for the specified tenant and entity type. - /// - /// The entity type. - /// The tenant identifier. - /// The options to cache. - public void SetOptions(TTenantKey tenantKey, TOptions options) - { - SetOptions(tenantKey, typeof(TEntity), options); - } - - /// - /// Sets options for the specified tenant and entity type. - /// - /// The tenant identifier. - /// The entity type. - /// The options to cache. - public void SetOptions(TTenantKey tenantKey, Type entityType, TOptions options) - { - _cache[(tenantKey, entityType)] = options; - } - - /// - /// Removes cached options for the specified tenant and entity type. - /// - /// The entity type. - /// The tenant identifier. - /// True if options were removed. - public bool RemoveOptions(TTenantKey tenantKey) - { - return RemoveOptions(tenantKey, typeof(TEntity)); - } - - /// - /// Removes cached options for the specified tenant and entity type. - /// - /// The tenant identifier. - /// The entity type. - /// True if options were removed. - public bool RemoveOptions(TTenantKey tenantKey, Type entityType) - { - return _cache.TryRemove((tenantKey, entityType), out _); - } - - /// - /// Removes all cached options for the specified tenant. - /// - /// The tenant identifier. - /// The number of options removed. - public int RemoveTenant(TTenantKey tenantKey) - { - var keysToRemove = _cache.Keys.Where(k => EqualityComparer.Default.Equals(k.Item1, tenantKey)).ToList(); - int removed = 0; - foreach (var key in keysToRemove) - { - if (_cache.TryRemove(key, out _)) - removed++; - } - return removed; - } - - /// - /// Removes all cached options for the specified entity type across all tenants. - /// - /// The entity type. - /// The number of options removed. - public int RemoveEntityType() - { - return RemoveEntityType(typeof(TEntity)); - } - - /// - /// Removes all cached options for the specified entity type across all tenants. - /// - /// The entity type. - /// The number of options removed. - public int RemoveEntityType(Type entityType) - { - var keysToRemove = _cache.Keys.Where(k => k.Item2 == entityType).ToList(); - int removed = 0; - foreach (var key in keysToRemove) - { - if (_cache.TryRemove(key, out _)) - removed++; - } - return removed; - } - - /// - /// Clears all cached options. - /// - public void Clear() - { - _cache.Clear(); - } - - /// - /// Gets the number of cached options. - /// - public int Count => _cache.Count; - - /// - /// Gets all cached tenant keys. - /// - public IEnumerable CachedTenants => _cache.Keys.Select(k => k.Item1).Distinct(); - - /// - /// Gets all cached entity types. - /// - public IEnumerable CachedEntityTypes => _cache.Keys.Select(k => k.Item2).Distinct(); - - /// - /// Refreshes options for the specified tenant and entity type. - /// - /// The entity type. - /// The tenant identifier. - /// The refreshed options. - public TOptions RefreshOptions(TTenantKey tenantKey) - { - return RefreshOptions(tenantKey, typeof(TEntity)); - } - - /// - /// Refreshes options for the specified tenant and entity type. - /// - /// The tenant identifier. - /// The entity type. - /// The refreshed options. - public TOptions RefreshOptions(TTenantKey tenantKey, Type entityType) - { - var newOptions = _optionsFactory(tenantKey, entityType); - _cache[(tenantKey, entityType)] = newOptions; - return newOptions; - } - - /// - /// Refreshes all options for the specified tenant. - /// - /// The tenant identifier. - public void RefreshTenant(TTenantKey tenantKey) - { - var keysToRefresh = _cache.Keys.Where(k => EqualityComparer.Default.Equals(k.Item1, tenantKey)).ToList(); - foreach (var key in keysToRefresh) - { - var newOptions = _optionsFactory(key.Item1, key.Item2); - _cache[key] = newOptions; - } - } -} - -/// -/// Builder for creating tenant options caches with fluent configuration. -/// -/// The tenant identifier type. -/// The options type (must inherit from QueryOptionsBase). -public class TenantOptionsCacheBuilder - where TKey : notnull - where TOptions : QueryOptionsBase -{ - private Func? _optionsFactory; - private readonly Dictionary _preloadedOptions = new(); - - /// - /// Sets the factory function for creating tenant options. - /// - public TenantOptionsCacheBuilder WithFactory(Func factory) - { - _optionsFactory = factory; - return this; - } - - /// - /// Preloads options for a specific tenant. - /// - public TenantOptionsCacheBuilder WithTenant(TKey tenantKey, TOptions options) - { - _preloadedOptions[tenantKey] = options; - return this; - } - - /// - /// Preloads options for a specific tenant using a configuration action. - /// - public TenantOptionsCacheBuilder WithTenant(TKey tenantKey, Func optionsFactory) - { - _preloadedOptions[tenantKey] = optionsFactory(); - return this; - } - - /// - /// Builds the tenant options cache. - /// - public TenantOptionsCache Build() - { - if (_optionsFactory is null) - throw new InvalidOperationException("Options factory must be configured using WithFactory()."); - - var cache = new TenantOptionsCache(_optionsFactory); - - // Preload any configured tenant options - foreach (var kvp in _preloadedOptions) - { - cache.SetOptions(kvp.Key, kvp.Value); - } - - return cache; - } -} - -/// -/// Static helper methods for creating options caches. -/// -public static class TenantOptionsCache -{ - /// - /// Creates a new tenant options cache builder. - /// - public static TenantOptionsCacheBuilder Create() - where TKey : notnull - where TOptions : QueryOptionsBase - { - return new TenantOptionsCacheBuilder(); - } - - /// - /// Creates a new tenant options cache with the specified factory. - /// - public static TenantOptionsCache Create(Func optionsFactory) - where TKey : notnull - where TOptions : QueryOptionsBase - { - return new TenantOptionsCache(optionsFactory); - } - - /// - /// Creates a new entity options cache with the specified factory. - /// - public static EntityOptionsCache CreateByEntityType(Func optionsFactory) - where TOptions : QueryOptionsBase - { - return new EntityOptionsCache(optionsFactory); - } - - /// - /// Creates a new tenant-entity options cache with the specified factory. - /// - public static TenantEntityOptionsCache CreateByTenantAndEntityType( - Func optionsFactory) - where TTenantKey : notnull - where TOptions : QueryOptionsBase - { - return new TenantEntityOptionsCache(optionsFactory); - } -} diff --git a/src/Foundatio.Lucene/VisitorPool.cs b/src/Foundatio.Lucene/VisitorPool.cs deleted file mode 100644 index 057161b..0000000 --- a/src/Foundatio.Lucene/VisitorPool.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System.Collections.Concurrent; - -namespace Foundatio.Lucene; - -/// -/// Simple object pool for reusing visitor instances across requests. -/// -public sealed class VisitorPool where T : class, new() -{ - private readonly ConcurrentBag _pool = new(); - private readonly int _maxPoolSize; - - /// - /// Creates a new visitor pool with the specified maximum size. - /// - public VisitorPool(int maxPoolSize = 64) - { - _maxPoolSize = maxPoolSize; - } - - /// - /// Rents a visitor instance from the pool or creates a new one. - /// - public T Rent() - { - return _pool.TryTake(out var visitor) ? visitor : new T(); - } - - /// - /// Returns a visitor instance to the pool for reuse. - /// - public void Return(T visitor) - { - if (_pool.Count < _maxPoolSize) - { - _pool.Add(visitor); - } - } -} From 2fb0cf05fc72b028284495c427274b0abd4f2d4c Mon Sep 17 00:00:00 2001 From: "Eric J. Smith" Date: Wed, 24 Jun 2026 23:58:09 -0500 Subject: [PATCH 03/10] M3: EF/ES parity - shared pipeline, capability model, cross-engine gate - EntityFrameworkQueryParser now runs the shared pre-build visitor pipeline (field-alias resolution, @include expansion, date-math evaluation) before building the LINQ expression, so per-scope FieldMap, includes, and date math behave identically to the Elasticsearch integration (previously silently ignored in SQL). Adds a configurable TimeProvider to the EF configuration. - Capability model: the EF builder throws QueryBuildException (UnsupportedQueryType) for fuzzy (term~N) and proximity/slop ("..."~N) queries instead of silently degrading them to substring matches. - Add Foundatio.Lucene.Parity.Tests: starts SQL Server + Elasticsearch containers, seeds identical data, and asserts the same Lucene query returns the same result set on both engines across the supported construct set. --- Foundatio.Lucene.slnx | 1 + .../EntityFrameworkQueryParser.cs | 44 +++++ ...EntityFrameworkQueryParserConfiguration.cs | 15 ++ .../ExpressionBuilderVisitor.cs | 8 + .../EntityFrameworkPipelineTests.cs | 99 ++++++++++ .../CrossEngineFixture.cs | 177 ++++++++++++++++++ .../CrossEngineParityTests.cs | 39 ++++ .../Foundatio.Lucene.Parity.Tests.csproj | 15 ++ 8 files changed, 398 insertions(+) create mode 100644 tests/Foundatio.Lucene.EntityFramework.Tests/EntityFrameworkPipelineTests.cs create mode 100644 tests/Foundatio.Lucene.Parity.Tests/CrossEngineFixture.cs create mode 100644 tests/Foundatio.Lucene.Parity.Tests/CrossEngineParityTests.cs create mode 100644 tests/Foundatio.Lucene.Parity.Tests/Foundatio.Lucene.Parity.Tests.csproj diff --git a/Foundatio.Lucene.slnx b/Foundatio.Lucene.slnx index 8fadcb0..ecb9fda 100644 --- a/Foundatio.Lucene.slnx +++ b/Foundatio.Lucene.slnx @@ -13,6 +13,7 @@ + diff --git a/src/Foundatio.Lucene.EntityFramework/EntityFrameworkQueryParser.cs b/src/Foundatio.Lucene.EntityFramework/EntityFrameworkQueryParser.cs index c96d868..4c8640a 100644 --- a/src/Foundatio.Lucene.EntityFramework/EntityFrameworkQueryParser.cs +++ b/src/Foundatio.Lucene.EntityFramework/EntityFrameworkQueryParser.cs @@ -1,6 +1,8 @@ using System.Collections.Concurrent; using System.Linq.Expressions; using System.Reflection; +using Foundatio.Lucene.Ast; +using Foundatio.Lucene.Visitors; using Microsoft.EntityFrameworkCore.Metadata; namespace Foundatio.Lucene.EntityFramework; @@ -14,6 +16,12 @@ public class EntityFrameworkQueryParser private static readonly ConcurrentDictionary> _reflectionFieldCache = new(); private readonly ConcurrentDictionary _entityTypeOptions = new(); + // Stateless visitors reused as singletons; per-request configuration (field map, + // includes) is carried on the visitor context, so no visitor is allocated per query. + private readonly FieldResolverQueryVisitor _fieldResolverVisitor = new(); + private readonly IncludeVisitor _includeVisitor = new(); + private readonly DateMathEvaluatorVisitor _dateMathVisitor; + /// /// Creates a new EntityFrameworkQueryParser with optional configuration. /// @@ -22,6 +30,7 @@ public EntityFrameworkQueryParser(Action @@ -146,6 +155,7 @@ public Expression> BuildFilter(string query, EntityFrameworkQue SetupContextDefaults(context, options); var document = ParseQuery(query); + ApplyVisitorPipeline(document, context, typeof(T), options); return ExpressionBuilderVisitor.Instance.BuildExpression(document, context, Configuration); } @@ -263,6 +273,7 @@ public LambdaExpression BuildFilter(Type entityType, string query, EntityFramewo SetupContextDefaults(entityType, context, options); var document = ParseQuery(query); + ApplyVisitorPipeline(document, context, entityType, options); return ExpressionBuilderVisitor.Instance.BuildExpression(entityType, document, context, Configuration); } @@ -307,6 +318,39 @@ private Ast.QueryDocument ParseQuery(string query) return parseResult.Document; } + /// + /// Runs the shared pre-build visitor pipeline (field alias resolution, @include expansion, + /// and date-math evaluation) over the parsed document so these behave identically to the + /// Elasticsearch integration. Per-scope field map and includes come from per-request options + /// (highest precedence) then options registered for the entity type. + /// + private void ApplyVisitorPipeline(Ast.QueryDocument document, EntityFrameworkQueryVisitorContext context, Type entityType, EntityFrameworkQueryOptions? options) + { + if (document.Query is null) + return; + + var registeredOptions = GetOptions(entityType); + + // Resolve field aliases (per-request > registered) + var fieldMap = options?.FieldMap ?? registeredOptions?.FieldMap; + if (fieldMap is not null) + { + context.SetFieldMap(fieldMap); + document.Query = _fieldResolverVisitor.Accept(document.Query, context); + } + + // Expand @includes (per-request > registered) + var includes = options?.Includes ?? registeredOptions?.Includes; + if (includes is not null) + { + context.SetIncludes(includes); + document.Query = _includeVisitor.Accept(document.Query, context); + } + + // Evaluate date math (now-7d, now/d, 2024-01-01||+1M, ...) + document.Query = _dateMathVisitor.Accept(document.Query, context); + } + /// /// Gets a visitor context initialized with field information from an EF entity type. /// diff --git a/src/Foundatio.Lucene.EntityFramework/EntityFrameworkQueryParserConfiguration.cs b/src/Foundatio.Lucene.EntityFramework/EntityFrameworkQueryParserConfiguration.cs index 2f6577e..c7075f0 100644 --- a/src/Foundatio.Lucene.EntityFramework/EntityFrameworkQueryParserConfiguration.cs +++ b/src/Foundatio.Lucene.EntityFramework/EntityFrameworkQueryParserConfiguration.cs @@ -98,6 +98,12 @@ public class EntityFrameworkQueryParserConfiguration /// public Func DateOnlyParser { get; private set; } = EntityFrameworkQueryVisitorContext.DefaultDateOnlyParser; + /// + /// Time provider controlling 'now' in date math expressions (e.g., now-7d, now/d). + /// Defaults to . + /// + public TimeProvider TimeProvider { get; private set; } = TimeProvider.System; + /// /// Filter to exclude specific properties from field discovery. /// Default includes all properties. @@ -188,6 +194,15 @@ public EntityFrameworkQueryParserConfiguration SetDateOnlyParser(Func + /// Sets the time provider controlling 'now' in date math expressions. + /// + public EntityFrameworkQueryParserConfiguration SetTimeProvider(TimeProvider timeProvider) + { + TimeProvider = timeProvider ?? throw new ArgumentNullException(nameof(timeProvider)); + return this; + } + /// /// Sets a filter for entity type properties. /// diff --git a/src/Foundatio.Lucene.EntityFramework/ExpressionBuilderVisitor.cs b/src/Foundatio.Lucene.EntityFramework/ExpressionBuilderVisitor.cs index 65e9a7d..c4ceca6 100644 --- a/src/Foundatio.Lucene.EntityFramework/ExpressionBuilderVisitor.cs +++ b/src/Foundatio.Lucene.EntityFramework/ExpressionBuilderVisitor.cs @@ -162,6 +162,10 @@ protected override QueryNode Visit(FieldQueryNode node, IEntityFrameworkQueryVis /// protected override QueryNode Visit(TermNode node, IEntityFrameworkQueryVisitorContext context) { + // Fail loudly rather than silently degrading: SQL cannot honor fuzzy matching. + if (node.FuzzyDistance.HasValue) + throw new QueryBuildException("Fuzzy queries (term~N) are not supported by the Entity Framework provider.", QueryErrorCode.UnsupportedQueryType); + var field = context.CurrentField; var term = node.UnescapedTerm; @@ -173,6 +177,10 @@ protected override QueryNode Visit(TermNode node, IEntityFrameworkQueryVisitorCo /// protected override QueryNode Visit(PhraseNode node, IEntityFrameworkQueryVisitorContext context) { + // Fail loudly rather than silently degrading: SQL cannot honor proximity/slop matching. + if (node.Slop.HasValue) + throw new QueryBuildException("Proximity/slop queries (\"...\"~N) are not supported by the Entity Framework provider.", QueryErrorCode.UnsupportedQueryType); + var field = context.CurrentField; var phrase = node.Phrase; diff --git a/tests/Foundatio.Lucene.EntityFramework.Tests/EntityFrameworkPipelineTests.cs b/tests/Foundatio.Lucene.EntityFramework.Tests/EntityFrameworkPipelineTests.cs new file mode 100644 index 0000000..0cdf100 --- /dev/null +++ b/tests/Foundatio.Lucene.EntityFramework.Tests/EntityFrameworkPipelineTests.cs @@ -0,0 +1,99 @@ +using Microsoft.EntityFrameworkCore; + +namespace Foundatio.Lucene.EntityFramework.Tests; + +/// +/// Verifies the EF parser runs the shared visitor pipeline (field aliases, @includes, date math) +/// and fails loudly for constructs SQL cannot honor (fuzzy, proximity/slop). +/// +public class EntityFrameworkPipelineTests +{ + private sealed class FixedTimeProvider(DateTimeOffset now) : TimeProvider + { + public override DateTimeOffset GetUtcNow() => now; + } + + private static SampleContext CreateContext() + { + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()) + .Options; + + var context = new SampleContext(options); + context.Companies.Add(new Company { Id = 1, Name = "Acme Corp", Location = "New York", FoundedYear = 2000, IsPublic = true }); + context.Employees.AddRange( + new Employee { Id = 1, Name = "John Doe", Email = "john@acme.com", Title = "Software Developer", Salary = 80000, Age = 30, HireDate = new DateTime(2020, 1, 15), IsActive = true, CompanyId = 1 }, + new Employee { Id = 2, Name = "Jane Smith", Email = "jane@acme.com", Title = "Project Manager", Salary = 95000, Age = 35, HireDate = new DateTime(2019, 6, 1), IsActive = true, CompanyId = 1 }, + new Employee { Id = 3, Name = "Bob Wilson", Email = "bob@tech.com", Title = "Senior Developer", Salary = 110000, Age = 40, HireDate = new DateTime(2018, 3, 20), IsActive = true, CompanyId = 1 }); + context.SaveChanges(); + return context; + } + + [Fact] + public void BuildFilter_WithPerRequestFieldMapAlias_ResolvesToRealField() + { + using var context = CreateContext(); + var parser = new EntityFrameworkQueryParser(); + var options = new EntityFrameworkQueryOptionsBuilder() + .WithFieldMap(new FieldMap { { "user", "Name" } }) + .Build(); + + var filter = parser.BuildFilter("user:John", context: null, options: options); + var results = context.Employees.Where(filter).ToList(); + + Assert.Single(results); + Assert.Equal("John Doe", results[0].Name); + } + + [Fact] + public void BuildFilter_WithPerRequestIncludes_ExpandsReference() + { + using var context = CreateContext(); + var parser = new EntityFrameworkQueryParser(); + var options = new EntityFrameworkQueryOptionsBuilder() + .WithIncludes(new Dictionary { ["seniors"] = "Title:Senior" }) + .Build(); + + var filter = parser.BuildFilter("@include:seniors", context: null, options: options); + var results = context.Employees.Where(filter).ToList(); + + Assert.Single(results); + Assert.Equal("Bob Wilson", results[0].Name); + } + + [Fact] + public void BuildFilter_WithDateMath_ResolvesNowRelativeToTimeProvider() + { + using var context = CreateContext(); + var parser = new EntityFrameworkQueryParser(c => + c.SetTimeProvider(new FixedTimeProvider(new DateTimeOffset(2020, 1, 20, 0, 0, 0, TimeSpan.Zero)))); + + // John was hired 2020-01-15, inside [now-7d TO now]; the others were hired years earlier. + var filter = parser.BuildFilter("HireDate:[now-7d TO now]"); + var results = context.Employees.Where(filter).ToList(); + + Assert.Single(results); + Assert.Equal("John Doe", results[0].Name); + } + + [Fact] + public void BuildFilter_FuzzyQuery_ThrowsUnsupported() + { + using var context = CreateContext(); + var parser = new EntityFrameworkQueryParser(); + + var ex = Assert.Throws(() => parser.BuildFilter("Name:jon~2")); + Assert.Equal(QueryErrorCode.UnsupportedQueryType, ex.ErrorCode); + } + + [Fact] + public void TryBuildFilter_ProximityQuery_ReturnsFailure() + { + using var context = CreateContext(); + var parser = new EntityFrameworkQueryParser(); + + var result = parser.TryBuildFilter("Title:\"Software Developer\"~2"); + + Assert.False(result.IsSuccess); + } +} diff --git a/tests/Foundatio.Lucene.Parity.Tests/CrossEngineFixture.cs b/tests/Foundatio.Lucene.Parity.Tests/CrossEngineFixture.cs new file mode 100644 index 0000000..044ab70 --- /dev/null +++ b/tests/Foundatio.Lucene.Parity.Tests/CrossEngineFixture.cs @@ -0,0 +1,177 @@ +using DotNet.Testcontainers.Builders; +using DotNet.Testcontainers.Containers; +using Elastic.Clients.Elasticsearch; +using Elastic.Transport; +using Foundatio.Lucene.Elasticsearch; +using Foundatio.Lucene.EntityFramework; +using Microsoft.EntityFrameworkCore; +using Testcontainers.MsSql; + +namespace Foundatio.Lucene.Parity.Tests; + +/// +/// Starts a SQL Server and an Elasticsearch container, seeds identical data into both, and runs +/// the same Lucene query through the EntityFramework and Elasticsearch parsers so tests can assert +/// the two engines return the same result set for the supported-on-both construct set. +/// +public class CrossEngineFixture : IAsyncLifetime +{ + private const string IndexName = "parity-docs"; + private const int ElasticsearchPort = 9200; + private const string EsUser = "elastic"; + private const string EsPassword = "elastic_password_123"; + + private readonly MsSqlContainer _sql; + private readonly IContainer _es; + private ElasticsearchClient _esClient = null!; + private string _connectionString = null!; + + // Names and categories are deliberately distinct, non-substring values so SQL Contains and ES + // keyword term matching agree (true result-set parity for equality queries). Dates sit well + // inside the test range boundaries so inclusive/exclusive day rounding never flips a result. + private static readonly Doc[] SeedDocs = + [ + new() { Id = 1, Name = "alpha", Category = "engineering", Age = 30, Salary = 80000, Active = true, Created = new DateTime(2020, 6, 15), Notes = "note-one" }, + new() { Id = 2, Name = "bravo", Category = "sales", Age = 35, Salary = 95000, Active = true, Created = new DateTime(2019, 3, 10), Notes = null }, + new() { Id = 3, Name = "charlie", Category = "research", Age = 40, Salary = 110000, Active = true, Created = new DateTime(2018, 9, 20), Notes = "note-three" }, + new() { Id = 4, Name = "delta", Category = "engineering", Age = 25, Salary = 55000, Active = false, Created = new DateTime(2022, 11, 5), Notes = null }, + new() { Id = 5, Name = "echo", Category = "research", Age = 50, Salary = 130000, Active = false, Created = new DateTime(2021, 1, 25), Notes = "note-five" }, + ]; + + public EntityFrameworkQueryParser EfParser { get; } = new(); + + public ElasticsearchQueryParser EsParser { get; } = new(c => + { + // Filter context (term/range) so string equality matches SQL's exact-ish Contains on the + // non-substring test data, and date fields produce real date range queries. + c.UseScoring = false; + c.IsDateField = f => string.Equals(f, "created", StringComparison.OrdinalIgnoreCase); + }); + + public CrossEngineFixture() + { + _sql = new MsSqlBuilder("mcr.microsoft.com/mssql/server:2022-latest").Build(); + + // Testcontainers.Elasticsearch does not yet support 9.x, so build the container directly + // (mirrors the Elasticsearch.Tests fixture). + _es = new ContainerBuilder("docker.elastic.co/elasticsearch/elasticsearch:9.0.0") + .WithPortBinding(ElasticsearchPort, true) + .WithEnvironment("discovery.type", "single-node") + .WithEnvironment("ELASTIC_PASSWORD", EsPassword) + .WithEnvironment("xpack.security.enabled", "true") + .WithEnvironment("xpack.security.http.ssl.enabled", "false") + .WithWaitStrategy(Wait.ForUnixContainer() + .UntilHttpRequestIsSucceeded(r => r + .ForPort(ElasticsearchPort) + .ForPath("/_cluster/health") + .WithBasicAuthentication(EsUser, EsPassword))) + .Build(); + } + + public async ValueTask InitializeAsync() + { + await Task.WhenAll(_sql.StartAsync(), _es.StartAsync()); + + _connectionString = _sql.GetConnectionString(); + + var uri = new Uri($"http://{_es.Hostname}:{_es.GetMappedPublicPort(ElasticsearchPort)}"); + _esClient = new ElasticsearchClient(new ElasticsearchClientSettings(uri) + .Authentication(new BasicAuthentication(EsUser, EsPassword))); + + await SeedSqlAsync(); + await SeedElasticsearchAsync(); + } + + public async ValueTask DisposeAsync() + { + await _sql.DisposeAsync(); + await _es.DisposeAsync(); + } + + /// Runs the query through the EF parser against SQL Server and returns matching ids. + public List QuerySql(string query) + { + using var db = CreateDb(); + var filter = EfParser.BuildFilter(query); + return db.Docs.Where(filter).Select(d => d.Id).ToList(); + } + + /// Runs the query through the ES parser against Elasticsearch and returns matching ids. + public async Task> QueryElasticsearchAsync(string query) + { + var esQuery = EsParser.BuildQuery(query); + var response = await _esClient.SearchAsync(s => s + .Indices(IndexName) + .Size(100) + .Query(esQuery)); + + if (!response.IsValidResponse) + throw new InvalidOperationException($"Elasticsearch query failed: {response.DebugInformation}"); + + return response.Documents.Select(d => d.Id).ToList(); + } + + private ParityDbContext CreateDb() + => new(new DbContextOptionsBuilder().UseSqlServer(_connectionString).Options); + + private async Task SeedSqlAsync() + { + await using var db = CreateDb(); + await db.Database.EnsureCreatedAsync(); + db.Docs.AddRange(SeedDocs); + await db.SaveChangesAsync(); + } + + private async Task SeedElasticsearchAsync() + { + var create = await _esClient.Indices.CreateAsync(IndexName, c => c + .Mappings(m => m + .Properties(p => p + .IntegerNumber(d => d.Id) + .Keyword(d => d.Name) + .Keyword(d => d.Category) + .IntegerNumber(d => d.Age) + .DoubleNumber(d => d.Salary) + .Boolean(d => d.Active) + .Date(d => d.Created) + .Keyword(d => d.Notes!)))); + + if (!create.IsValidResponse) + throw new InvalidOperationException($"Failed to create index: {create.DebugInformation}"); + + var bulk = await _esClient.BulkAsync(b => b + .Index(IndexName) + .IndexMany(SeedDocs) + .Refresh(Refresh.True)); + + if (!bulk.IsValidResponse) + throw new InvalidOperationException($"Failed to seed Elasticsearch: {bulk.DebugInformation}"); + } +} + +/// Document shared by the SQL (EF entity) and Elasticsearch (indexed document) sides. +public class Doc +{ + public int Id { get; set; } + public string Name { get; set; } = ""; + public string Category { get; set; } = ""; + public int Age { get; set; } + public double Salary { get; set; } + public bool Active { get; set; } + public DateTime Created { get; set; } + public string? Notes { get; set; } +} + +public class ParityDbContext(DbContextOptions options) : DbContext(options) +{ + public DbSet Docs => Set(); + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + // Use the seeded ids verbatim so they line up with the Elasticsearch documents. + modelBuilder.Entity().Property(d => d.Id).ValueGeneratedNever(); + } +} + +[CollectionDefinition("CrossEngine")] +public class CrossEngineCollection : ICollectionFixture; diff --git a/tests/Foundatio.Lucene.Parity.Tests/CrossEngineParityTests.cs b/tests/Foundatio.Lucene.Parity.Tests/CrossEngineParityTests.cs new file mode 100644 index 0000000..f7154ce --- /dev/null +++ b/tests/Foundatio.Lucene.Parity.Tests/CrossEngineParityTests.cs @@ -0,0 +1,39 @@ +namespace Foundatio.Lucene.Parity.Tests; + +/// +/// Strict cross-engine parity gate: the same Lucene query must return the same result set from +/// SQL Server (via the EntityFramework parser) and Elasticsearch, for every construct both engines +/// support. Constructs SQL cannot honor (fuzzy, regex, proximity) are intentionally excluded — they +/// are covered as engine-specific behavior elsewhere. +/// +[Collection("CrossEngine")] +public class CrossEngineParityTests(CrossEngineFixture fixture) +{ + public static IEnumerable ParityQueries() => + [ + ["*:*", new[] { 1, 2, 3, 4, 5 }], + ["age:[30 TO 40]", new[] { 1, 2, 3 }], + ["age:>35", new[] { 3, 5 }], + ["salary:<90000", new[] { 1, 4 }], + ["category:engineering", new[] { 1, 4 }], + ["name:alpha", new[] { 1 }], + ["category:research AND active:true", new[] { 3 }], + ["category:engineering OR category:sales", new[] { 1, 2, 4 }], + ["NOT active:true", new[] { 4, 5 }], + ["_exists_:notes", new[] { 1, 3, 5 }], + ["created:[2020-01-01 TO 2021-12-31]", new[] { 1, 5 }], + ]; + + [Theory] + [MemberData(nameof(ParityQueries))] + public async Task Query_ReturnsSameResultSetOnSqlAndElasticsearch(string query, int[] expectedIds) + { + var expected = expectedIds.OrderBy(id => id).ToArray(); + + var sqlIds = fixture.QuerySql(query).OrderBy(id => id).ToArray(); + var esIds = (await fixture.QueryElasticsearchAsync(query)).OrderBy(id => id).ToArray(); + + Assert.Equal(expected, sqlIds); + Assert.Equal(expected, esIds); + } +} diff --git a/tests/Foundatio.Lucene.Parity.Tests/Foundatio.Lucene.Parity.Tests.csproj b/tests/Foundatio.Lucene.Parity.Tests/Foundatio.Lucene.Parity.Tests.csproj new file mode 100644 index 0000000..d24ef42 --- /dev/null +++ b/tests/Foundatio.Lucene.Parity.Tests/Foundatio.Lucene.Parity.Tests.csproj @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + From a96ba78010caa0917cc2f29ef00578e2df56d4ae Mon Sep 17 00:00:00 2001 From: "Eric J. Smith" Date: Thu, 25 Jun 2026 00:03:23 -0500 Subject: [PATCH 04/10] M4: lock the public API for 1.0 - Remove the dead Elasticsearch geo surface (IsGeoPointField, GeoLocationResolver, UseGeoFields/UseGeoLocationResolver/WithGeoPointFields, context geo members and the geo lines in CreateContext). The builder never emitted geo queries and the async resolver could not be awaited in the synchronous pipeline; geo is deferred to a post-1.0 design that keeps the visitor pipeline synchronous. - Unify the duplicate default-operator enum: Elasticsearch now uses Foundatio.Lucene.Ast.BooleanOperator everywhere and the separate QueryOperator enum is deleted. - Make LuceneParseResult.Document/Errors init-only. - Fix EntityFieldInfo equality/hash to key on FullName instead of the leaf Name (nested fields sharing a leaf name no longer collide) and remove the unused public IsMoney property. --- .../ElasticsearchQueryBuilderVisitor.cs | 2 +- .../ElasticsearchQueryOptions.cs | 26 ---------------- .../ElasticsearchQueryParser.cs | 4 +-- .../ElasticsearchQueryParserConfiguration.cs | 14 ++------- ...earchQueryParserConfigurationExtensions.cs | 22 ++------------ .../ElasticsearchQueryVisitorContext.cs | 30 ++----------------- ...sticsearchQueryVisitorContextExtensions.cs | 24 +++------------ .../EntityFieldInfo.cs | 9 ++---- src/Foundatio.Lucene/LuceneParseResult.cs | 4 +-- .../ElasticsearchQueryParserTests.cs | 3 +- 10 files changed, 20 insertions(+), 118 deletions(-) diff --git a/src/Foundatio.Lucene.Elasticsearch/ElasticsearchQueryBuilderVisitor.cs b/src/Foundatio.Lucene.Elasticsearch/ElasticsearchQueryBuilderVisitor.cs index 9b48ff5..5fdd586 100644 --- a/src/Foundatio.Lucene.Elasticsearch/ElasticsearchQueryBuilderVisitor.cs +++ b/src/Foundatio.Lucene.Elasticsearch/ElasticsearchQueryBuilderVisitor.cs @@ -134,7 +134,7 @@ protected override QueryNode Visit(BooleanQueryNode node, IElasticsearchQueryVis break; case Occur.Should: // Check operator to determine if this should be Must or Should - if (clause.Operator == BooleanOperator.And || context.DefaultOperator == QueryOperator.And) + if (clause.Operator == BooleanOperator.And || context.DefaultOperator == BooleanOperator.And) mustClauses.Add(clauseQuery); else shouldClauses.Add(clauseQuery); diff --git a/src/Foundatio.Lucene.Elasticsearch/ElasticsearchQueryOptions.cs b/src/Foundatio.Lucene.Elasticsearch/ElasticsearchQueryOptions.cs index 356f32e..cb69bc5 100644 --- a/src/Foundatio.Lucene.Elasticsearch/ElasticsearchQueryOptions.cs +++ b/src/Foundatio.Lucene.Elasticsearch/ElasticsearchQueryOptions.cs @@ -16,11 +16,6 @@ public sealed record ElasticsearchQueryOptions : QueryOptionsBase /// public string? DefaultTimeZone { get; init; } - /// - /// Function to determine if a field is a geo point field. Overrides global IsGeoPointField if provided. - /// - public Func? IsGeoPointField { get; init; } - /// /// Function to determine if a field is a date field. Overrides global IsDateField if provided. /// @@ -43,7 +38,6 @@ public class ElasticsearchQueryOptionsBuilder private string[]? _defaultFields; private bool? _useScoring; private string? _defaultTimeZone; - private Func? _isGeoPointField; private Func? _isDateField; /// @@ -139,25 +133,6 @@ public ElasticsearchQueryOptionsBuilder WithDefaultTimeZone(string timeZone) return this; } - /// - /// Sets the function to determine if a field is a geo point field. - /// - public ElasticsearchQueryOptionsBuilder WithGeoPointFields(Func isGeoPointField) - { - _isGeoPointField = isGeoPointField; - return this; - } - - /// - /// Sets the function to determine if a field is a geo point field using a set of field names. - /// - public ElasticsearchQueryOptionsBuilder WithGeoPointFields(params string[] fieldNames) - { - var fieldSet = new HashSet(fieldNames, StringComparer.OrdinalIgnoreCase); - _isGeoPointField = field => fieldSet.Contains(field); - return this; - } - /// /// Sets the function to determine if a field is a date field. /// @@ -190,7 +165,6 @@ public ElasticsearchQueryOptions Build() DefaultFields = _defaultFields, UseScoring = _useScoring, DefaultTimeZone = _defaultTimeZone, - IsGeoPointField = _isGeoPointField, IsDateField = _isDateField }; } diff --git a/src/Foundatio.Lucene.Elasticsearch/ElasticsearchQueryParser.cs b/src/Foundatio.Lucene.Elasticsearch/ElasticsearchQueryParser.cs index eaa1319..d848d7b 100644 --- a/src/Foundatio.Lucene.Elasticsearch/ElasticsearchQueryParser.cs +++ b/src/Foundatio.Lucene.Elasticsearch/ElasticsearchQueryParser.cs @@ -238,10 +238,8 @@ private ElasticsearchQueryVisitorContext CreateContext(ElasticsearchQueryOptions UseScoring = options?.UseScoring ?? registeredOptions?.UseScoring ?? _config.UseScoring, DefaultFields = options?.DefaultFields ?? registeredOptions?.DefaultFields ?? _config.DefaultFields, DefaultOperator = _config.DefaultOperator, - IsGeoPointField = options?.IsGeoPointField ?? registeredOptions?.IsGeoPointField ?? _config.IsGeoPointField, IsDateField = options?.IsDateField ?? registeredOptions?.IsDateField ?? _config.IsDateField, - DefaultTimeZone = options?.DefaultTimeZone ?? registeredOptions?.DefaultTimeZone ?? _config.DefaultTimeZone, - GeoLocationResolver = _config.GeoLocationResolver + DefaultTimeZone = options?.DefaultTimeZone ?? registeredOptions?.DefaultTimeZone ?? _config.DefaultTimeZone }; // Set up validation options: per-request > registered > global diff --git a/src/Foundatio.Lucene.Elasticsearch/ElasticsearchQueryParserConfiguration.cs b/src/Foundatio.Lucene.Elasticsearch/ElasticsearchQueryParserConfiguration.cs index 936f818..cfda276 100644 --- a/src/Foundatio.Lucene.Elasticsearch/ElasticsearchQueryParserConfiguration.cs +++ b/src/Foundatio.Lucene.Elasticsearch/ElasticsearchQueryParserConfiguration.cs @@ -1,3 +1,5 @@ +using Foundatio.Lucene.Ast; + namespace Foundatio.Lucene.Elasticsearch; /// @@ -13,12 +15,7 @@ public class ElasticsearchQueryParserConfiguration : QueryParserConfigurationBas /// /// Default boolean operator for implicit combinations. /// - public QueryOperator DefaultOperator { get; set; } - - /// - /// Function to check if a field is a geo_point field. - /// - public Func? IsGeoPointField { get; set; } + public BooleanOperator DefaultOperator { get; set; } = BooleanOperator.Or; /// /// Function to check if a field is a date field. @@ -29,9 +26,4 @@ public class ElasticsearchQueryParserConfiguration : QueryParserConfigurationBas /// Default timezone for date range queries. /// public string? DefaultTimeZone { get; set; } - - /// - /// Function to resolve location strings to coordinates. - /// - public Func>? GeoLocationResolver { get; set; } } diff --git a/src/Foundatio.Lucene.Elasticsearch/ElasticsearchQueryParserConfigurationExtensions.cs b/src/Foundatio.Lucene.Elasticsearch/ElasticsearchQueryParserConfigurationExtensions.cs index 06d3413..c7f6ab6 100644 --- a/src/Foundatio.Lucene.Elasticsearch/ElasticsearchQueryParserConfigurationExtensions.cs +++ b/src/Foundatio.Lucene.Elasticsearch/ElasticsearchQueryParserConfigurationExtensions.cs @@ -22,14 +22,14 @@ public static ElasticsearchQueryParserConfiguration UseScoring(this Elasticsearc public static ElasticsearchQueryParserConfiguration UseSearchMode(this ElasticsearchQueryParserConfiguration config) { config.UseScoring = true; - config.DefaultOperator = QueryOperator.Or; + config.DefaultOperator = BooleanOperator.Or; return config; } /// /// Sets the default boolean operator. /// - public static ElasticsearchQueryParserConfiguration SetDefaultOperator(this ElasticsearchQueryParserConfiguration config, QueryOperator op) + public static ElasticsearchQueryParserConfiguration SetDefaultOperator(this ElasticsearchQueryParserConfiguration config, BooleanOperator op) { config.DefaultOperator = op; return config; @@ -62,24 +62,6 @@ public static ElasticsearchQueryParserConfiguration UseDateFields(this Elasticse return config; } - /// - /// Configures which fields are geo_point fields. - /// - public static ElasticsearchQueryParserConfiguration UseGeoFields(this ElasticsearchQueryParserConfiguration config, Func resolver) - { - config.IsGeoPointField = resolver; - return config; - } - - /// - /// Sets the geo location resolver. - /// - public static ElasticsearchQueryParserConfiguration UseGeoLocationResolver(this ElasticsearchQueryParserConfiguration config, Func> resolver) - { - config.GeoLocationResolver = resolver; - return config; - } - /// /// Sets the default timezone for date queries. /// diff --git a/src/Foundatio.Lucene.Elasticsearch/ElasticsearchQueryVisitorContext.cs b/src/Foundatio.Lucene.Elasticsearch/ElasticsearchQueryVisitorContext.cs index bb6bf91..b153396 100644 --- a/src/Foundatio.Lucene.Elasticsearch/ElasticsearchQueryVisitorContext.cs +++ b/src/Foundatio.Lucene.Elasticsearch/ElasticsearchQueryVisitorContext.cs @@ -1,17 +1,9 @@ using Elastic.Clients.Elasticsearch.QueryDsl; +using Foundatio.Lucene.Ast; using Foundatio.Lucene.Visitors; namespace Foundatio.Lucene.Elasticsearch; -/// -/// Boolean operator used when combining queries with implicit AND/OR. -/// -public enum QueryOperator -{ - Or, - And -} - /// /// Context interface for Elasticsearch query building. /// @@ -30,12 +22,7 @@ public interface IElasticsearchQueryVisitorContext : IQueryVisitorContext /// /// Default boolean operator for implicit combinations. /// - QueryOperator DefaultOperator { get; set; } - - /// - /// Function to check if a field is a geo_point field. - /// - Func? IsGeoPointField { get; set; } + BooleanOperator DefaultOperator { get; set; } /// /// Function to check if a field is a date field. @@ -47,11 +34,6 @@ public interface IElasticsearchQueryVisitorContext : IQueryVisitorContext /// string? DefaultTimeZone { get; set; } - /// - /// Function to resolve location strings to coordinates. - /// - Func>? GeoLocationResolver { get; set; } - /// /// Stack used during query building to accumulate Query objects. /// This is internal state for the stateless visitor pattern. @@ -77,10 +59,7 @@ public class ElasticsearchQueryVisitorContext : QueryVisitorContext, IElasticsea public string[]? DefaultFields { get; set; } /// - public QueryOperator DefaultOperator { get; set; } - - /// - public Func? IsGeoPointField { get; set; } + public BooleanOperator DefaultOperator { get; set; } = BooleanOperator.Or; /// public Func? IsDateField { get; set; } @@ -88,9 +67,6 @@ public class ElasticsearchQueryVisitorContext : QueryVisitorContext, IElasticsea /// public string? DefaultTimeZone { get; set; } - /// - public Func>? GeoLocationResolver { get; set; } - /// public Stack QueryStack { get; } = new(); diff --git a/src/Foundatio.Lucene.Elasticsearch/ElasticsearchQueryVisitorContextExtensions.cs b/src/Foundatio.Lucene.Elasticsearch/ElasticsearchQueryVisitorContextExtensions.cs index 38ce1c1..96e7b52 100644 --- a/src/Foundatio.Lucene.Elasticsearch/ElasticsearchQueryVisitorContextExtensions.cs +++ b/src/Foundatio.Lucene.Elasticsearch/ElasticsearchQueryVisitorContextExtensions.cs @@ -1,3 +1,5 @@ +using Foundatio.Lucene.Ast; + namespace Foundatio.Lucene.Elasticsearch; /// @@ -20,14 +22,14 @@ public static T UseScoring(this T context) where T : IElasticsearchQueryVisit public static T UseSearchMode(this T context) where T : IElasticsearchQueryVisitorContext { context.UseScoring = true; - context.DefaultOperator = QueryOperator.Or; + context.DefaultOperator = BooleanOperator.Or; return context; } /// /// Sets the default boolean operator. /// - public static T SetDefaultOperator(this T context, QueryOperator op) where T : IElasticsearchQueryVisitorContext + public static T SetDefaultOperator(this T context, BooleanOperator op) where T : IElasticsearchQueryVisitorContext { context.DefaultOperator = op; return context; @@ -51,24 +53,6 @@ public static T SetTimeZone(this T context, string timeZone) where T : IElast return context; } - /// - /// Sets the function to resolve location strings to coordinates. - /// - public static T SetGeoLocationResolver(this T context, Func> resolver) where T : IElasticsearchQueryVisitorContext - { - context.GeoLocationResolver = resolver; - return context; - } - - /// - /// Sets the function to determine if a field is a geo_point field. - /// - public static T SetGeoPointFieldResolver(this T context, Func resolver) where T : IElasticsearchQueryVisitorContext - { - context.IsGeoPointField = resolver; - return context; - } - /// /// Sets the function to determine if a field is a date field. /// diff --git a/src/Foundatio.Lucene.EntityFramework/EntityFieldInfo.cs b/src/Foundatio.Lucene.EntityFramework/EntityFieldInfo.cs index 3b39165..46852de 100644 --- a/src/Foundatio.Lucene.EntityFramework/EntityFieldInfo.cs +++ b/src/Foundatio.Lucene.EntityFramework/EntityFieldInfo.cs @@ -29,11 +29,6 @@ public class EntityFieldInfo /// public bool IsNumber { get; set; } - /// - /// Whether the field is a money/decimal type with specific precision. - /// - public bool IsMoney { get; set; } - /// /// Whether the field is a DateTime type. /// @@ -116,7 +111,7 @@ public string GetNavigationPrefix() } /// - protected bool Equals(EntityFieldInfo other) => Name == other.Name; + protected bool Equals(EntityFieldInfo other) => string.Equals(FullName, other.FullName, StringComparison.Ordinal); /// public override bool Equals(object? obj) @@ -128,5 +123,5 @@ public override bool Equals(object? obj) } /// - public override int GetHashCode() => Name.GetHashCode(); + public override int GetHashCode() => FullName.GetHashCode(StringComparison.Ordinal); } diff --git a/src/Foundatio.Lucene/LuceneParseResult.cs b/src/Foundatio.Lucene/LuceneParseResult.cs index 19af6a4..4b4256f 100644 --- a/src/Foundatio.Lucene/LuceneParseResult.cs +++ b/src/Foundatio.Lucene/LuceneParseResult.cs @@ -15,12 +15,12 @@ public class LuceneParseResult /// /// The parsed query document. Always non-null after parsing, even if errors occurred. /// - public QueryDocument Document { get; set; } + public QueryDocument Document { get; init; } /// /// List of errors encountered during parsing. Empty list means successful parse. /// - public List Errors { get; set; } + public List Errors { get; init; } /// /// Indicates whether the parsing was successful (no errors). diff --git a/tests/Foundatio.Lucene.Elasticsearch.Tests/ElasticsearchQueryParserTests.cs b/tests/Foundatio.Lucene.Elasticsearch.Tests/ElasticsearchQueryParserTests.cs index 0612075..9825a1b 100644 --- a/tests/Foundatio.Lucene.Elasticsearch.Tests/ElasticsearchQueryParserTests.cs +++ b/tests/Foundatio.Lucene.Elasticsearch.Tests/ElasticsearchQueryParserTests.cs @@ -1,4 +1,5 @@ using Elastic.Clients.Elasticsearch.QueryDsl; +using Foundatio.Lucene.Ast; namespace Foundatio.Lucene.Elasticsearch.Tests; @@ -395,7 +396,7 @@ public async Task CanParseDefaultOperatorAnd() { var parser = new ElasticsearchQueryParser(c => { - c.DefaultOperator = QueryOperator.And; + c.DefaultOperator = BooleanOperator.And; c.UseScoring = true; }); var query = parser.BuildQuery("foo bar"); From e2b572c5304a26ec1f8de4be07eaaea69eb41ce2 Mon Sep 17 00:00:00 2001 From: "Eric J. Smith" Date: Thu, 25 Jun 2026 00:07:11 -0500 Subject: [PATCH 05/10] M5: error-recovery and concurrency test coverage - QueryResultTests: success/failure model, GetValueOrThrow, GetValueOrDefault, Map, Try, Deconstruct, and implicit-bool behavior. - ElasticsearchErrorAndConcurrencyTests: TryBuildQuery returns a Failure (not a throw) on malformed input, and a stress test mutating registered per-index options (SetOptions/RemoveOptions) while building queries on a shared parser. - EF: TryBuildFilter returns a Failure on malformed input. --- .../ElasticsearchErrorAndConcurrencyTests.cs | 51 +++++++++++++ .../EntityFrameworkPipelineTests.cs | 11 +++ .../QueryResultTests.cs | 74 +++++++++++++++++++ 3 files changed, 136 insertions(+) create mode 100644 tests/Foundatio.Lucene.Elasticsearch.Tests/ElasticsearchErrorAndConcurrencyTests.cs create mode 100644 tests/Foundatio.Lucene.Tests/QueryResultTests.cs diff --git a/tests/Foundatio.Lucene.Elasticsearch.Tests/ElasticsearchErrorAndConcurrencyTests.cs b/tests/Foundatio.Lucene.Elasticsearch.Tests/ElasticsearchErrorAndConcurrencyTests.cs new file mode 100644 index 0000000..058a7ef --- /dev/null +++ b/tests/Foundatio.Lucene.Elasticsearch.Tests/ElasticsearchErrorAndConcurrencyTests.cs @@ -0,0 +1,51 @@ +namespace Foundatio.Lucene.Elasticsearch.Tests; + +public class ElasticsearchErrorAndConcurrencyTests +{ + [Fact] + public void TryBuildQuery_MalformedQuery_ReturnsFailureNotThrow() + { + var parser = new ElasticsearchQueryParser(); + + var result = parser.TryBuildQuery("(unbalanced AND"); + + Assert.True(result.IsFailure); + Assert.NotNull(result.Error); + } + + [Fact] + public void TryBuildQuery_ValidQuery_ReturnsSuccess() + { + var parser = new ElasticsearchQueryParser(); + + var result = parser.TryBuildQuery("status:active"); + + Assert.True(result.IsSuccess); + Assert.NotNull(result.Value); + } + + [Fact] + public async Task BuildQuery_WithConcurrentOptionRegistrationAndRemoval_IsThreadSafe() + { + // Stresses the parser's internal registered-options ConcurrentDictionary: register, query, + // and remove per-index options across many threads while building queries on a shared parser. + var parser = new ElasticsearchQueryParser(c => c.UseScoring = true); + var tasks = new List(); + + for (int i = 0; i < 100; i++) + { + int n = i; + var index = $"index-{n % 8}"; + tasks.Add(Task.Run(() => parser.SetOptions(index, new ElasticsearchQueryOptions + { + FieldMap = new FieldMap { { "user", $"tenant{n % 8}.userName" } } + }))); + tasks.Add(Task.Run(() => parser.BuildQuery("user:john", index, null))); + tasks.Add(Task.Run(() => parser.RemoveOptions(index))); + } + + // Must complete without throwing despite concurrent mutation + reads. + await Task.WhenAll(tasks); + Assert.True(tasks.All(t => t.IsCompletedSuccessfully)); + } +} diff --git a/tests/Foundatio.Lucene.EntityFramework.Tests/EntityFrameworkPipelineTests.cs b/tests/Foundatio.Lucene.EntityFramework.Tests/EntityFrameworkPipelineTests.cs index 0cdf100..c5768ff 100644 --- a/tests/Foundatio.Lucene.EntityFramework.Tests/EntityFrameworkPipelineTests.cs +++ b/tests/Foundatio.Lucene.EntityFramework.Tests/EntityFrameworkPipelineTests.cs @@ -96,4 +96,15 @@ public void TryBuildFilter_ProximityQuery_ReturnsFailure() Assert.False(result.IsSuccess); } + + [Fact] + public void TryBuildFilter_MalformedQuery_ReturnsFailureNotThrow() + { + var parser = new EntityFrameworkQueryParser(); + + var result = parser.TryBuildFilter("(unbalanced AND"); + + Assert.False(result.IsSuccess); + Assert.NotNull(result.Error); + } } diff --git a/tests/Foundatio.Lucene.Tests/QueryResultTests.cs b/tests/Foundatio.Lucene.Tests/QueryResultTests.cs new file mode 100644 index 0000000..8563c17 --- /dev/null +++ b/tests/Foundatio.Lucene.Tests/QueryResultTests.cs @@ -0,0 +1,74 @@ +namespace Foundatio.Lucene.Tests; + +public class QueryResultTests +{ + [Fact] + public void Success_ExposesValue_AndReportsSuccess() + { + var result = QueryResult.Success(42); + + Assert.True(result.IsSuccess); + Assert.False(result.IsFailure); + Assert.Equal(42, result.Value); + Assert.Null(result.Error); + Assert.True(result); // implicit bool + } + + [Fact] + public void Failure_ExposesError_AndThrowsOnValue() + { + var result = QueryResult.Failure(new QueryParseException("bad", QueryErrorCode.UnexpectedToken)); + + Assert.True(result.IsFailure); + Assert.Equal(QueryErrorCode.UnexpectedToken, result.ErrorCode); + Assert.Equal("bad", result.ErrorMessage); + Assert.Throws(() => result.Value); + Assert.False(result); // implicit bool + } + + [Fact] + public void GetValueOrThrow_RethrowsOriginalException() + { + var ex = new QueryBuildException("nope", QueryErrorCode.UnsupportedQueryType); + var result = QueryResult.Failure(ex); + + var thrown = Assert.Throws(() => result.GetValueOrThrow()); + Assert.Same(ex, thrown); + } + + [Fact] + public void GetValueOrDefault_ReturnsFallbackOnFailure() + { + var result = QueryResult.Failure("oops"); + + Assert.Equal("fallback", result.GetValueOrDefault("fallback")); + } + + [Fact] + public void Map_TransformsSuccess_AndPreservesFailure() + { + Assert.Equal(6, QueryResult.Success(3).Map(v => v * 2).Value); + + var failed = QueryResult.Failure("err").Map(v => v * 2); + Assert.True(failed.IsFailure); + } + + [Fact] + public void Try_CapturesQueryExceptionAsFailure() + { + var result = QueryResult.Try(() => throw new QueryParseException("boom")); + + Assert.True(result.IsFailure); + Assert.Equal(QueryErrorCode.ParseError, result.ErrorCode); + } + + [Fact] + public void Deconstruct_YieldsStatusValueAndError() + { + var (isSuccess, value, error) = QueryResult.Success(7); + + Assert.True(isSuccess); + Assert.Equal(7, value); + Assert.Null(error); + } +} From 60b98fc2bfab6437c436a3869ef3929cb8b5d8d8 Mon Sep 17 00:00:00 2001 From: "Eric J. Smith" Date: Thu, 25 Jun 2026 00:19:38 -0500 Subject: [PATCH 06/10] M6: release essentials - LICENSE, CHANGELOG, doc accuracy - Add root LICENSE (Apache-2.0) matching the package license expression. - Add CHANGELOG documenting the 1.0 hardening (added/changed/removed/fixed, breaking changes, and the PublicApiAnalyzers follow-up). - Fix pervasive documentation drift: examples now use the real synchronous API (no ParseAsync/BuildQueryAsync/RunAsync/AcceptAsync/VisitAsync), the real AST shape (no BooleanQueryNode.Left/Right, GroupNode.Child, FieldQueryNode.Value, or IncludeNode), BooleanOperator instead of QueryOperator, and reflect the geo removal and the EF field-map/include/date-math pipeline. Correct AGENTS.md (recursive-descent parser; synchronous QueryVisitor.Visit pattern). --- AGENTS.md | 20 +- CHANGELOG.md | 76 ++++++ LICENSE | 201 ++++++++++++++ docs/guide/configuration.md | 354 ++++++++----------------- docs/guide/custom-visitors.md | 139 ++++------ docs/guide/date-math.md | 16 +- docs/guide/elasticsearch.md | 82 +----- docs/guide/entity-framework.md | 6 +- docs/guide/field-mapping.md | 16 +- docs/guide/getting-started.md | 7 +- docs/guide/query-syntax.md | 3 +- docs/guide/validation.md | 42 +-- docs/guide/visitors.md | 87 +++--- docs/guide/what-is-foundatio-lucene.md | 4 +- 14 files changed, 537 insertions(+), 516 deletions(-) create mode 100644 CHANGELOG.md create mode 100644 LICENSE diff --git a/AGENTS.md b/AGENTS.md index 0b93163..9cee7bf 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -55,7 +55,7 @@ src │ ├── Visitors # Query visitors for traversal/transformation │ ├── Extensions # Extension methods for nodes and strings │ ├── LuceneQuery.cs # Main entry point for parsing -│ ├── LuceneParser.cs # Pratt parser implementation +│ ├── LuceneParser.cs # Recursive-descent parser implementation │ ├── LuceneLexer.cs # Tokenizer for query strings │ ├── QueryStringBuilder.cs # Converts AST back to query string │ ├── QueryValidator.cs # Query validation against options @@ -106,7 +106,7 @@ docs # VitePress documentation site ### Common Patterns -- **Async suffix**: All async methods end with `Async` (e.g., `ParseAsync`, `BuildQueryAsync`) +- **Async suffix**: Methods that are genuinely asynchronous end with `Async`. The parser, query builders, and visitor pipeline are **synchronous** — there are no `ParseAsync`/`BuildQueryAsync`/`VisitAsync` methods - **CancellationToken**: Last parameter, defaulted to `default` in public APIs - **Extension methods**: Place in `Extensions/` directory, use descriptive class names (e.g., `QueryNodeExtensions`) - **Logging**: Use structured logging with `ILogger`, log at appropriate levels @@ -114,15 +114,15 @@ docs # VitePress documentation site ### Visitor Pattern (Critical for Extensions) -Extend `ChainableQueryVisitor` and override `VisitAsync` methods for specific node types: +Extend `QueryVisitor` and override the synchronous `Visit` methods for specific node types: ```csharp -public class MyVisitor : ChainableQueryVisitor +public class MyVisitor : QueryVisitor { - public override async Task VisitAsync(FieldQueryNode node, IQueryVisitorContext context) + protected override QueryNode Visit(FieldQueryNode node, IQueryVisitorContext context) { // Transform the node - return await base.VisitAsync(node, context); // Visits children + return base.Visit(node, context); // Visits children } } ``` @@ -379,18 +379,18 @@ if (result.IsSuccess) ```csharp var fieldMap = new FieldMap { { "user", "account.user" }, { "created", "metadata.timestamp" } }; -await FieldResolverQueryVisitor.RunAsync(result.Document, fieldMap); +FieldResolverQueryVisitor.Run(result.Document, fieldMap); ``` - `FieldMap` is case-insensitive (uses `StringComparer.OrdinalIgnoreCase`) -- `ToHierarchicalFieldResolver()` extension supports nested paths (`data.field` → `resolved.field`) +- `FieldMap.ResolutionMode` is `Hierarchical` by default, so nested paths resolve by longest matching prefix (`data.field` → `resolved.field`) ### Validation Pattern ```csharp var options = new QueryValidationOptions { AllowLeadingWildcards = false }; options.AllowedFields.Add("title"); -var validationResult = await QueryValidator.ValidateAsync(document, options); +var validationResult = QueryValidator.Validate(document, options); ``` ### Entity Framework Integration @@ -413,7 +413,7 @@ var parser = new ElasticsearchQueryParser(config => config.DefaultFields = ["title", "content"]; config.FieldMap = new FieldMap { { "author", "metadata.author" } }; }); -var query = await parser.BuildQueryAsync("author:john AND status:active"); +var query = parser.BuildQuery("author:john AND status:active"); // Returns Elastic.Clients.Elasticsearch.QueryDsl.Query ``` diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..d31284e --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,76 @@ +# Changelog + +All notable changes to Foundatio.Lucene are documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). + +## [Unreleased] — 1.0 hardening + +This release hardens the library for a stable 1.0, with a focus on high-performance per-scope +configuration swapping that works equally well with Entity Framework (SQL) and Elasticsearch. + +### Added + +- **Cross-engine parity gate.** A new `Foundatio.Lucene.Parity.Tests` suite seeds identical data into + SQL Server and Elasticsearch (via Testcontainers) and asserts that the same Lucene query returns + the same result set on both engines across the supported construct set (ranges, comparisons, + equality, boolean composition, `_exists_`, `NOT`, match-all). +- **Entity Framework field maps, `@includes`, and date math.** The EF parser now runs the same + pre-build visitor pipeline as the Elasticsearch parser, so per-scope `FieldMap`, `@include` + expansion, and date math (`now-7d`, `now/d`, `2024-01-01||+1M`) behave identically on SQL. These + were previously accepted on the options API but silently ignored. +- **Configurable `TimeProvider` on the EF parser** (`config.SetTimeProvider(...)`) controlling `now` + in date math. +- **Parser depth bound** (`LuceneParser.MaxDepth`, default 100): deeply nested input now records a + `MaxDepthExceeded` `ParseError` instead of risking a `StackOverflowException`. +- **`ParseError.Code`** (`QueryErrorCode`): parse errors are now classified (depth, unmatched + bracket, invalid range, unexpected character). +- **`ConfigSwapBenchmarks`**: measures per-query allocations when swapping a different scope's field + map / default fields against a shared parser, for both EF and Elasticsearch. +- Error-recovery, concurrency, and pipeline test coverage; root `LICENSE` (Apache-2.0). + +### Changed + +- **Capability model (breaking).** The EF builder now throws `QueryBuildException` + (`QueryErrorCode.UnsupportedQueryType`) for fuzzy (`term~N`) and proximity/slop (`"a b"~N`) + queries instead of silently degrading them to substring matches. Use `TryBuildFilter` for a + `QueryResult` instead of an exception. +- **Elasticsearch scope swapping is allocation-free on the hot path.** The parser carries the + per-scope field map and includes on the visitor context and reuses singleton visitors, instead of + allocating a new `FieldResolverQueryVisitor`/`IncludeVisitor` per query. +- Boost (`^`) and fuzzy/slop (`~N`) parsing is now culture-invariant. +- `EntityFieldInfo` equality/hash now key on `FullName` (was the leaf `Name`), so nested fields that + share a leaf name no longer collide. + +### Removed (breaking) + +- **`TenantOptionsCache` / `EntityOptionsCache` / `TenantEntityOptionsCache` / `VisitorPool`** — + orphaned, untested infrastructure. Per-request options (`ElasticsearchQueryOptions` / + `EntityFrameworkQueryOptions`, both immutable records) are the supported scope-swap mechanism; + applications own caching of those option objects. +- **Elasticsearch geo configuration** (`IsGeoPointField`, `GeoLocationResolver`, + `UseGeoFields`/`UseGeoLocationResolver`/`WithGeoPointFields`/`SetGeoPointFieldResolver`/ + `SetGeoLocationResolver`). The builder never emitted geo queries and the async resolver could not + be awaited in the synchronous pipeline. Geo is deferred to a post-1.0 design that keeps the + visitor pipeline synchronous (collect geo references → resolve coordinates outside the pipeline → + annotate the AST). +- **`QueryOperator` enum** — the Elasticsearch integration now uses + `Foundatio.Lucene.Ast.BooleanOperator` everywhere. +- The unused `EntityFieldInfo.IsMoney` property. + +### Fixed + +- Lexer no longer advances past the end of the buffer on a trailing backslash in a quoted string or + regex (could throw while slicing). +- Documentation examples updated to the real **synchronous** API (no `ParseAsync`/`BuildQueryAsync`/ + `RunAsync`/`AcceptAsync`/`VisitAsync`), and to reflect the geo removal and the EF pipeline support. + +### Compatibility + +- `LuceneParseResult.Document` and `Errors` are now `init`-only. + +### Known follow-ups + +- Adopt `Microsoft.CodeAnalysis.PublicApiAnalyzers` with committed `PublicAPI.Shipped.txt` / + `PublicAPI.Unshipped.txt` baselines to lock the public surface against accidental changes. (The + surface itself has been cleaned for 1.0; this adds the build-time guardrail.) diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..02008ba --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or Derivative + Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2024 Foundatio + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/docs/guide/configuration.md b/docs/guide/configuration.md index 09d60b5..126c11a 100644 --- a/docs/guide/configuration.md +++ b/docs/guide/configuration.md @@ -2,157 +2,120 @@ This guide covers configuration options for the various components of Foundatio.Lucene. +The parser APIs are **synchronous** — there are no `*Async` parse/build/visitor methods. + ## Core Parser -The core parser is stateless and doesn't require configuration: +The core parser is stateless and requires no configuration: ```csharp var result = LuceneQuery.Parse("title:hello AND status:active"); ``` -## Entity Framework Parser +`LuceneQuery.Parse` is resilient: it always returns a (possibly partial) AST plus any +`ParseError`s, and bounds nesting depth (`LuceneParser.MaxDepth`, default 100) so deeply nested +input can never overflow the stack. -The `EntityFrameworkQueryParser` configuration: +## Entity Framework Parser ```csharp -var parser = new EntityFrameworkQueryParser(); - -// Build a filter with field mapping -var fieldMap = new FieldMap +var parser = new EntityFrameworkQueryParser(config => { - { "name", "FullName" }, - { "dept", "Department.Name" } -}; + config.SetDefaultFields("Name", "Email"); + config.SetDefaultOperator(BooleanOperator.And); + // Controls 'now' in date math (now-7d, now/d). Defaults to TimeProvider.System. + config.SetTimeProvider(TimeProvider.System); +}); -var filter = parser.BuildFilter(query, fieldMap); +var filter = parser.BuildFilter("name:john AND salary:[50000 TO *]"); +var employees = context.Employees.Where(filter).ToList(); ``` -## Elasticsearch Parser +### Field aliasing, includes and date math (per request) -The `ElasticsearchQueryParser` has extensive configuration options: +Field maps, `@include` references and date math are applied through the shared visitor pipeline, +exactly as in the Elasticsearch integration. Supply them per request via +`EntityFrameworkQueryOptions` (the recommended way to swap configuration per scope/tenant): ```csharp -var parser = new ElasticsearchQueryParser(config => -{ - // Scoring configuration - config.UseScoring = true; - - // Default fields for unfielded terms - config.DefaultFields = ["title", "content", "description"]; +var options = new EntityFrameworkQueryOptionsBuilder() + .WithFieldMap(new FieldMap { { "user", "Name" }, { "dept", "Department.Name" } }) + .WithIncludes(new Dictionary { ["seniors"] = "Title:Senior" }) + .WithValidationOptions(o => o.AllowLeadingWildcards = false) + .Build(); - // Default boolean operator - config.DefaultOperator = QueryOperator.And; +var filter = parser.BuildFilter("user:john AND @include:seniors", context: null, options); +``` - // Field aliasing - config.FieldMap = new FieldMap - { - { "author", "metadata.author" }, - { "date", "metadata.publishedAt" } - }; +You can also register default options per entity type with `parser.SetOptions(options)`. +Per-request options take precedence over registered options, which take precedence over the +global configuration. - // Geo field detection - config.IsGeoPointField = field => - field == "location" || - field.EndsWith("_geo"); +> SQL cannot honor fuzzy (`term~N`) or proximity/slop (`"a b"~N`) queries. Rather than silently +> returning the wrong rows, the EF builder throws `QueryBuildException` (use `TryBuildFilter` to get +> a `QueryResult` instead of an exception). Regex queries depend on the database provider. - // Date field detection - config.IsDateField = field => - field.EndsWith("date") || - field.EndsWith("At") || - field.EndsWith("timestamp"); +## Elasticsearch Parser - // Timezone for date queries +```csharp +var parser = new ElasticsearchQueryParser(config => +{ + config.UseScoring = true; // match queries (scoring) vs term queries (filter) + config.DefaultFields = ["title", "content"]; // fields for unfielded terms + config.DefaultOperator = BooleanOperator.And; // implicit operator + config.FieldMap = new FieldMap { { "author", "metadata.author" } }; + config.IsDateField = field => field.EndsWith("At") || field.EndsWith("date"); config.DefaultTimeZone = "America/Chicago"; - - // Geo location resolver (for named locations) - config.GeoLocationResolver = async name => - { - var coords = await _geocodingService.ResolveAsync(name); - return coords != null ? $"{coords.Lat},{coords.Lon}" : null; - }; - - // Include resolver (for @include syntax) - config.IncludeResolver = async name => - { - return await _savedQueryService.GetQueryAsync(name); - }; - - // Validation options - config.ValidationOptions = new QueryValidationOptions - { - AllowLeadingWildcards = false - }; + config.ValidationOptions = new QueryValidationOptions { AllowLeadingWildcards = false }; }); + +var query = parser.BuildQuery("author:john AND status:active"); ``` -### Configuration Properties +### Configuration properties | Property | Type | Default | Description | |----------|------|---------|-------------| | `UseScoring` | `bool` | `false` | Use match queries (scoring) vs term queries (filtering) | | `DefaultFields` | `string[]?` | `null` | Fields to search for unfielded terms | -| `DefaultOperator` | `QueryOperator` | `Or` | Default boolean operator for implicit combinations | +| `DefaultOperator` | `BooleanOperator` | `Or` | Default boolean operator for implicit combinations | | `FieldMap` | `FieldMap?` | `null` | Field name mappings | -| `IsGeoPointField` | `Func?` | `null` | Function to detect geo_point fields | -| `IsDateField` | `Func?` | `null` | Function to detect date fields | +| `Includes` | `IReadOnlyDictionary?` | `null` | Pre-resolved `@include` content | +| `IsDateField` | `Func?` | `null` | Detects date fields for date range queries | | `DefaultTimeZone` | `string?` | `null` | Default timezone for date range queries | -| `GeoLocationResolver` | `Func>?` | `null` | Async function to resolve location names to coordinates | -| `IncludeResolver` | `IncludeResolver?` | `null` | Function to resolve @include references | | `ValidationOptions` | `QueryValidationOptions?` | `null` | Query validation options | +| `TimeProvider` | `TimeProvider` | `System` | Controls `now` in date math | -## Validation Options +### Per-request / per-scope options -Configure query validation: +Swap configuration per scope by passing a prebuilt `ElasticsearchQueryOptions` (or registering it +per index name). Options are immutable records, so an application can cache one per tenant and reuse +it across requests: ```csharp -var options = new QueryValidationOptions -{ - // Wildcard restrictions - AllowLeadingWildcards = false, - AllowWildcardOnlyQueries = false, - - // Field restrictions - AllowedFields = new HashSet(StringComparer.OrdinalIgnoreCase) - { - "title", "author", "status", "date" - }, - - DisallowedFields = new HashSet(StringComparer.OrdinalIgnoreCase) - { - "password", "ssn", "internalId" - } -}; +var tenantOptions = new ElasticsearchQueryOptionsBuilder() + .WithFieldMap(new FieldMap { { "user", "tenant42.userName" } }) + .WithDefaultFields("tenant42.title") + .Build(); + +var query = parser.BuildQuery("user:john", tenantOptions); ``` -### Validation Properties - -| Property | Type | Default | Description | -|----------|------|---------|-------------| -| `AllowLeadingWildcards` | `bool` | `true` | Allow patterns like `*suffix` | -| `AllowWildcardOnlyQueries` | `bool` | `true` | Allow `*` or `*:*` queries | -| `AllowedFields` | `HashSet` | empty | Whitelist of allowed fields | -| `DisallowedFields` | `HashSet` | empty | Blacklist of disallowed fields | +The same parser instance is thread-safe and reuses its visitors across requests, so swapping +options per request does not allocate a visitor per call. ## Field Map -Configure field aliasing: - ```csharp var fieldMap = new FieldMap { { "user", "account.username" }, - { "email", "account.emailAddress" }, { "created", "metadata.createdAt" } }; - -// Case-insensitive by default -// "User:john" -> "account.username:john" -// "USER:john" -> "account.username:john" ``` -### Hierarchical Resolution - -For nested field structures: +`FieldMap` is case-insensitive. By default `ResolutionMode` is `Hierarchical`, so nested paths +resolve by longest matching prefix: ```csharp var fieldMap = new FieldMap @@ -160,185 +123,86 @@ var fieldMap = new FieldMap { "data", "payload" }, { "data.user", "payload.account.username" } }; +// "data.user:john" -> "payload.account.username:john" +// "data.status:open" -> "payload.status:open" +``` -var resolver = fieldMap.ToHierarchicalFieldResolver(); -await FieldResolverQueryVisitor.RunAsync(document, resolver); +Set `ResolutionMode = FieldResolutionMode.Direct` for exact-match-only resolution, +`ReportUnmappedFields = true` to flag unmapped fields as unresolved, or `ResultPrefix` to prefix +every resolved name. The parsers apply the field map automatically; to run it manually: -// "data.user:john" -> "payload.account.username:john" -// "data.status:active" -> "payload.status:active" +```csharp +FieldResolverQueryVisitor.Run(result.Document, fieldMap); ``` -## Include Resolver +## Includes -Configure @include syntax resolution: +`@include:name` references expand from a pre-resolved dictionary (resolve saved queries from your +store before parsing): ```csharp -IncludeResolver resolver = async name => +var includes = new Dictionary { ["recent"] = "created:[now-7d TO now]" }; + +var parser = new ElasticsearchQueryParser(c => c.Includes = includes); +var query = parser.BuildQuery("@include:recent AND status:active"); + +// Or run it manually against the AST: +result.Document.ExpandIncludes(includes); +``` + +Circular references and excessive nesting (`IncludeVisitor.MaxIncludeDepth`) are detected and +reported as validation errors. + +## Validation + +```csharp +var options = new QueryValidationOptions { - // Load from database - var savedQuery = await _db.SavedQueries - .Where(q => q.Name == name) - .Select(q => q.QueryText) - .FirstOrDefaultAsync(); - - return savedQuery; + AllowLeadingWildcards = false, + AllowWildcardOnlyQueries = false, + AllowedFields = { "title", "author", "status", "date" }, + DisallowedFields = { "password", "ssn" } }; -// Use in Elasticsearch parser -var parser = new ElasticsearchQueryParser(config => +var result = QueryValidator.ValidateQuery("title:hello", options); +if (!result.IsValid) { - config.IncludeResolver = resolver; -}); - -// Or with IncludeVisitor directly -await IncludeVisitor.RunAsync(document, resolver); + // result.ValidationErrors describe what failed +} ``` -## Visitor Configuration +| Property | Type | Default | Description | +|----------|------|---------|-------------| +| `AllowLeadingWildcards` | `bool` | `true` | Allow patterns like `*suffix` | +| `AllowWildcardOnlyQueries` | `bool` | `true` | Allow `*` or `*:*` queries | +| `AllowedFields` | `HashSet` | empty | Whitelist of allowed fields | +| `DisallowedFields` | `HashSet` | empty | Blacklist of disallowed fields | + +## Custom Visitors -Configure visitor chains: +Compose visitors with `ChainedQueryVisitor` and run them synchronously: ```csharp var visitors = new ChainedQueryVisitor() .AddVisitor(new FieldResolverQueryVisitor(fieldMap), priority: 10) - .AddVisitor(new IncludeVisitor(includeResolver), priority: 20) .AddVisitor(new DateMathEvaluatorVisitor(), priority: 30) - .AddVisitor(new CustomTransformVisitor(), priority: 50) .AddVisitor(new ValidationVisitor(), priority: 100); var context = new QueryVisitorContext(); -await visitors.AcceptAsync(document, context); +visitors.Accept(result.Document, context); ``` ## Dependency Injection -Register parsers with DI: - ```csharp -// Program.cs or Startup.cs services.AddSingleton(); services.AddSingleton(sp => new ElasticsearchQueryParser(config => { config.UseScoring = true; config.DefaultFields = ["title", "content"]; - config.IncludeResolver = sp.GetRequiredService().GetQueryAsync; - config.GeoLocationResolver = sp.GetRequiredService().ResolveAsync; - config.ValidationOptions = new QueryValidationOptions - { - AllowLeadingWildcards = false - }; + config.ValidationOptions = new QueryValidationOptions { AllowLeadingWildcards = false }; })); - -// In controllers/services -public class SearchController -{ - private readonly ElasticsearchQueryParser _parser; - - public SearchController(ElasticsearchQueryParser parser) - { - _parser = parser; - } -} -``` - -## Environment-Specific Configuration - -Use configuration files for environment-specific settings: - -```csharp -// appsettings.json -{ - "Search": { - "UseScoring": true, - "DefaultFields": ["title", "content"], - "DefaultTimeZone": "America/Chicago", - "AllowLeadingWildcards": false - } -} - -// Configuration -services.AddSingleton(sp => -{ - var config = sp.GetRequiredService(); - var searchConfig = config.GetSection("Search"); - - return new ElasticsearchQueryParser(parserConfig => - { - parserConfig.UseScoring = searchConfig.GetValue("UseScoring"); - parserConfig.DefaultFields = searchConfig.GetSection("DefaultFields").Get(); - parserConfig.DefaultTimeZone = searchConfig.GetValue("DefaultTimeZone"); - parserConfig.ValidationOptions = new QueryValidationOptions - { - AllowLeadingWildcards = searchConfig.GetValue("AllowLeadingWildcards") - }; - }); -}); -``` - -## Best Practices - -### 1. Centralize Configuration - -```csharp -public static class SearchConfiguration -{ - public static readonly FieldMap FieldMap = new() - { - { "name", "fullName" }, - { "email", "emailAddress" } - }; - - public static readonly QueryValidationOptions ValidationOptions = new() - { - AllowLeadingWildcards = false - }; - - public static ElasticsearchQueryParser CreateParser() - { - return new ElasticsearchQueryParser(config => - { - config.FieldMap = FieldMap; - config.ValidationOptions = ValidationOptions; - }); - } -} -``` - -### 2. Use Constants for Field Names - -```csharp -public static class SearchFields -{ - public const string Name = "name"; - public const string Email = "email"; - public const string Status = "status"; - public const string Created = "created"; - - public static readonly IReadOnlySet All = new HashSet - { - Name, Email, Status, Created - }; -} -``` - -### 3. Document Configuration - -```csharp -/// -/// Search API configuration. -/// -/// -/// Field mappings: -/// - name -> fullName -/// - email -> emailAddress -/// - created -> createdAt -/// -/// Validation: -/// - Leading wildcards disabled for performance -/// - Only whitelisted fields allowed -/// -public static class SearchConfiguration { } ``` ## Next Steps diff --git a/docs/guide/custom-visitors.md b/docs/guide/custom-visitors.md index 70a4678..8088550 100644 --- a/docs/guide/custom-visitors.md +++ b/docs/guide/custom-visitors.md @@ -12,7 +12,7 @@ using Foundatio.Lucene.Visitors; public class MyVisitor : QueryVisitor { - public override async Task VisitAsync(TermNode node, IQueryVisitorContext context) + protected override QueryNode Visit(TermNode node, IQueryVisitorContext context) { // Transform the node node.Term = node.Term?.ToLowerInvariant(); @@ -25,21 +25,21 @@ public class MyVisitor : QueryVisitor ## Visiting Child Nodes -Call `base.VisitAsync()` to visit child nodes: +Call `base.Visit()` to visit child nodes: ```csharp -public override async Task VisitAsync(FieldQueryNode node, IQueryVisitorContext context) +protected override QueryNode Visit(FieldQueryNode node, IQueryVisitorContext context) { // Process this node first node.Field = node.Field?.ToLowerInvariant(); // Then visit children (the field's value) - return await base.VisitAsync(node, context); + return base.Visit(node, context); } ``` ::: warning -If you don't call `base.VisitAsync()`, child nodes won't be visited! +If you don't call `base.Visit()`, child nodes won't be visited! ::: ## Common Patterns @@ -51,18 +51,18 @@ Transform nodes in place: ```csharp public class NormalizeTermsVisitor : QueryVisitor { - public override Task VisitAsync(TermNode node, IQueryVisitorContext context) + protected override QueryNode Visit(TermNode node, IQueryVisitorContext context) { // Normalize whitespace and case node.Term = node.Term?.Trim().ToLowerInvariant(); - return Task.FromResult(node); + return node; } - public override Task VisitAsync(PhraseNode node, IQueryVisitorContext context) + protected override QueryNode Visit(PhraseNode node, IQueryVisitorContext context) { // Normalize phrase node.Phrase = node.Phrase?.Trim(); - return Task.FromResult(node); + return node; } } ``` @@ -77,30 +77,30 @@ public class FieldCollectorVisitor : QueryVisitor public HashSet Fields { get; } = new(StringComparer.OrdinalIgnoreCase); public HashSet Terms { get; } = new(StringComparer.OrdinalIgnoreCase); - public override async Task VisitAsync(FieldQueryNode node, IQueryVisitorContext context) + protected override QueryNode Visit(FieldQueryNode node, IQueryVisitorContext context) { if (node.Field != null) { Fields.Add(node.Field); } - return await base.VisitAsync(node, context); + return base.Visit(node, context); } - public override Task VisitAsync(TermNode node, IQueryVisitorContext context) + protected override QueryNode Visit(TermNode node, IQueryVisitorContext context) { if (node.Term != null) { Terms.Add(node.Term); } - return Task.FromResult(node); + return node; } } // Usage var collector = new FieldCollectorVisitor(); -await collector.AcceptAsync(result.Document, new QueryVisitorContext()); +collector.Accept(result.Document, new QueryVisitorContext()); Console.WriteLine($"Fields: {string.Join(", ", collector.Fields)}"); Console.WriteLine($"Terms: {string.Join(", ", collector.Terms)}"); ``` @@ -112,35 +112,17 @@ Replace nodes with different nodes: ```csharp public class StatusExpanderVisitor : QueryVisitor { - public override Task VisitAsync(FieldQueryNode node, IQueryVisitorContext context) + protected override QueryNode Visit(FieldQueryNode node, IQueryVisitorContext context) { - // Expand status:all to (status:active OR status:pending OR status:review) - if (node.Field == "status" && node.Value is TermNode term && term.Term == "all") + // Expand status:all to (status:active OR status:pending OR status:review). + // Re-parsing the expansion is simpler and safer than hand-building AST nodes. + if (node.Field == "status" && node.Query is TermNode { Term: "all" }) { - return Task.FromResult(new GroupNode - { - Child = new BooleanQueryNode - { - Left = new BooleanQueryNode - { - Left = CreateStatusNode("active"), - Operator = QueryOperator.Or, - Right = CreateStatusNode("pending") - }, - Operator = QueryOperator.Or, - Right = CreateStatusNode("review") - } - }); + return LuceneQuery.Parse("(status:active OR status:pending OR status:review)").Document.Query!; } - - return base.VisitAsync(node, context); - } - private static FieldQueryNode CreateStatusNode(string status) => new() - { - Field = "status", - Value = new TermNode { Term = status } - }; + return base.Visit(node, context); + } } ``` @@ -155,7 +137,7 @@ public class ValidationVisitor : QueryVisitor public IReadOnlyList Errors => _errors; public bool IsValid => _errors.Count == 0; - public override Task VisitAsync(TermNode node, IQueryVisitorContext context) + protected override QueryNode Visit(TermNode node, IQueryVisitorContext context) { if (node.Term?.StartsWith('*') == true) { @@ -167,10 +149,10 @@ public class ValidationVisitor : QueryVisitor }); } - return Task.FromResult(node); + return node; } - public override async Task VisitAsync(RangeNode node, IQueryVisitorContext context) + protected override QueryNode Visit(RangeNode node, IQueryVisitorContext context) { // Validate range bounds if (node.Min != null && node.Max != null) @@ -189,7 +171,7 @@ public class ValidationVisitor : QueryVisitor } } - return await base.VisitAsync(node, context); + return base.Visit(node, context); } } @@ -201,45 +183,20 @@ public class ValidationError } ``` -### Async Visitor +### Async work: resolve outside the pipeline -Perform async operations during visitation: +The visitor pipeline is **synchronous by design** — there is no `VisitAsync`. When a transformation +needs data from an async source (for example loading saved queries for `@include`), do the async +work *before* running the pipeline and pass the results in. The built-in include expansion takes a +pre-resolved dictionary: ```csharp -public class AsyncIncludeResolver : QueryVisitor -{ - private readonly IQueryRepository _repository; +// Resolve saved queries asynchronously up front... +var names = new[] { "active-filter", "recent" }; +var includes = await _repository.GetSavedQueriesAsync(names); // your async lookup -> dictionary - public AsyncIncludeResolver(IQueryRepository repository) - { - _repository = repository; - } - - public override async Task VisitAsync(IncludeNode node, IQueryVisitorContext context) - { - if (node.Name == null) - { - return node; - } - - // Load the saved query from the database - var savedQuery = await _repository.GetQueryAsync(node.Name); - if (savedQuery == null) - { - throw new InvalidOperationException($"Saved query '{node.Name}' not found"); - } - - // Parse the saved query - var result = LuceneQuery.Parse(savedQuery); - if (!result.IsSuccess) - { - throw new InvalidOperationException($"Invalid saved query '{node.Name}'"); - } - - // Return the parsed document wrapped in a group - return new GroupNode { Child = result.Document }; - } -} +// ...then expand synchronously. +result.Document.ExpandIncludes(includes); ``` ## Using Visitor Context @@ -249,7 +206,7 @@ The `IQueryVisitorContext` allows passing state: ```csharp public class ContextAwareVisitor : QueryVisitor { - public override async Task VisitAsync(FieldQueryNode node, IQueryVisitorContext context) + protected override QueryNode Visit(FieldQueryNode node, IQueryVisitorContext context) { // Get user from context var user = context.GetValue("CurrentUser"); @@ -261,7 +218,7 @@ public class ContextAwareVisitor : QueryVisitor throw new UnauthorizedAccessException($"Field '{node.Field}' is not accessible"); } - return await base.VisitAsync(node, context); + return base.Visit(node, context); } } @@ -270,7 +227,7 @@ var context = new QueryVisitorContext(); context.SetValue("CurrentUser", currentUser); context.SetValue("AllowedFields", new HashSet { "title", "author", "date" }); -await visitor.AcceptAsync(document, context); +visitor.Accept(document, context); ``` ## Composing Visitors @@ -293,7 +250,7 @@ QueryNode current = document; foreach (var visitor in visitors) { - current = await visitor.AcceptAsync(current, context); + current = visitor.Accept(current, context); } ``` @@ -308,7 +265,7 @@ var chain = new ChainedQueryVisitor() .AddVisitor(new DateMathEvaluatorVisitor(), priority: 30) .AddVisitor(new ValidationVisitor(), priority: 100); -await chain.AcceptAsync(document, context); +chain.Accept(document, context); ``` ## Best Practices @@ -331,21 +288,21 @@ public class DoEverythingVisitor : QueryVisitor { } // Good: Stateless, reusable public class LowercaseVisitor : QueryVisitor { - public override Task VisitAsync(TermNode node, IQueryVisitorContext context) + protected override QueryNode Visit(TermNode node, IQueryVisitorContext context) { node.Term = node.Term?.ToLowerInvariant(); - return Task.FromResult(node); + return node; } } // If state is needed, use context public class StatefulVisitor : QueryVisitor { - public override Task VisitAsync(TermNode node, IQueryVisitorContext context) + protected override QueryNode Visit(TermNode node, IQueryVisitorContext context) { var count = context.GetValue("TermCount"); context.SetValue("TermCount", count + 1); - return Task.FromResult(node); + return node; } } ``` @@ -353,7 +310,7 @@ public class StatefulVisitor : QueryVisitor ### 3. Handle Null Values ```csharp -public override Task VisitAsync(TermNode node, IQueryVisitorContext context) +protected override QueryNode Visit(TermNode node, IQueryVisitorContext context) { // Always check for null if (node.Term != null) @@ -361,7 +318,7 @@ public override Task VisitAsync(TermNode node, IQueryVisitorContext c node.Term = node.Term.ToLowerInvariant(); } - return Task.FromResult(node); + return node; } ``` @@ -393,7 +350,7 @@ public async Task LowercaseVisitor_LowercasesTerms() var visitor = new LowercaseTermsVisitor(); // Act - await visitor.AcceptAsync(result.Document, new QueryVisitorContext()); + visitor.Accept(result.Document, new QueryVisitorContext()); var output = QueryStringBuilder.ToQueryString(result.Document); // Assert @@ -408,7 +365,7 @@ public async Task ValidationVisitor_RejectsLeadingWildcards() var visitor = new ValidationVisitor(); // Act - await visitor.AcceptAsync(result.Document, new QueryVisitorContext()); + visitor.Accept(result.Document, new QueryVisitorContext()); // Assert Assert.False(visitor.IsValid); diff --git a/docs/guide/date-math.md b/docs/guide/date-math.md index e7461cc..a4781e3 100644 --- a/docs/guide/date-math.md +++ b/docs/guide/date-math.md @@ -95,7 +95,7 @@ using Foundatio.Lucene; var result = LuceneQuery.Parse("created:[now-7d TO now]"); // Evaluate the date math expressions -await DateMathEvaluatorVisitor.RunAsync(result.Document); +new DateMathEvaluatorVisitor().Evaluate(result.Document); // Now the date values are resolved to actual dates ``` @@ -129,8 +129,8 @@ using Foundatio.Lucene; var result = LuceneQuery.Parse("date:[now-1d TO now]"); // Custom "now" reference point -var referenceTime = new DateTime(2024, 6, 15, 12, 0, 0); -await DateMathEvaluatorVisitor.RunAsync(result.Document, referenceTime); +var referenceTime = new DateTimeOffset(2024, 6, 15, 12, 0, 0, TimeSpan.Zero); +new DateMathEvaluatorVisitor(referenceTime).Evaluate(result.Document); ``` ## Common Patterns @@ -261,15 +261,15 @@ When testing, use a fixed reference time: ```csharp [Fact] -public async Task DateMath_EvaluatesCorrectly() +public void DateMath_EvaluatesCorrectly() { // Arrange var result = LuceneQuery.Parse("date:[now-1d TO now]"); - var referenceTime = new DateTime(2024, 6, 15, 12, 0, 0, DateTimeKind.Utc); - + var referenceTime = new DateTimeOffset(2024, 6, 15, 12, 0, 0, TimeSpan.Zero); + // Act - await DateMathEvaluatorVisitor.RunAsync(result.Document, referenceTime); - + new DateMathEvaluatorVisitor(referenceTime).Evaluate(result.Document); + // Assert - check the resolved values // Expected: date:[2024-06-14T12:00:00Z TO 2024-06-15T12:00:00Z] } diff --git a/docs/guide/elasticsearch.md b/docs/guide/elasticsearch.md index 523c3c6..4a7152c 100644 --- a/docs/guide/elasticsearch.md +++ b/docs/guide/elasticsearch.md @@ -41,7 +41,7 @@ var parser = new ElasticsearchQueryParser(config => config.DefaultFields = ["title", "content", "description"]; // Default boolean operator (AND or OR) - config.DefaultOperator = QueryOperator.And; + config.DefaultOperator = BooleanOperator.And; // Field aliasing config.FieldMap = new FieldMap @@ -51,23 +51,20 @@ var parser = new ElasticsearchQueryParser(config => { "updated", "metadata.updatedAt" } }; - // Geo field detection - config.IsGeoPointField = field => field == "location" || field.EndsWith("_geo"); - // Date field detection - config.IsDateField = field => - field.EndsWith("date") || + config.IsDateField = field => + field.EndsWith("date") || field.EndsWith("timestamp") || - field == "created" || + field == "created" || field == "updated"; // Default timezone for date ranges config.DefaultTimeZone = "America/Chicago"; - // Include resolver for @include syntax - config.IncludeResolver = async name => + // Pre-resolved @include content (resolve saved queries from your store before building) + config.Includes = new Dictionary { - return await _savedQueryService.GetQueryAsync(name); + ["active"] = "status:active AND deleted:false" }; // Query validation @@ -198,60 +195,9 @@ Field existence checks: ## Geo Queries -The Elasticsearch integration supports geo queries when `IsGeoPointField` is configured. - -### Distance Queries - -```csharp -config.IsGeoPointField = field => field == "location"; - -// Input: field:lat,lon~distance -"location:40.7128,-74.0060~10km" - -// Output -{ - "geo_distance": { - "distance": "10km", - "location": { - "lat": 40.7128, - "lon": -74.0060 - } - } -} -``` - -### Bounding Box Queries - -```csharp -// Input: field:[min_lon,min_lat TO max_lon,max_lat] -"location:[-74.1,40.6 TO -73.9,40.8]" - -// Output -{ - "geo_bounding_box": { - "location": { - "top_left": { "lat": 40.8, "lon": -74.1 }, - "bottom_right": { "lat": 40.6, "lon": -73.9 } - } - } -} -``` - -### Geo Location Resolution - -You can resolve location names to coordinates: - -```csharp -config.GeoLocationResolver = async locationName => -{ - // Resolve "New York" to coordinates - var coords = await _geocodingService.ResolveAsync(locationName); - return coords != null ? $"{coords.Lat},{coords.Lon}" : null; -}; - -// Input -"location:\"New York\"~50mi" -``` +> Geo query generation (`geo_distance` / `geo_bounding_box`) is **not supported in 1.0**. It is +> planned for a later release with a design that keeps the visitor pipeline synchronous (collect geo +> references, resolve coordinates outside the pipeline, then annotate the AST). ## Date Queries @@ -276,14 +222,6 @@ config.DefaultTimeZone = "America/Chicago"; } ``` -## Async API - -For async operations (like include resolution or geo location resolution): - -```csharp -var query = await parser.BuildQueryAsync("@include:saved-filter AND status:active"); -``` - ## Error Handling The parser throws `QueryParseException` for invalid queries: diff --git a/docs/guide/entity-framework.md b/docs/guide/entity-framework.md index 4f68a72..888d1ad 100644 --- a/docs/guide/entity-framework.md +++ b/docs/guide/entity-framework.md @@ -248,7 +248,7 @@ options.AllowedFields.Add("department"); // Validate before executing var parseResult = LuceneQuery.Parse(userQuery); -var validation = await QueryValidator.ValidateAsync(parseResult.Document, options); +var validation = QueryValidator.Validate(parseResult.Document, options); if (!validation.IsValid) { @@ -376,10 +376,10 @@ public class EmployeesController : ControllerBase } // Resolve field aliases - await FieldResolverQueryVisitor.RunAsync(parseResult.Document, FieldMap); + FieldResolverQueryVisitor.Run(parseResult.Document, FieldMap); // Validate the query - var validation = await QueryValidator.ValidateAsync( + var validation = QueryValidator.Validate( parseResult.Document, ValidationOptions ); diff --git a/docs/guide/field-mapping.md b/docs/guide/field-mapping.md index b6247c8..f835aea 100644 --- a/docs/guide/field-mapping.md +++ b/docs/guide/field-mapping.md @@ -19,7 +19,7 @@ var fieldMap = new FieldMap }; var result = LuceneQuery.Parse("user:john AND created:[2024-01-01 TO *]"); -await FieldResolverQueryVisitor.RunAsync(result.Document, fieldMap); +FieldResolverQueryVisitor.Run(result.Document, fieldMap); var resolved = QueryStringBuilder.ToQueryString(result.Document); // Returns: "account.username:john AND metadata.createdAt:[2024-01-01 TO *]" @@ -43,7 +43,8 @@ var fieldMap = new FieldMap ## Hierarchical Field Resolution -For nested field structures, use `ToHierarchicalFieldResolver()`: +`FieldMap.ResolutionMode` is `Hierarchical` by default, so nested field structures resolve by the +longest matching prefix — no extra setup required: ```csharp var fieldMap = new FieldMap @@ -53,13 +54,14 @@ var fieldMap = new FieldMap { "data.created", "payload.metadata.createdAt" } }; -var resolver = fieldMap.ToHierarchicalFieldResolver(); -await FieldResolverQueryVisitor.RunAsync(result.Document, resolver); +FieldResolverQueryVisitor.Run(result.Document, fieldMap); // "data.user:john" -> "payload.account.username:john" // "data.status:active" -> "payload.status:active" (partial match on "data") ``` +Set `fieldMap.ResolutionMode = FieldResolutionMode.Direct` to require exact matches only. + ## Validation with Field Mapping Combine field mapping with validation to restrict allowed fields: @@ -77,10 +79,10 @@ validationOptions.AllowedFields.AddRange(fieldMap.Keys); // First resolve aliases var result = LuceneQuery.Parse(userQuery); -await FieldResolverQueryVisitor.RunAsync(result.Document, fieldMap); +FieldResolverQueryVisitor.Run(result.Document, fieldMap); // Then validate -var validation = await QueryValidator.ValidateAsync(result.Document, validationOptions); +var validation = QueryValidator.Validate(result.Document, validationOptions); ``` ## Dynamic Field Mapping @@ -130,7 +132,7 @@ Func customResolver = field => }; }; -await FieldResolverQueryVisitor.RunAsync(result.Document, customResolver); +FieldResolverQueryVisitor.Run(result.Document, customResolver); ``` ## Field Mapping in Parsers diff --git a/docs/guide/getting-started.md b/docs/guide/getting-started.md index a99c623..942651b 100644 --- a/docs/guide/getting-started.md +++ b/docs/guide/getting-started.md @@ -74,7 +74,7 @@ var fieldMap = new FieldMap { "created", "metadata.timestamp" } }; -await FieldResolverQueryVisitor.RunAsync(result.Document, fieldMap); +FieldResolverQueryVisitor.Run(result.Document, fieldMap); var resolved = QueryStringBuilder.ToQueryString(result.Document); // Returns: "account.username:john AND metadata.timestamp:[2020-01-01 TO 2020-12-31]" @@ -96,7 +96,7 @@ var options = new QueryValidationOptions options.AllowedFields.Add("title"); options.AllowedFields.Add("status"); -var validationResult = await QueryValidator.ValidateAsync(result.Document, options); +var validationResult = QueryValidator.Validate(result.Document, options); if (!validationResult.IsValid) { @@ -184,9 +184,6 @@ var parser = new ElasticsearchQueryParser(config => { "created", "metadata.timestamp" } }; - // Configure geo field detection for geo queries - config.IsGeoPointField = field => field == "location"; - // Configure date field detection for date ranges config.IsDateField = field => field.EndsWith("date") || field.EndsWith("timestamp"); config.DefaultTimeZone = "America/Chicago"; diff --git a/docs/guide/query-syntax.md b/docs/guide/query-syntax.md index 4440c5b..f818946 100644 --- a/docs/guide/query-syntax.md +++ b/docs/guide/query-syntax.md @@ -343,7 +343,8 @@ Reference saved or named queries: ``` ::: info -Include expansion requires configuring an `IncludeResolver` function. +Include expansion requires supplying the referenced queries via the parser's `Includes` dictionary +(or per-request options). Names are resolved against that pre-resolved content. ::: ## Escaping Special Characters diff --git a/docs/guide/validation.md b/docs/guide/validation.md index 0e84417..f17eb27 100644 --- a/docs/guide/validation.md +++ b/docs/guide/validation.md @@ -18,7 +18,7 @@ var options = new QueryValidationOptions options.AllowedFields.Add("title"); options.AllowedFields.Add("status"); -var validationResult = await QueryValidator.ValidateAsync(result.Document, options); +var validationResult = QueryValidator.Validate(result.Document, options); if (!validationResult.IsValid) { @@ -111,14 +111,14 @@ validationOptions.AllowedFields.AddRange(fieldMap.Keys); // Parse and validate var result = LuceneQuery.Parse(userQuery); -var validation = await QueryValidator.ValidateAsync(result.Document, validationOptions); +var validation = QueryValidator.Validate(result.Document, validationOptions); if (!validation.IsValid) { return BadRequest(validation.Message); } // Then resolve and execute -await FieldResolverQueryVisitor.RunAsync(result.Document, fieldMap); +FieldResolverQueryVisitor.Run(result.Document, fieldMap); var filter = parser.BuildFilter(QueryStringBuilder.ToQueryString(result.Document)); ``` @@ -134,7 +134,7 @@ public class CustomValidationVisitor : QueryVisitor public IReadOnlyList Errors => _errors; public bool IsValid => _errors.Count == 0; - public override Task VisitAsync(RangeNode node, IQueryVisitorContext context) + protected override QueryNode Visit(RangeNode node, IQueryVisitorContext context) { // Validate date ranges don't span more than 1 year if (node.Min != null && node.Max != null) @@ -149,13 +149,13 @@ public class CustomValidationVisitor : QueryVisitor } } - return base.VisitAsync(node, context); + return base.Visit(node, context); } - public override async Task VisitAsync(FieldQueryNode node, IQueryVisitorContext context) + protected override QueryNode Visit(FieldQueryNode node, IQueryVisitorContext context) { // Validate specific field requirements - if (node.Field == "email" && node.Value is TermNode term) + if (node.Field == "email" && node.Query is TermNode term) { if (!term.Term?.Contains("@") == true) { @@ -163,13 +163,13 @@ public class CustomValidationVisitor : QueryVisitor } } - return await base.VisitAsync(node, context); + return base.Visit(node, context); } } // Usage var validator = new CustomValidationVisitor(); -await validator.AcceptAsync(result.Document, new QueryVisitorContext()); +validator.Accept(result.Document, new QueryVisitorContext()); if (!validator.IsValid) { @@ -202,7 +202,7 @@ public async Task Search([FromQuery] string q) } // 2. Validate the query - var validation = await QueryValidator.ValidateAsync( + var validation = QueryValidator.Validate( parseResult.Document, _validationOptions ); @@ -213,14 +213,14 @@ public async Task Search([FromQuery] string q) // 3. Run custom validation var customValidator = new CustomValidationVisitor(); - await customValidator.AcceptAsync(parseResult.Document, new QueryVisitorContext()); + customValidator.Accept(parseResult.Document, new QueryVisitorContext()); if (!customValidator.IsValid) { return BadRequest(new { Errors = customValidator.Errors }); } // 4. Resolve fields and execute - await FieldResolverQueryVisitor.RunAsync(parseResult.Document, _fieldMap); + FieldResolverQueryVisitor.Run(parseResult.Document, _fieldMap); var filter = _parser.BuildFilter( QueryStringBuilder.ToQueryString(parseResult.Document) ); @@ -271,7 +271,7 @@ public class QueryComplexityVisitor : QueryVisitor { public int Complexity { get; private set; } = 0; - public override Task VisitAsync(TermNode node, IQueryVisitorContext context) + protected override QueryNode Visit(TermNode node, IQueryVisitorContext context) { Complexity += 1; @@ -287,25 +287,25 @@ public class QueryComplexityVisitor : QueryVisitor } } - return base.VisitAsync(node, context); + return base.Visit(node, context); } - public override Task VisitAsync(RangeNode node, IQueryVisitorContext context) + protected override QueryNode Visit(RangeNode node, IQueryVisitorContext context) { Complexity += 3; - return base.VisitAsync(node, context); + return base.Visit(node, context); } - public override Task VisitAsync(RegexNode node, IQueryVisitorContext context) + protected override QueryNode Visit(RegexNode node, IQueryVisitorContext context) { Complexity += 10; - return base.VisitAsync(node, context); + return base.Visit(node, context); } } // Usage var complexityVisitor = new QueryComplexityVisitor(); -await complexityVisitor.AcceptAsync(result.Document, new QueryVisitorContext()); +complexityVisitor.Accept(result.Document, new QueryVisitorContext()); if (complexityVisitor.Complexity > 50) { @@ -322,7 +322,7 @@ if (complexityVisitor.Complexity > 50) var parseResult = LuceneQuery.Parse(userQuery); if (!parseResult.IsSuccess) { /* handle error */ } -var validation = await QueryValidator.ValidateAsync(parseResult.Document, options); +var validation = QueryValidator.Validate(parseResult.Document, options); if (!validation.IsValid) { /* handle error */ } ``` @@ -343,7 +343,7 @@ options.DisallowedFields.Add("password"); // Easy to forget fields // Parse error + Standard validation + Custom validation var pipeline = new List>> { - doc => QueryValidator.ValidateAsync(doc, standardOptions), + doc => QueryValidator.Validate(doc, standardOptions), doc => ValidateDateRanges(doc), doc => ValidateUserPermissions(doc, currentUser) }; diff --git a/docs/guide/visitors.md b/docs/guide/visitors.md index a3e0e9a..a7885e5 100644 --- a/docs/guide/visitors.md +++ b/docs/guide/visitors.md @@ -32,7 +32,7 @@ var fieldMap = new FieldMap { "created", "metadata.timestamp" } }; -await FieldResolverQueryVisitor.RunAsync(result.Document, fieldMap); +FieldResolverQueryVisitor.Run(result.Document, fieldMap); var resolved = QueryStringBuilder.ToQueryString(result.Document); // Returns: "account.username:john AND metadata.timestamp:[now-1d TO now]" @@ -45,7 +45,7 @@ Evaluate date math expressions to actual dates: ```csharp var result = LuceneQuery.Parse("created:[now-7d TO now]"); -await DateMathEvaluatorVisitor.RunAsync(result.Document); +new DateMathEvaluatorVisitor().Evaluate(result.Document); // Date expressions are now evaluated to actual DateTime values ``` @@ -57,17 +57,13 @@ Expand `@include:name` references to saved queries: ```csharp var result = LuceneQuery.Parse("@include:active-filter AND category:books"); -Func> resolver = async name => +// Pre-resolve saved queries (from a database, file, etc.) into a dictionary. +var includes = new Dictionary { - // Load saved query from database, file, etc. - return name switch - { - "active-filter" => "status:active AND deleted:false", - _ => null - }; + ["active-filter"] = "status:active AND deleted:false" }; -await IncludeVisitor.RunAsync(result.Document, resolver); +result.Document.ExpandIncludes(includes); var expanded = QueryStringBuilder.ToQueryString(result.Document); // Returns: "(status:active AND deleted:false) AND category:books" @@ -80,7 +76,7 @@ Extract all field names used in a query: ```csharp var result = LuceneQuery.Parse("title:hello AND author:john AND date:[2024-01-01 TO *]"); -var fields = await GetReferencedFieldsVisitor.RunAsync(result.Document); +var fields = result.Document.GetReferencedFields(); // Returns: ["title", "author", "date"] ``` @@ -94,27 +90,27 @@ using Foundatio.Lucene.Visitors; public class LowercaseTermVisitor : QueryVisitor { - public override Task VisitAsync(TermNode node, IQueryVisitorContext context) + protected override QueryNode Visit(TermNode node, IQueryVisitorContext context) { // Lowercase the term node.Term = node.Term?.ToLowerInvariant(); - return Task.FromResult(node); + return node; } - public override async Task VisitAsync(FieldQueryNode node, IQueryVisitorContext context) + protected override QueryNode Visit(FieldQueryNode node, IQueryVisitorContext context) { // Lowercase the field name node.Field = node.Field?.ToLowerInvariant(); // Visit children (the field's value) - return await base.VisitAsync(node, context); + return base.Visit(node, context); } } // Usage var result = LuceneQuery.Parse("Title:HELLO"); var visitor = new LowercaseTermVisitor(); -await visitor.AcceptAsync(result.Document, new QueryVisitorContext()); +visitor.Accept(result.Document, new QueryVisitorContext()); var output = QueryStringBuilder.ToQueryString(result.Document); // Returns: "title:hello" @@ -127,7 +123,7 @@ Use `IQueryVisitorContext` to pass state between visitors or across the traversa ```csharp public class FieldCollectorVisitor : QueryVisitor { - public override async Task VisitAsync(FieldQueryNode node, IQueryVisitorContext context) + protected override QueryNode Visit(FieldQueryNode node, IQueryVisitorContext context) { // Get or create the field list in context var fields = context.GetValue>("CollectedFields") ?? new List(); @@ -138,13 +134,13 @@ public class FieldCollectorVisitor : QueryVisitor context.SetValue("CollectedFields", fields); } - return await base.VisitAsync(node, context); + return base.Visit(node, context); } } // Usage var context = new QueryVisitorContext(); -await new FieldCollectorVisitor().AcceptAsync(result.Document, context); +new FieldCollectorVisitor().Accept(result.Document, context); var fields = context.GetValue>("CollectedFields"); ``` @@ -160,7 +156,7 @@ var chain = new ChainedQueryVisitor() .AddVisitor(new LowercaseTermVisitor(), priority: 30) .AddVisitor(new ValidationVisitor(), priority: 100); -await chain.AcceptAsync(document, context); +chain.Accept(document, context); ``` Visitors with lower priority numbers run first. @@ -173,43 +169,40 @@ Override these methods to handle specific node types: public class MyVisitor : QueryVisitor { // Called for the root document - public override Task VisitAsync(QueryDocument node, IQueryVisitorContext context); + protected override QueryNode Visit(QueryDocument node, IQueryVisitorContext context); // Simple terms like: hello - public override Task VisitAsync(TermNode node, IQueryVisitorContext context); + protected override QueryNode Visit(TermNode node, IQueryVisitorContext context); // Quoted phrases like: "hello world" - public override Task VisitAsync(PhraseNode node, IQueryVisitorContext context); + protected override QueryNode Visit(PhraseNode node, IQueryVisitorContext context); // Field queries like: title:hello - public override Task VisitAsync(FieldQueryNode node, IQueryVisitorContext context); + protected override QueryNode Visit(FieldQueryNode node, IQueryVisitorContext context); // Range queries like: [1 TO 10] - public override Task VisitAsync(RangeNode node, IQueryVisitorContext context); + protected override QueryNode Visit(RangeNode node, IQueryVisitorContext context); // Boolean combinations like: a AND b - public override Task VisitAsync(BooleanQueryNode node, IQueryVisitorContext context); + protected override QueryNode Visit(BooleanQueryNode node, IQueryVisitorContext context); // Parenthetical groups like: (a OR b) - public override Task VisitAsync(GroupNode node, IQueryVisitorContext context); + protected override QueryNode Visit(GroupNode node, IQueryVisitorContext context); // Negations like: NOT a - public override Task VisitAsync(NotNode node, IQueryVisitorContext context); + protected override QueryNode Visit(NotNode node, IQueryVisitorContext context); // Existence checks like: _exists_:field - public override Task VisitAsync(ExistsNode node, IQueryVisitorContext context); + protected override QueryNode Visit(ExistsNode node, IQueryVisitorContext context); // Missing checks like: _missing_:field - public override Task VisitAsync(MissingNode node, IQueryVisitorContext context); + protected override QueryNode Visit(MissingNode node, IQueryVisitorContext context); // Match all like: *:* - public override Task VisitAsync(MatchAllNode node, IQueryVisitorContext context); + protected override QueryNode Visit(MatchAllNode node, IQueryVisitorContext context); // Regex patterns like: /pattern/ - public override Task VisitAsync(RegexNode node, IQueryVisitorContext context); - - // Include references like: @include:name - public override Task VisitAsync(IncludeNode node, IQueryVisitorContext context); + protected override QueryNode Visit(RegexNode node, IQueryVisitorContext context); } ``` @@ -220,24 +213,16 @@ Return a different node to replace the current one: ```csharp public class ExpandStatusVisitor : QueryVisitor { - public override Task VisitAsync(FieldQueryNode node, IQueryVisitorContext context) + protected override QueryNode Visit(FieldQueryNode node, IQueryVisitorContext context) { // Replace status:all with a group of all statuses - if (node.Field == "status" && node.Value is TermNode term && term.Term == "all") + if (node.Field == "status" && node.Query is TermNode { Term: "all" }) { - var group = new GroupNode - { - Child = new BooleanQueryNode - { - Left = new FieldQueryNode { Field = "status", Value = new TermNode { Term = "active" } }, - Operator = QueryOperator.Or, - Right = new FieldQueryNode { Field = "status", Value = new TermNode { Term = "pending" } } - } - }; - return Task.FromResult(group); + // Re-parsing is simpler and safer than hand-building AST nodes. + return LuceneQuery.Parse("(status:active OR status:pending)").Document.Query!; } - return base.VisitAsync(node, context); + return base.Visit(node, context); } } @@ -259,14 +244,14 @@ public class RemoveFieldVisitor : QueryVisitor _fieldsToRemove = new HashSet(fields, StringComparer.OrdinalIgnoreCase); } - public override Task VisitAsync(FieldQueryNode node, IQueryVisitorContext context) + protected override QueryNode Visit(FieldQueryNode node, IQueryVisitorContext context) { if (_fieldsToRemove.Contains(node.Field ?? "")) { - return Task.FromResult(null!); + return null!; } - return base.VisitAsync(node, context); + return base.Visit(node, context); } } ``` diff --git a/docs/guide/what-is-foundatio-lucene.md b/docs/guide/what-is-foundatio-lucene.md index 716d4d9..2adc1d9 100644 --- a/docs/guide/what-is-foundatio-lucene.md +++ b/docs/guide/what-is-foundatio-lucene.md @@ -90,7 +90,7 @@ var options = new QueryValidationOptions options.AllowedFields.Add("title"); options.AllowedFields.Add("status"); -var validationResult = await QueryValidator.ValidateAsync(document, options); +var validationResult = QueryValidator.Validate(document, options); ``` ### 🏷️ Field Aliasing @@ -103,7 +103,7 @@ var fieldMap = new FieldMap { "user", "account.username" }, { "created", "metadata.timestamp" } }; -await FieldResolverQueryVisitor.RunAsync(result.Document, fieldMap); +FieldResolverQueryVisitor.Run(result.Document, fieldMap); ``` ### 📅 Date Math Support From 952f1483a41b8da9a7a413cc6c0d28acb3535eed Mon Sep 17 00:00:00 2001 From: "Eric J. Smith" Date: Thu, 25 Jun 2026 00:22:00 -0500 Subject: [PATCH 07/10] Remove unnecessary usings flagged by dotnet format Follow-up to the Elasticsearch enum unification and EF pipeline wiring. --- .../ElasticsearchQueryBuilderVisitor.cs | 1 - .../EntityFrameworkQueryParser.cs | 1 - 2 files changed, 2 deletions(-) diff --git a/src/Foundatio.Lucene.Elasticsearch/ElasticsearchQueryBuilderVisitor.cs b/src/Foundatio.Lucene.Elasticsearch/ElasticsearchQueryBuilderVisitor.cs index 5fdd586..8ed9da4 100644 --- a/src/Foundatio.Lucene.Elasticsearch/ElasticsearchQueryBuilderVisitor.cs +++ b/src/Foundatio.Lucene.Elasticsearch/ElasticsearchQueryBuilderVisitor.cs @@ -1,7 +1,6 @@ using Elastic.Clients.Elasticsearch; using Elastic.Clients.Elasticsearch.QueryDsl; using Foundatio.Lucene.Ast; -using Foundatio.Lucene.Visitors; namespace Foundatio.Lucene.Elasticsearch; diff --git a/src/Foundatio.Lucene.EntityFramework/EntityFrameworkQueryParser.cs b/src/Foundatio.Lucene.EntityFramework/EntityFrameworkQueryParser.cs index 4c8640a..fd94225 100644 --- a/src/Foundatio.Lucene.EntityFramework/EntityFrameworkQueryParser.cs +++ b/src/Foundatio.Lucene.EntityFramework/EntityFrameworkQueryParser.cs @@ -1,7 +1,6 @@ using System.Collections.Concurrent; using System.Linq.Expressions; using System.Reflection; -using Foundatio.Lucene.Ast; using Foundatio.Lucene.Visitors; using Microsoft.EntityFrameworkCore.Metadata; From 8e6285cc852d864b21b110564633122392330d88 Mon Sep 17 00:00:00 2001 From: "Eric J. Smith" Date: Thu, 25 Jun 2026 00:28:16 -0500 Subject: [PATCH 08/10] Cap Elasticsearch test-container heap so integration suites run together Adding the cross-engine parity project introduced a second Elasticsearch container; running the full solution test suite then launched 2x ES + 2x SQL concurrently and exhausted Docker memory. Bound the ES JVM heap (-Xms512m -Xmx512m) in both ES fixtures (the test data sets are tiny) so the full `dotnet test` run is reliable. --- .../ElasticsearchFixture.cs | 2 ++ tests/Foundatio.Lucene.Parity.Tests/CrossEngineFixture.cs | 3 +++ 2 files changed, 5 insertions(+) diff --git a/tests/Foundatio.Lucene.Elasticsearch.Tests/ElasticsearchFixture.cs b/tests/Foundatio.Lucene.Elasticsearch.Tests/ElasticsearchFixture.cs index 52ef5c4..a32ade8 100644 --- a/tests/Foundatio.Lucene.Elasticsearch.Tests/ElasticsearchFixture.cs +++ b/tests/Foundatio.Lucene.Elasticsearch.Tests/ElasticsearchFixture.cs @@ -30,6 +30,8 @@ public ElasticsearchFixture() .WithEnvironment("ELASTIC_PASSWORD", Password) .WithEnvironment("xpack.security.enabled", "true") .WithEnvironment("xpack.security.http.ssl.enabled", "false") + // Cap the JVM heap so the integration test containers can run side by side. + .WithEnvironment("ES_JAVA_OPTS", "-Xms512m -Xmx512m") .WithWaitStrategy(Wait.ForUnixContainer() .UntilHttpRequestIsSucceeded(r => r .ForPort(ElasticsearchPort) diff --git a/tests/Foundatio.Lucene.Parity.Tests/CrossEngineFixture.cs b/tests/Foundatio.Lucene.Parity.Tests/CrossEngineFixture.cs index 044ab70..1cdf771 100644 --- a/tests/Foundatio.Lucene.Parity.Tests/CrossEngineFixture.cs +++ b/tests/Foundatio.Lucene.Parity.Tests/CrossEngineFixture.cs @@ -60,6 +60,9 @@ public CrossEngineFixture() .WithEnvironment("ELASTIC_PASSWORD", EsPassword) .WithEnvironment("xpack.security.enabled", "true") .WithEnvironment("xpack.security.http.ssl.enabled", "false") + // Cap the JVM heap so this container can run alongside the other integration + // containers (the test data set is tiny). + .WithEnvironment("ES_JAVA_OPTS", "-Xms512m -Xmx512m") .WithWaitStrategy(Wait.ForUnixContainer() .UntilHttpRequestIsSucceeded(r => r .ForPort(ElasticsearchPort) From ba30a4238ed4fb2498060b2c830bbe4b1bcc6160 Mon Sep 17 00:00:00 2001 From: "Eric J. Smith" Date: Thu, 25 Jun 2026 16:24:18 -0500 Subject: [PATCH 09/10] docs: drop pointless mentions of non-existent async methods State the API is synchronous positively instead of enumerating *Async methods that do not exist. --- AGENTS.md | 2 +- docs/guide/configuration.md | 2 -- docs/guide/custom-visitors.md | 7 +++---- 3 files changed, 4 insertions(+), 7 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 9cee7bf..c30de57 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -106,7 +106,7 @@ docs # VitePress documentation site ### Common Patterns -- **Async suffix**: Methods that are genuinely asynchronous end with `Async`. The parser, query builders, and visitor pipeline are **synchronous** — there are no `ParseAsync`/`BuildQueryAsync`/`VisitAsync` methods +- **Async suffix**: Methods that are genuinely asynchronous end with `Async`. The parser, query builders, and visitor pipeline are synchronous - **CancellationToken**: Last parameter, defaulted to `default` in public APIs - **Extension methods**: Place in `Extensions/` directory, use descriptive class names (e.g., `QueryNodeExtensions`) - **Logging**: Use structured logging with `ILogger`, log at appropriate levels diff --git a/docs/guide/configuration.md b/docs/guide/configuration.md index 126c11a..6940111 100644 --- a/docs/guide/configuration.md +++ b/docs/guide/configuration.md @@ -2,8 +2,6 @@ This guide covers configuration options for the various components of Foundatio.Lucene. -The parser APIs are **synchronous** — there are no `*Async` parse/build/visitor methods. - ## Core Parser The core parser is stateless and requires no configuration: diff --git a/docs/guide/custom-visitors.md b/docs/guide/custom-visitors.md index 8088550..930b7d2 100644 --- a/docs/guide/custom-visitors.md +++ b/docs/guide/custom-visitors.md @@ -185,10 +185,9 @@ public class ValidationError ### Async work: resolve outside the pipeline -The visitor pipeline is **synchronous by design** — there is no `VisitAsync`. When a transformation -needs data from an async source (for example loading saved queries for `@include`), do the async -work *before* running the pipeline and pass the results in. The built-in include expansion takes a -pre-resolved dictionary: +The visitor pipeline is **synchronous by design**. When a transformation needs data from an async +source (for example loading saved queries for `@include`), do the async work *before* running the +pipeline and pass the results in. The built-in include expansion takes a pre-resolved dictionary: ```csharp // Resolve saved queries asynchronously up front... From edd277b85fe6775630b110cbdeaef7e72857249d Mon Sep 17 00:00:00 2001 From: "Eric J. Smith" Date: Mon, 28 Sep 2026 21:44:45 -0500 Subject: [PATCH 10/10] Align parity test package versions with main Co-Authored-By: Claude Opus 5.5 (1M context) --- .../Foundatio.Lucene.Parity.Tests.csproj | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/Foundatio.Lucene.Parity.Tests/Foundatio.Lucene.Parity.Tests.csproj b/tests/Foundatio.Lucene.Parity.Tests/Foundatio.Lucene.Parity.Tests.csproj index d24ef42..55b9c43 100644 --- a/tests/Foundatio.Lucene.Parity.Tests/Foundatio.Lucene.Parity.Tests.csproj +++ b/tests/Foundatio.Lucene.Parity.Tests/Foundatio.Lucene.Parity.Tests.csproj @@ -1,10 +1,10 @@ - - - - + + + +