My Github

Elastic学习之旅 (12) .NET 6应用集成ES - 下

大家好,我是Edison。

上一篇:.NET集成ES进行CRUD

写在开头

在.NET应用中集成ES一般涉及两个方面:

(1)将ES当存储用,类似于MongoDB,做文档的增删查改,这一类操作偏CRUD。

(2)对ES中的数据做查询分析,聚合统计、分组等等,这一类操作偏查询分析。

上一篇我们了解了CRUD,我们今天再来搞定查询和聚合作为本系列的结尾!

增加模型

为了进行今天的查询和聚合,我们在上一篇的demo项目中增加一个Product模型。都是常规字段,就不再解释了。

public class Product : ElasticModelBase
{
    public string Ean { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string Brand { get; set; }
    public string Category { get; set; }
    public decimal Price { get; set; }
    public int Quantity { get; set; }
    public DateTime ReleaseDate { get; set; }
}

与此同时,新增一个ProductRepository:

public class ProductRepository : ElasticRepositoryBase<Product>, IProductRepository
{
    public ProductRepository(IElasticProxy elasticProxy) : base(elasticProxy)
    {
    }

    protected override string IndexName => "products";
}

分页查询

我们在上一篇的demo项目中其实已经做了分页查询的基础实现了:

public virtual async Task<Tuple<int, IList<T>>> QueryAsync(int page, int limit)
{
  var query = await this.Client.SearchAsync<T>(x => x.Index(this.IndexName)
   .From((page -1) * limit)
   .Size(limit));

  return new Tuple<int, IList<T>>(Convert.ToInt32(query.Total), query.Documents.ToList());
}

但很多时候我们还想要根据某个字段排序,我们可以在上一篇的基类的基础上重写一下,在ProductRepository就可以实现:

public override async Task<Tuple<int, IList<Product>>> QueryAsync(int page, int limit)
{
  var query = await this.Client.SearchAsync<Product>(x => x.Index(this.IndexName)
    .From((page - 1) * limit)
    .Size(limit)
    .Sort(x => x.Descending(v => v.ReleaseDate)));

  return new Tuple<int, IList<Product>>(Convert.ToInt32(query.Total), query.Documents.ToList());
}

条件查询(基于Term)

我们在之前的学习中学习了结构化搜索主要是通过Term来进行查询,那么假如我们想要根据EAN字段来查询某个product,则可以在ProductRepository中新增一个方法来实现:

public async Task<IList<Product>> QueryByEanAsync(string ean)
{
  var result = await this.Client.SearchAsync<Product>(x => x.Index(this.IndexName)
    .Query(q => q.Term(p => p.Ean, ean)));
  return result.Documents.ToList();
}

一般来说,Query的结果默认是document集合。这里我们测试结果如下:

那么,如果是多条件查询呢?比如:根据一个key查询EAN或Name,这就是多个Term的Or查询:

public async Task<IList<Product>> QueryByEanOrNameAsync(string key)
{
  var result = await this.Client.SearchAsync<Product>(x => x.Index(this.IndexName)
    .Query(q => q.Term(p => p.Ean, key) || q.Term(p => p.Name, key)));
  return result.Documents.ToList();
}

比如:根据一个key查询Name并只筛选Status="Active"的product,这就是多个Term的And查询:

public async Task<IList<Product>> GetActiveProductsByNameAsync(string key)
{
  var result = await this.Client.SearchAsync<Product>(x => x.Index(this.IndexName)
    .Query(q => q.Term(p => p.Name, key) && q.Term(p => p.Status, "Active")));
  return result.Documents.ToList();
}

聚合统计

我们在之前的学习中学习了聚合查询,那么这里我们通过聚合来统计一下Product数据中Price字段的最大值、最小值和平均值:

public async Task<Nest.AggregateDictionary> QueryPriceAggAsync()
{
  var searchResult = await this.Client.SearchAsync<Product>(x => x.Index(this.IndexName)
    .Size(0) // 代表不返回源数据
    .Aggregations(agg => agg.Average("price_avg", avg => avg.Field("price"))
        .Max("price_max", max => max.Field("price"))
        .Min("price_min", min => min.Field("price")))
    );
  return searchResult.Aggregations;
}

聚合分组

如果我们想要根据某个字段分组查询product数据,那么可以使用聚合分组:

public async Task<Nest.AggregateDictionary> QueryBrandAggAsync()
{
  var searchResult = await this.Client.SearchAsync<Product>(x => x.Index(this.IndexName)
    .Size(0) // 代表不返回源数据
    .Aggregations(agg => agg.Terms("brandgroup", group => group.Field("brand"))
    ));
  return searchResult.Aggregations;
}

小结

本篇,我们了解了如何在ASP.NET 6应用中对ES中的数据进行查询 和 聚合,通过使用这些查询我们可以在应用中实现一些报表功能。到此,本系列的学习之旅就要跟大家说声再见了,12篇说多不多,持续输出就是坚持,希望对你学习ElasticSearch有所帮助。

示例代码

Github:https://github.com/Coder-EdisonZhou/ElasticSamples

参考资料

博客园,包子wxl,《ElasticSearch使用系列-.NET6对接ES

CSDN,阿星Plus,《.NET Core下使用ES

CSDN,风神.NET,《如何在ASP.NET Core中集成ES

极客时间,阮一鸣,《ElasticSearch核心技术与实战

 

posted @ 2024-04-23 08:30  EdisonZhou  阅读(21)  评论(0编辑  收藏  举报