ElasticSearch.net NEST批量创建修改删除索引完整示例

本示例采用Elasticsearch+Nest

网上查了很多资料,发现用C#调用Elasticsearch搜索引擎的功能代码很分散,功能不完整,多半是非常简单的操作,没有成型的应用示例。比如新增或修改索引,都是发起一个request新增或修改一条数据,当一次性修改几千条数据时,发起的requst请求过多容易导致429 Too Many Request的错误,单个新增修改索引就非常不适用。其实Nest有批量新增、修改索引的功能,批量删除也可以。现将项目中采用Elasticsearch的C#代码分享如下:

使用NEST客户端

1.连接

[csharp] view plain copy
 
  1. public ElasticClient GetElasticClient(string esServer, string IndexName)  
  2. {  
  3.     ElasticClient client = null;  
  4.     string[] server = esServer.Split(',');  
  5.     Uri[] nodes = new Uri[server.Length];  
  6.     for (int i = 0; i < server.Length;i++ )  
  7.     {  
  8.         nodes[i] = new Uri(server[i]);  
  9.     }  
  10.     var connectionPool = new StaticConnectionPool(nodes);  
  11.     var settings = new ConnectionSettings(  
  12.         connectionPool  
  13.     );  
  14.     settings.DefaultIndex(IndexName);   
  15.     client = new ElasticClient(settings);  
  16.     return client;  
  17. }  

2.添加索引

[csharp] view plain copy
 
  1. var indexExist = client.IndexExists(IndexName);  
  2. if (!indexExist.Exists)  
  3. {  
  4.     //基本配置  
  5.     IIndexState indexState = new IndexState()  
  6.     {  
  7.         Settings = new IndexSettings()  
  8.         {  
  9.             NumberOfReplicas = 1,//副本数  
  10.             NumberOfShards = 6//分片数  
  11.         }  
  12.     };  
  13.     //ICreateIndexResponse response = client.CreateIndex(IndexName, p => p.Mappings(m => m.Map<ES_PUB_Stock>(mp => mp.AutoMap())));  
  14.     ICreateIndexResponse response = client.CreateIndex(IndexName, p => p  
  15.         .InitializeUsing(indexState)  
  16.         .Mappings(ms =>  
  17.             ms.Map<ES_PUB_Stock>(m =>   
  18.                 m.AutoMap()  
  19.                 .Properties(ps =>   
  20.                     ps.Nested<ES_PUB_StockPrice>(n =>   
  21.                         n.Name(c => c.stockPrice)  
  22.                         )  
  23.                     .Nested<ES_PUB_SpecValue>(q=>  
  24.                         q.Name(c=>c.specValue))))));  
  25.     if (response.IsValid)  
  26.     {  
  27.         string msg = string.Format("索引创建" + IncrementIndexName + "成功!");  
  28.         this.WriteLog(msg);  
  29.     }  
  30.     else  
  31.     {  
  32.         string msg = string.Format("索引创建" + IncrementIndexName + "失败!");  
  33.         this.WriteLog(msg);  
  34.         Thread.CurrentThread.Abort();  
  35.     }  
  36. }  

这里创建索引设置6个分片数,并Mapping自定义的结构。

Mapping相关类型如下:

