擴展Elasticsearch客戶端簡化ES查詢(.net core/framework)

擴展Elasticsearch客戶端簡化ES查詢(.net core/framework)

Elasticsearch .net 客戶端提供了兩種方式進行查詢操作

基於對象構造查詢

new IdsQuery
{
    Name = "named_query",
    Boost = 1.1,
    Values = new List<Id> { 1, 2, 3, 4 },
}

基於lambda語法查詢

q
.Ids(c => c
    .Name("named_query")
    .Boost(1.1)
    .Values(1, 2, 3, 4)
)

兩種方式各有優缺點,最主要原因是條件稍有點複雜後,感覺像在套娃,一層套一層,特別是lambda

如:

var searchResults = this.Client.Search<Project>(s => s
    .Query(q => q
        .Bool(b => b
            .Should(
                bs => bs.Term(p => p.Name, "x"),
                bs => bs.Term(p => p.Name, "y")
            )
        )
    )
);

官方文檔有簡化的寫法,[Writing bool queries | Elasticsearch.Net and NEST: the .NET clients 7.x] | Elastic

但是這種方法式的調用還是很麻煩,避免不了方法組合

對於一般邏輯查詢,通過運算符(d,!=,>,<)處理會更簡潔

以下示例ES版本爲7.x

  1. 安裝nuget包:CRL.Elasticsearch
  2. using CRL;
    using CRL.Elasticsearch;

定義數據源

var builder = DBConfigRegister.GetInstance();
            builder.UseElasticsearch();
            builder.RegisterDBAccessBuild(dbLocation =>
            {
                var dBAccessBuild= new DBAccessBuild(DBType.ES, "http://127.0.0.1:9200/testIndex");
                //定義連接設置
                Func<ConnectionSettings, ConnectionSettings> func = (setting) =>
                {
                    setting.DefaultMappingFor<GoodsInfo>(m => m.IndexName("testIndex"));
                    setting.DefaultMappingFor<GoodsInfoChild>(m => m.IndexName("testIndex"));
                    return setting;
                };
                dBAccessBuild.Data = func;
                return dBAccessBuild;
            });

定義查詢對象

public class GoodsService:BaseProvider<GoodsInfo>
{
}

初始數據

public static void CreateMapping()
        {
            var service = new GoodsService();
            service.DropTable();
            service.CreateEsIndex();
            var list = new List<GoodsInfo>();
            for (int i = 1; i < 11; i++)
            {
                list.Add(new GoodsInfo { Id = i.ToString(), DataType = "Goods", Name = "goods" + i, Number = i });
            }
            service.BatchInsert(list);
            var service2 = new GoodsInfoChildService();
            var childs = new List<GoodsInfoChild>();
            childs.Add(new GoodsInfoChild("1", "100", "History") { GroupCode = "001" });
            childs.Add(new GoodsInfoChild("1", "200", "History") { GroupCode = "001" });
            service2.BatchInsert(childs);

        }

按邏輯查詢

var service = new GoodsService();
var list = service.QueryList(b => b.DataType == "Goods" && b.Id != "2");
Console.WriteLine($"count should 9 {list.Count == 9}");

對結果進行分組

  public static void testAggregationCount()
    {
        var service = new GoodsService();
        var query = service.GetLambdaQuery();
        query.Where(b => b.DataType == "Goods");
        query.GroupBy(b => new { b.DataType, b.Name });
        var list = query.ToAggregationCount();
        Console.WriteLine($"count should 2 {list.Count == 2}");
    }

指定查詢方法

public static void testMethodAll()
        {
            var service = new GoodsService();
            var query = service.GetLambdaQuery();
            var ids = new List<Id>();
            ids.Add("1");
            query.Where(b => b.WithIdsQuery(ids));
            query.Where(b => b.Name.WithWildcardQuery("goods*"));
            query.Where(b => b.Name.WithTermQuery("goods"));
            query.Where(b => b.Name.WithMatchQuery("goods", Operator.And));
            query.Where(b => b.Name.WithMatchPhraseQuery("goods"));
            query.Where(b => b.WithMultiMatchQuery(new string[] { "Name", "DataType" }, "goods", Operator.And, TextQueryType.BestFields));
            query.Where(b => b.WithQueryBase(new WildcardQuery
            {
                Field = "Name",
                Value = "goods"
            }));
        }

子查詢判斷

    public static void testChildQuery()
    {
        var service = new GoodsService();
        var query = service.GetLambdaQuery().Where(b => b.DataType == "Goods");
        var queryChild = query.CreateQuery<GoodsInfoChild>();
        queryChild.Where(b => b.GroupCode == "001");
        query.HasChild(queryChild);
        var list = query.ToList();
        Console.WriteLine($"count should 1 {list.Count == 1}");
    }

源碼示例參考

Data/esTest · hubroxxl/CRL - 碼雲 - 開源中國 (gitee.com)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章