.NET CORE【ES】

一、基础查询

 //条件单个
 var mustQuerys = new List<Func<QueryContainerDescriptor<RequestFunds>, QueryContainer>>();
 //条件集合
 if (input.BrokerIds.Any())
 {
     mustQuerys.Add(q => q.Terms(t => t.Field(f => f.BrokerId).Terms(input.BrokerIds)));
 }
 //关键字检索
  if (!string.IsNullOrEmpty(input.Keyword))
  {
       //关键字搜索
       mustQuerys.Add(q => q.Wildcard(w => w.JYCode, $"*{input.Keyword}*")
        || q.Wildcard(w => w.Payee, $"*{input.Keyword}*")
       );
   }
   //时间范围检索
    if (input.BeginTime != null)
    mustQuerys.Add(q => q.DateRange(d => d.Field(f =>f.CreationTime).GreaterThanOrEquals(input.BeginTime.Value.LocalDateTime.Date)));
    if (input.EndTime != null)
    mustQuerys.Add(q => q.DateRange(d => d.Field(f =>f.CreationTime).LessThan(input.EndTime.Value.LocalDateTime.Date.AddDays(1))));
//或
 if (input.IsAffirm.HasValue && input.IsAffirm.Value == false)
            {
                var should = new List<Func<QueryContainerDescriptor<Proceeds>, QueryContainer>>();
                should.Add(q => q.Term(t => t.IsAffirm, input.IsAffirm));
                should.Add(q => q.Bool(m => m.MustNot(q => q.Exists(t => t.Field(t => t.IsAffirm)))));
                mustQuerys.Add(mu => mu.Bool(b => b.Should(should)));
            }
//不等于
 mustNotQuerys.Add(q => q.Term(t => t.Status.Value, "refund-confirmed"));
//参数时间在库中时间交集检索
 mustNotQuerys.Add(m =>
                (m.DateRange(d => d.Field(f => f.RentBeginTime).GreaterThan(param.RentEndTime.LocalDateTime.Date.AddDays(1)))) 
                ||
                (m.DateRange(d => d.Field(f => f.RentEndTime).LessThan(param.RentBeginTime.LocalDateTime.Date)))
                );

    var query = await _elastic.SearchAsync<RequestFunds>(s =>
                s.Index(ESIndexName.RequestFunds + "*")
                .Query(q => q.Bool(b => b.Must(mustQuerys).MustNot(mustNotQuerys)))
                .Sort(o => o.Descending(d => d.ProcessingDate))
                .From((input.PageIndex - 1) * input.PageSize)
                .Size(input.PageSize)
            );
            var queryDocs = query.Documents;
    	 	//关联表转定信息
            var depositQuery = await _elastic.SearchAsync<Deposits>(s =>
                s.Index(ESIndexName.Deposit)
                .Query(q => q.Terms(t => t.Field(f => f.JYCode).Terms(queryDocs.Select(e =>e.JYCode).ToArray())))
                .Size(_defaultSearchSize)
            );
            return new PageModel<RequestFundsDto>(Convert.ToInt32(query.Total), query.Documents.Select(o =>
                new RequestFundsDto(o.QKCode.ToString(), o.JYCode, o.DemandType, o.SignType, o.RequestFundsAmount, o.Payee,
                o.CreationTime.DateTime, o.CirculationStatus, o.ProcessingStatus, o.ProcessingDate, o.BrokerId, o.BrokerName,
                o.BrokerPhone, o.Category, depositQuery.Documents.FirstOrDefault(d => d.JYCode == o.JYCode),
                o.CompanyName,o.DepartmentName, o.BigRegionName, o.RegionName, o.StoreName, o.GroupName
                )));
 

二、基础新增

//批量插入    input.Accessories是集合
RequestFundsBingAccessoriesInput rfbai = new RequestFundsBingAccessoriesInput();
ValueNameItem accesType = rfbai.AccessoryTypeInput(input.AccessoriesFlag);
var accessory = input.Accessories.Select(o => new Accessory(input.QKCode, accesType, o.AccessoryName, o.AccessoryUrl?.ToModel(), o.AccessoryRemarks, broker.Name));
var bulkResponse = await _elastic.BulkAsync(b => b.Index(ESIndexName.Accessory).CreateMany(accessory).Refresh(Refresh.True));
if (!bulkResponse.IsValid)
    Console.WriteLine($"新增请款项附件{input.QKCode}失败:" + bulkResponse.DebugInformation);

//单条新增一
var requestFunds = new RequestFunds(Guid.Parse(id), request.JYCode, qkCode,
                                request.RequestFundsAmount, request.PaymentType,
                                request.RequestFundsRemark, request.BankCardType,
                                request.BankOpenName,request.Payee, request.BankAccount,
                                request.PhoneNumber, request.IdCard, JYCodeExtension.GetBrokerCode(_elastic, broker.CompanyId, broker.Id), 
                                broker, broker.City, request.Category,request.RfOptFlag
                                ,request.CollectionType,request.BranchOpenName, signType,"意向","意向金",request.RefundType);