[csharp] view plain copy
 
  1. <span style="font-size:14px;">using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using Nest;  
  7.   
  8. namespace SearchMaker.Model.ES.PUB  
  9. {  
  10.     [ElasticsearchType(IdProperty = "sid", Name = "ES_PUB_Stock")]  
  11.     public class ES_PUB_Stock  
  12.     {  
  13.         [Number(Index = NonStringIndexOption.NotAnalyzed, DocValues = false, IgnoreMalformed = true, Coerce = true)]  
  14.         public long? sid { get; set; }  
  15.   
  16.         [String(Index = FieldIndexOption.NotAnalyzed)]  
  17.         public string model { get; set; }  
  18.   
  19.         [String(Index = FieldIndexOption.NotAnalyzed)]  
  20.         public string brand { get; set; }  
  21.   
  22.         [String(Index = FieldIndexOption.NotAnalyzed)]  
  23.         public string encapsulation { get; set; }  
  24.   
  25.         [String(Index = FieldIndexOption.NotAnalyzed)]  
  26.         public string batchNo { get; set; }  
  27.   
  28.         [Number(Index = NonStringIndexOption.NotAnalyzed, DocValues = false, IgnoreMalformed = true, Coerce = true)]  
  29.         public int invQty { get; set; }  
  30.   
  31.         [Date(Format = "yyyy-MM-dd HH:mm:ss")]  
  32.         public string updateTime { get; set; }  
  33.   
  34.         [Number(Index = NonStringIndexOption.NotAnalyzed, DocValues = false, IgnoreMalformed = true, Coerce = true)]  
  35.         public int upByMemberID { get; set; }  
  36.   
  37.         [String(Index = FieldIndexOption.NotAnalyzed)]  
  38.         public string upByMemberName { get; set; }  
  39.   
  40.         [String(Index = FieldIndexOption.NotAnalyzed)]  
  41.         public string guid { get; set; }  
  42.   
  43.         [Number(Index = NonStringIndexOption.NotAnalyzed, DocValues = false, IgnoreMalformed = true, Coerce = true)]  
  44.         public decimal? price { get; set; }  
  45.           
  46.         [Number(Index = NonStringIndexOption.NotAnalyzed, DocValues = false, IgnoreMalformed = true, Coerce = true)]  
  47.         public int? leastQty { get; set; }  
  48.   
  49.         [Number(Index = NonStringIndexOption.NotAnalyzed, DocValues = false, IgnoreMalformed = true, Coerce = true)]  
  50.         public int limitTime { get; set; }  
  51.   
  52.         [String(Index = FieldIndexOption.NotAnalyzed)]  
  53.         public string proImg { get; set; }  
  54.   
  55.         [String(Index = FieldIndexOption.NotAnalyzed)]  
  56.         public string categoryNO { get; set; }  
  57.   
  58.         [String(Index = FieldIndexOption.NotAnalyzed)]  
  59.         public string proRemark { get; set; }  
  60.   
  61.         [Number(Index = NonStringIndexOption.NotAnalyzed, DocValues = false, IgnoreMalformed = true, Coerce = true)]  
  62.         public int type { get; set; }  
  63.           
  64.         [Number(Index = NonStringIndexOption.NotAnalyzed, DocValues = false, IgnoreMalformed = true, Coerce = true)]  
  65.         public int sendToday { get; set; }  
  66.   
  67.         [Number(Index = NonStringIndexOption.NotAnalyzed, DocValues = false, IgnoreMalformed = true, Coerce = true)]  
  68.         public int pickedToday { get; set; }  
  69.           
  70.         [String(Index = FieldIndexOption.NotAnalyzed)]  
  71.         public string categoryName { get; set; }  
  72.   
  73.         [Object(Path = "specValue")]  
  74.         public List<ES_PUB_SpecValue> specValue { get; set; }  
  75.   
  76.         [Object(Path = "stockPrice")]  
  77.         public List<ES_PUB_StockPrice> stockPrice { get; set; }  
  78.   
  79.         [String(Analyzer = "ik", Index = FieldIndexOption.Analyzed)]  
  80.         public string specsName { get; set; }  
  81.   
  82.         [String(Analyzer = "ik", Index = FieldIndexOption.Analyzed)]  
  83.         public string keyword { get; set; }  
  84.   
  85.         [String(Analyzer = "ik", Index = FieldIndexOption.Analyzed)]  
  86.         public string modelAS { get; set; }  
  87.   
  88.         [Number(Index = NonStringIndexOption.NotAnalyzed, DocValues = false, IgnoreMalformed = true, Coerce = true)]  
  89.         public int modelLength { get; set; }  
  90.   
  91.         [Number(Index = NonStringIndexOption.NotAnalyzed, DocValues = false, IgnoreMalformed = true, Coerce = true)]  
  92.         public decimal score { get; set; }  
  93.     }  
  94.   
  95.     [ElasticsearchType(Name = "ES_PUB_StockPrice")]  
  96.     public class ES_PUB_StockPrice  
  97.     {  
  98.         [Number(Index = NonStringIndexOption.NotAnalyzed, DocValues = false, IgnoreMalformed = true, Coerce = true)]  
  99.         public int? minval { get; set; }  
  100.   
  101.         [Number(Index = NonStringIndexOption.NotAnalyzed, DocValues = false, IgnoreMalformed = true, Coerce = true)]  
  102.         public decimal? price { get; set; }  
  103.     }  
  104.   
  105.     [ElasticsearchType(Name = "ES_PUB_Specs")]  
  106.     public class ES_PUB_SpecValue  
  107.     {  
  108.         [String(Index = FieldIndexOption.NotAnalyzed)]  
  109.         public string spec { get; set; }  
  110.   
  111.         [String(Index = FieldIndexOption.NotAnalyzed)]  
  112.         public string value { get; set; }  
  113.     }  
  114. }  
  115. </span>  

