.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上安装zsh
简单介绍: 相对于绝大多数linux发行版默认的shell--bash,zsh绝对是一个优秀的替代品.zsh是交互型shell,同一时候它也是一个强大的编程语言,很多bash,ksh,tcsh优秀的地 ...
- tt1
DIm #include iostream.h#include iostream.h# #include iostream.h http://www.cnblogs.com/cmt/archive/2 ...
- php(cli模式)执行文件传递参数
php -f index.php hello test 2314 shell命令执行php文件不像http那样通过GET方式传参 同样php文件获取的时候也不能用$_GET方法了 而是通过$argv[ ...
- Cocos2d-x编译Android环境
1.Android环境搭配: 下载jdk 下载Android ADT 下载安装Android SDK,地址:http://developer.android.com/sdk/index.html#do ...
- [办公自动化]如何将PPT转为PDF,免费
同事需要把PPT格式的文档转为PDF.她没有安装adobe acrobat,安装了微软office 2007. 这个其实可以通过安装微软官方插件来解决.无需额外费用. 所需软件为: 2007 Micr ...
- 【bzoj3124】[Sdoi2013]直径
1.求树的直径: 先随便取一个点,一遍dfs找到离它最远的点l1,再以l1为起点做一遍dfs,找到离l1最远的点l2 那么l1到l2的距离即为直径 2. 求出有多少条边在这棵树的所有直径上: ...
- EL 隐含对象
EL 隐含对象(11个):
- ViewControl的size设为freeform
freeform的用处是让你写一些不标准的view,比如说自定义一个cell,或者自己写一个小的VIEW,freeform的XIB是可以自己拖拽更改大小的
- Java 基础 —— 注解
注解(annotation)不是注释(comment): 注解,是一种元数据(metadata),可为我们在代码中添加信息提供了一种形式化的方法.注解在一定程度上实现了元数据和源代码文件的结合,而不是 ...
- 第十二周 Leetcode 354. Russian Doll Envelopes(HARD) LIS问题
Leetcode354 暴力的方法是显而易见的 O(n^2)构造一个DAG找最长链即可. 也有办法优化到O(nlogn) 注意 信封的方向是不能转换的. 对第一维从小到大排序,第一维相同第二维从大到小 ...