.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 ...
随机推荐
- Linux下的文件夹创建命令使用实践
[文章摘要] 本文以实际的C源程序为样例,介绍了Linux下的文件夹创建命令(mkdir)的用法.为相关开发工作的开展提供了故意的參考. [关键词] C语言 Linux 文件夹创建 makefi ...
- QVariant(相当于是Java里面的Object,是万能的容器,但要注册)
这个类型相当于是Java里面的Object,它把绝大多数Qt提供的数据类型都封装起来,起到一个数据类型“擦除”的作用.比如我们的 table单元格可以是string,也可以是int,也可以是一个颜色值 ...
- [翻译]NUnit---Exception && Utility Methods (六)
网址:http://www.cnblogs.com/kim01/archive/2013/04/01/2994378.html Exception Asserts (NUnit 2.5) Assert ...
- bzoj3295 洛谷P3157、1393 动态逆序对——树套树
题目:bzoj3295 https://www.lydsy.com/JudgeOnline/problem.php?id=3295 洛谷 P3157(同一道题) https://www.luogu.o ...
- 深入理解JMM(Java内存模型) --(六)final
与前面介绍的锁和volatile相比较,对final域的读和写更像是普通的变量访问.对于final域,编译器和处理器要遵守两个重排序规则: 在构造函数内对一个final域的写入,与随后把这个被构造对象 ...
- bzoj2989
坐标轴转化+cdq分治 我们发现那个绝对值不太好搞,于是我们把曼哈顿距离转为切比雪夫距离,x'=x-y,y'=x+y,这样两点之间距离就是max(|x1'-x2'|,|y1'-y2'|),这个距离要小 ...
- STM32: TIMER门控模式控制PWM输出长度
搞了两天单脉冲没搞定,无意中发现,这个利用主从模式的门控方式来控制一路PWM的输出长度很有效. //TIM2 PWM输出,由TIM4来控制其输出与停止 //frequency_tim2:TIM2 PW ...
- E2017E0605-hm
carbon copy 抄送, 抄写与送达 blind carbon copy 密送 blind adj. 失明的; 盲目的,轻率的; contact n. 接触; 触点 v 联系,接触; ...
- bzoj 1637: [Usaco2007 Mar]Balanced Lineup【瞎搞】
我是怎么想出来的-- 把种族为0的都变成-1,按位置x排升序之后,s[i]表示种族前缀和,想要取(l,r)的话就要\( s[r]-s[l-1]==0 s[r]==s[l-1] \),用一个map存每个 ...
- bzoj 1650: [Usaco2006 Dec]River Hopscotch 跳石子【贪心+二分】
脑子一抽写了个堆,发现不对才想起来最值用二分 然后判断的时候贪心的把不合mid的区间打通,看打通次数是否小于等于m即可 #include<iostream> #include<cst ...