.net core Elasticsearch 查询更新
记录一下:
数据结构如下:
public class ESUserTransaction
{ public long AccountId { get; set; } public string VarietyName { get; set; } public int OrganizationAgentId { get; set; } public int OrganizationMemberId { get; set; } public int OrganizationChannelId { get; set; } public int OrganizationMinorMakerId { get; set; } public int OrganizationMasterMakerId { get; set; } public List<EsOrder> Order { get; set; } = new List<EsOrder>(); public DateTime CreateTime { get; set; } public DateTime LastTime { get; set; }
} public class EsOrder
{ public long Id { get; set; } public string OrderCode { get; set; } public int TradeHand { get; set; } public decimal Amount { get; set; } public int OrderType { get; set; } public int OrderStatus { get; set; } public DateTime? CreateTime { get; set; }
}
然后开始操作:
建索引 :
public async Task<bool> DoAllSummary()
{
try
{
List<ESUserTransaction> userList = new List<ESUserTransaction>();
var esClient = _esClientProvider.GetClient(); //todo: 处理数据 esClient.CreateIndex(indexKey, p => p.Mappings(ms =>
ms.Map<ESUserTransaction>(m => m.AutoMap().Properties(ps => ps.Nested<EsOrder>(n => n.Name(c => c.Order))))));
return _esClientProvider.BulkAll<ESUserTransaction>(esClient, indexKey, userList);
}
catch (Exception ex)
{
Logger.Error("---DigitalCurrencyExchange.ElasticsearchService.CronJob.DoAllSummary---DoAllSummary---出错", ex);
return false;
}
} public class EsClientProvider : IEsClientProvider
{public ElasticClient GetClient()
{
if (_esclient != null)
return _esclient;
InitClient();
return _esclient;
} private void InitClient()
{
var node = new Uri(_configuration["EsUrl"]);
_esclient = new ElasticClient(new ConnectionSettings(node));
} public bool BulkAll<T>(IElasticClient elasticClient, IndexName indexName, IEnumerable<T> list) where T : class
{
const int size = ;
var tokenSource = new CancellationTokenSource(); var observableBulk = elasticClient.BulkAll(list, f => f
.MaxDegreeOfParallelism()
.BackOffTime(TimeSpan.FromSeconds())
.BackOffRetries()
.Size(size)
.RefreshOnCompleted()
.Index(indexName)
.BufferToBulk((r, buffer) => r.IndexMany(buffer))
, tokenSource.Token); var countdownEvent = new CountdownEvent(); Exception exception = null; void OnCompleted()
{
Logger.Error("BulkAll Finished");
countdownEvent.Signal();
} var bulkAllObserver = new BulkAllObserver(
onNext: response =>
{
Logger.Error($"Indexed {response.Page * size} with {response.Retries} retries");
},
onError: ex =>
{
Logger.Error("BulkAll Error : {0}", ex);
exception = ex;
countdownEvent.Signal();
}); observableBulk.Subscribe(bulkAllObserver); countdownEvent.Wait(tokenSource.Token); if (exception != null)
{
Logger.Error("BulkHotelGeo Error : {0}", exception);
return false;
}
else
{
return true;
}
} }
public interface IEsClientProvider
{
ElasticClient GetClient();
bool BulkAll<T>(IElasticClient elasticClient, IndexName indexName, IEnumerable<T> list) where T : class;
}
查询数据:
//单个字段查询
var result = await esClient.SearchAsync<ESUserTransaction>(d => d.Index(indexKey).Type(typeof(ESUserTransaction)).Query(q => q.Term(t => t.AccountId, dto.AccountId)));
//多个字段查询
var result = esClient.Search<ESUserTransaction>(s => s.Index(indexKey).Query(q => q.Bool(b => b
.Must(bm => bm.Term(tm => tm.AccountId, dto.AccountId),
bm => bm.Term(tm => tm.CreateTime, dto.endDate))
))); //多条件查询 var esClient = this._esClientProvider.GetClient();
SearchRequest sr = new SearchRequest(indexKey, typeof(ESUserTransactions));
BoolQuery bq = new BoolQuery();
List<QueryContainer> list = new List<QueryContainer>(); #region accountId
if (dto.AccountId.HasValue)
{
list.Add(new TermQuery()
{
Field = "accountId",
Value = dto.AccountId
});
}
#endregion #region VarietyName
if (!string.IsNullOrWhiteSpace(dto.VarietyName))
{
list.Add(new TermQuery()
{
Field = "varietyName",
Value = dto.VarietyName
});
}
#endregion #region DateTime
if (!dto.startDate.HasValue)
dto.startDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
list.Add(new DateRangeQuery
{
Field = "createTime",
GreaterThanOrEqualTo = dto.startDate,
}); if (!dto.endDate.HasValue)
dto.endDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day).AddMonths();
list.Add(new DateRangeQuery
{
Field = "createTime",
LessThan = dto.endDate
});
#endregion #region OrderStatus
//list.Add(new TermQuery()
//{
// Field = "orderStatus",
// Value = dto.VarietyName
//});
#endregion bq.Must = list.ToArray();
sr.Query = bq;
sr.Size = ; var result = await esClient.SearchAsync<ESUserTransactions>(sr);
聚合:
var esClient = this._esClientProvider.GetClient(); var result = await esClient.SearchAsync<ESUserTransaction>(d => d.Index(indexKey).Type(typeof(ESUserTransaction)).Size().
Aggregations(a => a.Terms("getorderlist", st => st.Field(f => f.AccountId).
Aggregations(na => na.Nested("order", nat => nat.Path(aa => aa.Order).Aggregations(agg => agg
.Sum("sum_order_amount", m => m.Field(o => o.Order.Sum(oc => oc.Amount)))
.ValueCount("count_statu_amountid", m => m.Field(md => md.Order.FirstOrDefault().Id))
)))))); 聚合2:
sr.Aggregations = new AggregationDictionary()
{
{
"order",new FilterAggregation("order")
{
Filter = new TermQuery { Field = Nest.Infer.Field<ESUserTransactions>(p => p.OrderType), Value = },
Aggregations =
new TermsAggregation("groupby_amountid")
{
Field=Nest.Infer.Field<ESUserTransactions>(p => p.AccountId),
Aggregations = new AggregationDictionary
{
{"es_count",new ValueCountAggregation("es_count", Nest.Infer.Field<ESUserTransactions>(p => p.OrderId))},
{"es_amount", new SumAggregation("es_amount", Nest.Infer.Field<ESUserTransactions>(p =>p.Amount)) },
{"es_tradehand", new SumAggregation("es_tradehand", Nest.Infer.Field<ESUserTransactions>(p =>p.TradeHand)) },
},
}
}
},
{
"position",new FilterAggregation("position")
{
Filter = new TermQuery { Field = Nest.Infer.Field<ESUserTransactions>(p => p.OrderType),Value = },
Aggregations =
new TermsAggregation("groupby_amountid")
{
Field=Nest.Infer.Field<ESUserTransactions>(p => p.AccountId),
Aggregations = new AggregationDictionary
{
{"es_count",new ValueCountAggregation("es_count", Nest.Infer.Field<ESUserTransactions>(p => p.OrderId))},
{"es_amount", new SumAggregation("es_amount", Nest.Infer.Field<ESUserTransactions>(p =>p.Amount)) },
{"es_tradehand", new SumAggregation("es_tradehand", Nest.Infer.Field<ESUserTransactions>(p =>p.TradeHand)) },
},
}
}
}
};
更新 多层数据结构
var esClient = this._esClientProvider.GetClient();
var resultData = await esClient.SearchAsync<ESUserTransaction>(s => s.Index(indexKey).Query(q => q.Bool(b => b
.Must(bm => bm.Term(tm => tm.AccountId, ),
bm => bm.Term(tm => tm.CreateTime, t)))));
var id = resultData.Hits.First().Id;
var nmodel = resultData.Hits.FirstOrDefault().Source;
nmodel.Order.Add(new EsOrder() { Id = , Amount = , OrderType = , OrderStatus = });
esClient.CreateIndex(indexKey, p => p.Mappings(ms =>
ms.Map<ESUserTransaction>(m => m.AutoMap().Properties(ps => ps.Nested<EsOrder>(n => n.Name(c => c.Order))))));
var response =await esClient.UpdateAsync<ESUserTransaction>(id, i => i.Index(indexKey).Type(typeof(ESUserTransaction)).Doc(nmodel));
删除多层数据结构
var esClient = this._esClientProvider.GetClient();
var resultData = await esClient.SearchAsync<ESUserTransaction>(s => s.Index(indexKey).Query(q => q.Bool(b => b
.Must(bm => bm.Term(tm => tm.AccountId, ),
bm => bm.Term(tm => tm.CreateTime, t)))));
var id = resultData.Hits.First().Id;
var nmodel = resultData.Hits.FirstOrDefault().Source;
var removemodel = nmodel.Order.Where(d => d.Id == ).FirstOrDefault();
nmodel.Order.Remove(removemodel);
esClient.CreateIndex(indexKey, p => p.Mappings(ms =>
ms.Map<ESUserTransaction>(m => m.AutoMap().Properties(ps => ps.Nested<EsOrder>(n => n.Name(c => c.Order))))));
var response = await esClient.UpdateAsync<ESUserTransaction>(id, i => i.Index(indexKey).Type(typeof(ESUserTransaction)).Doc(nmodel));
删除索引
var esClient = this._esClientProvider.GetClient();
var response = await esClient.DeleteIndexAsync(indexKey, d => d.Index(indexKey));
.net core Elasticsearch 查询更新的更多相关文章
- ElasticSearch查询 第二篇:文档更新
<ElasticSearch查询>目录导航: ElasticSearch查询 第一篇:搜索API ElasticSearch查询 第二篇:文档更新 ElasticSearch查询 第三篇: ...
- ElasticSearch查询 第五篇:布尔查询
布尔查询是最常用的组合查询,不仅将多个查询条件组合在一起,并且将查询的结果和结果的评分组合在一起.当查询条件是多个表达式的组合时,布尔查询非常有用,实际上,布尔查询把多个子查询组合(combine)成 ...
- [翻译 EF Core in Action 2.3] 理解EF Core数据库查询
Entity Framework Core in Action Entityframework Core in action是 Jon P smith 所著的关于Entityframework Cor ...
- ElasticSearch查询 第四篇:匹配查询(Match)
<ElasticSearch查询>目录导航: ElasticSearch查询 第一篇:搜索API ElasticSearch查询 第二篇:文档更新 ElasticSearch查询 第三篇: ...
- ElasticSearch查询 第三篇:词条查询
<ElasticSearch查询>目录导航: ElasticSearch查询 第一篇:搜索API ElasticSearch查询 第二篇:文档更新 ElasticSearch查询 第三篇: ...
- ElasticSearch查询 第一篇:搜索API
<ElasticSearch查询>目录导航: ElasticSearch查询 第一篇:搜索API ElasticSearch查询 第二篇:文档更新 ElasticSearch查询 第三篇: ...
- Elasticsearch教程(九) elasticsearch 查询数据 | 分页查询
Elasticsearch 的查询很灵活,并且有Filter,有分组功能,还有ScriptFilter等等,所以很强大.下面上代码: 一个简单的查询,返回一个List<对象> .. ...
- asp.net core 3.0 更新简记
asp.net core 3.0 更新简记 asp.net core 3.0 更新简记 Intro 最近把活动室预约项目从 asp.net core 2.2 更新到了 asp.net core 3.0 ...
- Elasticsearch入门教程(五):Elasticsearch查询(一)
原文:Elasticsearch入门教程(五):Elasticsearch查询(一) 版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:h ...
随机推荐
- java UDP聊天与文件传输
package rgy.com.UDP3; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.Action ...
- 2016/2/19 position: fixed absolute relative z-index float 半透明效果
一.position:fixed 锁定位置(相对于浏览器的位置),例如有些网站的右下角的弹出窗口. 显示效果 无论滚动条怎么移动 都固定在显示页面的一个位置不动 二.position:a ...
- 学习Flash Builder编程的准备工作
1. 下载教科书,Essential ActionScript 3.0或者Programming ActionScript 3.0.这将是你的很好的老师.英语不灵的买一本中文版本. 2. 安装Flas ...
- leetcode 784. Letter Case Permutation——所有BFS和DFS的题目本质上都可以抽象为tree,这样方便你写代码
Given a string S, we can transform every letter individually to be lowercase or uppercase to create ...
- 美国诚实签经验——中英文行程单、往返机票、用英语面试的申请者通过率>用中文面试的申请者的通过率、一直保持着微笑,看上去很自信,也很诚恳、户口簿带上最好
在排队等待时据我的观察,用英语面试的申请者通过率>用中文面试的申请者的通过率.一家人申请通过率>单个人通过率:商务签证通过率>旅游签证通过率 一. 面签材料 1. 必备材 ...
- 实现SpringBoot登录
SpringBoot登录 https://www.cnblogs.com/jiekzou/p/9303871.html 通过前面10篇文章的学习,相信我们对SpringBoot已经有了一些了解,那么如 ...
- [loj6089]小Y的背包计数问题
https://www.zybuluo.com/ysner/note/1285358 题面 小\(Y\)有一个大小为\(n\)的背包,并且小\(Y\)有\(n\)种物品. 对于第\(i\)种物品,共有 ...
- python datatime日期和时间值模块
datetime.time():是一个时间类,这个类接受4个参数,分别代表时,分,秒,毫秒.参数的默认值是为0 #!/usr/bin/env python #coding:utf8 import da ...
- source命令用法(转载)
转自:http://zhidao.baidu.com/link?url=mNfsPHSjTEm7llgyMYx0UVNwkJmD_cxLeHtZnHcM6Ms8LDXofVHka_EzHi6GltbR ...
- Java DAO模式
DAO模式: DAO(DateAccessObject,数据存取对象) 位于业务逻辑和持久化数据之间,实现对持久化数据的访问. DAO组成: DAO接口: 数据库的所有操作定义成抽象方法,可以提供多种 ...