Fluent way to query ElasticSearch from C# based on NEST.
Elastic Search & Nest Version | Build | Nuget | Branch |
---|---|---|---|
6.x | master | ||
5.x | 5.x | ||
2.x | 2.x | ||
1.7.x | 1.x |
Complex queries in ElasticSearch JSON query language are barely readable. NEST takes some part of the pain away, but nested lambdas are still painful. FluenNest tries to simplify the query composition. Details are available in the wiki. Motivation and few implementation details are described in this blog post.
var result = client.Search<Car>(sc => sc.Aggregations(agg => agg
.SumBy(x => x.Price)
.CardinalityBy(x => x.EngineType)
);
var container = result.Aggregations.AsContainer<Car>();
var priceSum = container.GetSum(x => x.Price);
var engines = container.GetCardinality(x => x.EngineType);
Conditional sums can be quite complicated with NEST. One has to define a Filter aggregation with nested inner Sum or other aggregation. Here is quicker way with FluentNest:
var result = client.Search<Car>(sc => sc.Aggregations(aggs => aggs
.SumBy(x=>x.Price, c => c.EngineType == EngineType.Diesel)
.SumBy(x=>x.Sales, c => c.CarType == "Car1"))
);
Filtering on multiple conditions might be complicated since you have to compose filters using Bool together with Must or Should methods, often resulting in huge lambdas. FluentNest can compile small expressions into NEST query language:
client.Search<Car>(s => s.FilterOn(f => f.Timestamp > startDate && f.Timestamp < endDate));
client.Search<Car>(s => s.FilterOn(f=> f.Ranking.HasValue || f.IsAllowed);
client.Search<Car>(s => s.FilterOn(f=> f.Age > 10 || f.Age < 20 && f.Name == "Peter");
Quite often you might want to calculate an aggregation per group or per histogram bucket:
var result = client.Search<Car>(sc => sc.Aggregations(agg => agg
.SumBy(s => s.Price)
.GroupBy(s => s.EngineType)
);
var result = client.Search<Car>(s => s.Aggregations(agg => agg
.SumBy(x => x.Price, x => x.EngineType == EngineType.Diesel)
.IntoDateHistogram(date => date.Timestamp, DateInterval.Month)
);
Groups and histograms can be also nested:
var result = client.Search<Car>(sc => sc.Aggregations(agg => agg
.SumBy(s => s.Price)
.GroupBy(s => s.CarType)
.IntoDateHistogram(date => date.Timestamp, DateInterval.Month));