当前位置:   article > 正文

c#使用Elastic.Clients.Elasticsearch 库进行ElasticSearch的增删改查操作,根据变量动态构建查询条件。

c#使用Elastic.Clients.Elasticsearch 库进行ElasticSearch的增删改查操作,根据变量动态构建查询条件。

实体类Shop结构:

  1. public class Shop
  2. {
  3. public string UUID { set; get; }
  4. public string ItemType { set; get; }
  5. public long ItemId { set; get; }
  6. public string ItemName { set; get; }
  7. public long Gold { set; get; }
  8. public long Number { set; get; }
  9. public string Data { set; get; }
  10. public string Quality { set; get; }
  11. public string Category { set; get; }
  12. public string SellerIp { set; get; }
  13. }

初始化客户端

var client = new ElasticsearchClient(new Uri("http://localhost:9200"));

创建索引

var response = await client.Indices.CreateAsync("dragon");

判断索引是否存在

var response = await client.Indices.ExistsAsync("dragon");

增加数据

var response = await client.IndexAsync(shop, (IndexName)"dragon");

修改数据

var response = await client.UpdateAsync<Shop, Shop>((IndexName)"dragon", 1, u => u.Doc(shop));

判断是否存在
 

var response = await client.ExistsAsync<Shop>(1, idx => idx.Index("dragon"));

删除数据

var response = await client.DeleteAsync((IndexName)"dragon", 1);

查询数据(根据4个变量是否为空,动态构建查询条件).其中,Term是精确匹配,Match是模糊匹配。

  1. protected override async Task ExecuteAsync(CancellationToken stoppingToken)
  2. {
  3. var client = new ElasticsearchClient(new Uri("http://localhost:9200"));
  4. string category = "";
  5. string quality = "";
  6. string itemName = "";
  7. string itemType = "";
  8. List<Action<QueryDescriptor<Shop>>> configure = new List<Action<QueryDescriptor<Shop>>>();
  9. if (!string.IsNullOrEmpty(quality))
  10. {
  11. configure.Add(m => m.Term(t => t.Field(f => f.Quality).Value(FieldValue.String(quality))));
  12. }
  13. if (!string.IsNullOrEmpty(category))
  14. {
  15. configure.Add(m => m.Term(t => t.Field(f => f.Category).Value(FieldValue.String(category))));
  16. }
  17. if (!string.IsNullOrEmpty(itemType))
  18. {
  19. configure.Add(m => m.Term(t => t.Field(f => f.ItemType).Value(FieldValue.String(itemType))));
  20. }
  21. if (!string.IsNullOrEmpty(itemName))
  22. {
  23. configure.Add(m => m.Match(t => t.Field(f => f.ItemName).Query(itemName)));
  24. }
  25. var response = await client.SearchAsync<Shop>(s => s
  26. .Index("dragon")
  27. .From(0)
  28. .Size(16)
  29. .Query(q =>
  30. q.Bool(b => b.Must(configure.ToArray()))
  31. )
  32. );
  33. if (response.IsValidResponse)
  34. {
  35. //本次查询获得的数据
  36. List<Shop> shops = response.Documents.ToList();
  37. //本次查询取得的数据量
  38. int count = response.Documents.Count;
  39. //满足查询条件的总数据量
  40. long total = response.HitsMetadata.Total.Match(x => x.Value, y => y);
  41. }
  42. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/510678
推荐阅读
相关标签
  

闽ICP备14008679号