.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 ...
随机推荐
- boost::mpl::eval_if的使用方法
近期看boost的时候总是遇见这个eval_if,不知道啥意思,就没法看下去了,比方 前篇文章boost::serialization 拆分serialize函数分析时就出现这样一段代码: templ ...
- Nginx + FastCgi + Spawn-fcgi + C 架构的server环境搭建
1.Nginx 1.1.安装 Nginx 的中文维基 http://wiki.codemongers.com/NginxChs 下载 Nginx 0.6.26(开发版)(请下载最新版本号) tar z ...
- HFile存储格式
Table of Contents HFile存储格式 Block块结构 HFile存储格式 HFile是參照谷歌的SSTable存储格式进行设计的.全部的数据记录都是通过它来完毕持久化,其内部主要採 ...
- python 【第一篇】初识python
人生苦短,我用python Python是我喜欢的语言,简洁.优美.容易使用.所以我总是很激昂的向朋友宣传Python的好处. python起源 1989年,为了打发圣诞节假期,Guido开始写Pyt ...
- ZOJ 3870 Team Formation 贪心二进制
B - Team Formation Description For an upcoming progr ...
- 【bzoj1150】[CTSC2007]数据备份Backup
将k对点两两相连,求最小长度 易证得,最优方案中,相连的办公楼一定是取相邻的比取不相邻的要更优 然后就可以用贪心来做这道题了.. 将初始所有的线段放进堆里 每次取最短的线段进行连接,且ans+=a[i ...
- qemu常见选项解析
1 -hda file -hdb file.-hdc file.-hdd file 把文件当成hard disk 0.hard disk 1.hard disk 2和hard disk 3. 2 -a ...
- SpringMVC_RESTRUL_CRUD
编写POJO Departmet: package org.springmvc.curd.entity; public class Department { private int id; priva ...
- CANopen——笔记
1. c语言的typedef高级用法 typedef void (*post_sync_t)(CO_Data*); http://zhidao.baidu.com/link?url=_lDBGq_uk ...
- EasyUI Datagrid 分页显示(客户端)
转自:https://blog.csdn.net/metal1/article/details/17536185 EasyUI Datagrid 分页显示(客户端) By ZYZ 在使用JQuery ...