var response = await _elastic.UpdateAsync<RequestFunds>(new UpdateRequest<RequestFunds, RequestFunds>(ESIndexName.RequestFunds, TypeName.From<RequestFunds>(), id)
{
    Doc = requestFunds,
    Refresh = Refresh.True
});
//单条新增二
 var logContentObject = new LogContentObject(qkCode, "新增请款", "QK");
 var log = new OperationLog(request.JYCode, $"{broker.OuName}-{broker.Name}",null, JsonConvert.SerializeObject(logContentObject),null, broker.City,null);
 var logresponse = await _elastic.CreateAsync<OperationLog>(log, c => c.Index(ESIndexName.OperationLog).Refresh(Refresh.True));

三、基础删除

  var mustQuerys = new List<Func<QueryContainerDescriptor<RequestFunds>, QueryContainer>>();
  mustQuerys.Add(q => q.DateRange(d => d.Field(f => f.CreationTime).GreaterThanOrEquals("2021-06-01T14:52:18.711Z")));
  mustQuerys.Add(q => q.DateRange(d => d.Field(f => f.CreationTime).LessThan(DateTime.Now.AddDays(1))));
  var query = await _elastic.SearchAsync<RequestFunds>(s =>
             s.Index(ESIndexName.RequestFunds + "*")
             .Query(q => q.Bool(b => b.Must(mustQuerys)))
             .Sort(o => o.Descending(d => d.ProcessingDate))
             .Size(1000)
            );
            //var requestFunds = query.Documents.FirstOrDefault();
  foreach (var del in query.Documents) {
      var response = await _elastic.DeleteAsync<RequestFunds>(del, d => d.Index(ESIndexName.RequestFunds).Refresh(Refresh.True));
      if (!response.IsValid)
          throw new DomainException("删除失败:" + response.DebugInformation);
  }

四、基础修改

 //请款信息
 var queryRequestFunds = await _elastic.SearchAsync<RequestFunds>(s =>
    s.Index(ESIndexName.RequestFunds)
    .Query(q => q.Term(t => t.QKCode, request.QKCode))
);
 if (queryRequestFunds.Total == 0)
     throw new DomainException("请款不存在");
 var requestFunds = queryRequestFunds.Documents.FirstOrDefault();
 var path = new DocumentPath<RequestFunds>(requestFunds);
 var response = await _elastic.UpdateAsync<RequestFunds, object>(path, p =>
     p.Index(ESIndexName.RequestFunds)
     .Doc(new
     {
         processingDate = DateTime.Now,
         rejectReason = request.RejectReason,
         isAccountConfirmed = isConf,
         accountingOpeStatus = true
     })
     .Refresh(Refresh.True)
 );
 if (!response.IsValid)
     throw new DomainException("修改失败:" + response.DebugInformation);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您好!对于在.NET Core中使用Elasticsearch,您可以使用官方提供的Elasticsearch .NET客户端库。这个库为您提供了一个简单而强大的方式来与Elasticsearch进行交互。 首先,您需要在.NET Core项目中安装Elasticsearch .NET客户端库。您可以通过NuGet包管理器或通过命令行来执行安装。在安装完成后,您可以在代码中导入所需的命名空间。 接下来,您需要与Elasticsearch建立连接。您可以使用`ConnectionSettings`类来配置连接参数,例如Elasticsearch服务器的URL、索引名称等。然后,使用`ElasticClient`类创建一个客户端实例来执行各种操作,如索引创建、文档插入、搜索等。 以下是一个简单的示例代码,演示如何在.NET Core中使用Elasticsearch进行基本操作: ``` using Elasticsearch.Net; using Nest; class Program { static void Main(string[] args) { var settings = new ConnectionSettings(new Uri("http://localhost:9200")) .DefaultIndex("your_index_name"); var client = new ElasticClient(settings); // 创建索引 var createIndexResponse = client.Indices.Create("your_index_name", c => c .Map<Document>(m => m.AutoMap()) ); // 插入文档 var document = new Document { Id = 1, Title = "Hello World", Content = "This is a sample document" }; var indexResponse = client.IndexDocument(document); // 搜索文档 var searchResponse = client.Search<Document>(s => s .Query(q => q .Match(m => m .Field(f => f.Title) .Query("Hello") ) ) ); // 输出搜索结果 foreach (var hit in searchResponse.Hits) { Console.WriteLine($"Id: {hit.Source.Id}, Title: {hit.Source.Title}, Content: {hit.Source.Content}"); } } } public class Document { public int Id { get; set; } public string Title { get; set; } public string Content { get; set; } } ``` 这只是一个简单的示例,您可以根据自己的需求扩展和定制。希望对您有所帮助!如果您有任何进一步的问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值