这里中文分词采用IK分词

3.单个新增、修改索引

[csharp] view plain copy
 
  1. <span style="font-size:14px;">        private int CreateIndex(ES_PUB_Stock param)  
  2.         {  
  3.             int indexCnt = 0;  
  4.             if (param.sid.GetValueOrDefault(0) > 0)  
  5.             {  
  6.                 var response = client.Index<ES_PUB_Stock>(param, i => i.Index(IndexName).Type(IndexType));  
  7.                 if (response.IsValid)  
  8.                 {  
  9.                     indexCnt++;  
  10.                 }  
  11.                 else  
  12.                 {  
  13.                     this.WriteWarmessage("创建" + IncrementIndexName + "索引,发生异常:SID:" + param.sid.ToString() + "," + response.DebugInformation, "");  
  14.                 }  
  15.             }  
  16.             return indexCnt;  
  17.         }</span>  

 4.批量新增、修改索引

[csharp] view plain copy
 
    1. <span style="font-size:14px;"><span style="white-space:pre">    </span>BulkDescriptor descriptor = new BulkDescriptor();</span><pre name="code" class="csharp"><span style="font-size:14px;"><span style="white-space:pre"> </span>descriptor.Index<ES_PUB_Stock>(op => op.Document(esStock));</span></pre><pre name="code" class="csharp"><span style="font-family: Arial, Helvetica, sans-serif;"><span style="font-size:14px;"><span style="white-space:pre">   </span>       private int CreateIndex(BulkDescriptor param)</span></span><pre name="code" class="csharp">   {</pre><pre name="code" class="csharp">            int count = 0;  
    2.             var result = client.Bulk(param);  
    3.             if (!result.Errors)  
    4.                 count = result.Items.Count();  
    5.             return count;  
    6.         }</pre>  
    7. <pre></pre>  
    8. <pre></pre>  
    9. <p></p>  
    10. <pre></pre>  
    11. <pre></pre>  
    12. <p></p>  
    13. <p><span style="font-size:14px"><span style="white-space:pre"></span><strong>5.单个删除索引</strong></span></p>  
    14. <pre name="code" class="csharp"><span style="font-size:14px;">  private int DeleteIndex(ES_PUB_Stock param)  
    15.         {  
    16.             int indexCnt = 0;  
    17.             if (param.sid.GetValueOrDefault(0) > 0)  
    18.             {  
    19.                 var response = client.Delete<ES_PUB_Stock>(param.sid, i => i.Index(IndexName).Type(IndexType));  
    20.                 if (response.IsValid)  
    21.                 {  
    22.                     indexCnt++;  
    23.                 }  
    24.             }  
    25.             return indexCnt;  
    26.         }</span></pre><span style="font-size:14px"><br>  
    27. </span>  
    28. <p></p>  
    29. <p><span style="font-size:14px">按上方所述,即可实现C#对Elasticsearch的操作。</span></p>  
    30. <p><span style="font-size:14px">NEST对Elasticsearch的结构化查询,待下篇......<br>  
    31. </span><br>  
    32. </p>  
    33. <pre></pre>  
    34. <pre></pre>  
    35.      
    36. </pre>  
原文地址:https://www.cnblogs.com/a-du/p/7098065.html