An extensible Lucene-style query parser with support for Elasticsearch and SQL/Entity Framework Core. Build dynamic search APIs, custom dashboards, and powerful query interfaces.
# Core Lucene parser
dotnet add package Foundatio.Parsers.LuceneQueries
# Elasticsearch integration
dotnet add package Foundatio.Parsers.ElasticQueries
# SQL/EF Core integration
dotnet add package Foundatio.Parsers.SqlQueriesThe C# examples use SDK-style projects with implicit usings enabled. Install the package for the integration you use; application-specific clients and contexts are described below.
using Foundatio.Parsers.LuceneQueries;
using Foundatio.Parsers.LuceneQueries.Visitors;
var parser = new LuceneQueryParser();
var result = parser.Parse("field:[1 TO 2]");
// Debug the AST structure
Console.WriteLine(DebugQueryVisitor.Run(result));Output from DebugQueryVisitor:
Group:
Left - Term Range:
Field: field
Original Field: field
IsNegated: False
Max: 2
Min: 1
MinInclusive: True
MaxInclusive: True
Regenerate the original query:
string query = GenerateQueryVisitor.Run(result);
// Output: "field:[1 TO 2]"These examples use a configured ElasticsearchClient named client and an existing my-index index. Its mappings determine field types and query translation; see the official .NET client setup.
using Foundatio.Parsers.ElasticQueries;
var parser = new ElasticQueryParser(c => c
.UseMappings(client, "my-index")
.UseFieldMap(new Dictionary<string, string> {
{ "user", "data.user.identity" }
}));
// Build an Elastic.Clients.Elasticsearch query
var query = await parser.BuildQueryAsync("user:john AND status:active");
// Build aggregations
var aggs = await parser.BuildAggregationsAsync("terms:(status min:created max:created)");
// Build sort
var sort = await parser.BuildSortAsync("-created +name");Here, db is your EF Core context with a Products set whose entity has Name, Description, Status, and Price properties. The parser produces a Dynamic LINQ predicate; EF Core translates it for your database provider.
using System.Linq.Dynamic.Core;
using Foundatio.Parsers.SqlQueries;
using Microsoft.EntityFrameworkCore;
var parser = new SqlQueryParser(c => c
.SetDefaultFields(new[] { "Name", "Description" }));
var context = parser.GetContext(db.Products.EntityType);
string dynamicLinq = await parser.ToDynamicLinqAsync("Status:active AND Price:>100", context);
var results = await db.Products
.Where(parser.ParsingConfig, dynamicLinq)
.ToListAsync();- Term queries:
field:value,field:"quoted phrase" - Range queries:
field:[1 TO 10],field:>100,field:>=2024-01-01 - Boolean operators:
AND,OR,NOT,+,- - Wildcard expressions:
field:val*(*matches zero or more characters),field:va?ue(?matches one). Escape or quote literal wildcards. See Elasticsearch's wildcard syntax. - Existence:
_exists_:field,_missing_:field - Date math:
created:[now-7d TO now] - Geo queries:
location:"New York, NY"~75mi(with a configured location resolver)
The default Elasticsearch query builder translates wildcard, regex, fuzzy, phrase-proximity, and boost syntax and enforces required + clauses under OR. These corrections can change saved-query matches and ranking. Mappings, analyzers, scoring mode, and validation options still determine behavior; other backends have separate contracts. See the compatibility guide for migration, cost controls, and remaining differences from query_string.
Full Query Syntax Reference | Syntax Compatibility with Lucene/Elasticsearch
- Metrics:
min,max,avg,sum,stats,cardinality,percentiles - Buckets:
terms,date,histogram,geogrid,missing - Nested:
terms:(category min:price max:price)
Full Aggregation Syntax Reference
Map user-friendly names to actual field paths:
using Foundatio.Parsers.ElasticQueries;
var parser = new ElasticQueryParser(c => c
.UseFieldMap(new Dictionary<string, string> {
{ "user", "data.user.identity" },
{ "created", "metadata.createdAt" }
}));Define reusable query macros:
using Foundatio.Parsers.ElasticQueries;
var parser = new ElasticQueryParser(c => c
.UseIncludes(new Dictionary<string, string> {
{ "active", "status:active AND deleted:false" },
{ "recent", "created:[now-7d TO now]" }
}));
// Expands @include:active inline
var query = await parser.BuildQueryAsync("@include:active AND category:electronics");Validate and restrict queries:
using Foundatio.Parsers.ElasticQueries;
using Foundatio.Parsers.LuceneQueries;
var parser = new ElasticQueryParser(c => c
.SetValidationOptions(new QueryValidationOptions {
AllowedFields = { "status", "name", "created" },
AllowLeadingWildcards = false,
AllowedMaxNodeDepth = 10
}));
var result = await parser.ValidateQueryAsync("status:active");
if (!result.IsValid)
Console.WriteLine(result.Message);Extend with custom query transformations:
using Foundatio.Parsers.ElasticQueries;
using Foundatio.Parsers.LuceneQueries.Nodes;
using Foundatio.Parsers.LuceneQueries.Visitors;
var parser = new ElasticQueryParser(c => c
.AddVisitor(new CustomVisitor(), priority: 100));
public class CustomVisitor : ChainableQueryVisitor
{
public override Task VisitAsync(TermNode node, IQueryVisitorContext context)
{
// Add your term transformation here.
return base.VisitAsync(node, context);
}
}- Dynamic Search APIs - Let users build complex queries
- Custom Dashboards - User-defined aggregations and visualizations
- Saved Searches - Store and reuse query fragments
- Multi-tenant Filtering - Apply tenant filters transparently
- Query Translation - Parse once, output to multiple backends
- Clone the repository
- Open
Foundatio.Parsers.slnxin Visual Studio or VS Code - Build:
dotnet build - Test:
dotnet test