Elasticsearch入门CRUD(新增、查询、修改、删除)

1. 项目中引用 Elasticsearch.NET  

      Elasticsearch 其他版本可在: http://www.nuget.org/  找到对应的项目以源码 ! 

          本文以 2.4.1版本为例

      首先我们打开项目,点击-工具--》NuGet 包管理器--》程序包管理器控制台 

       在控制台输入安装命令:   Install-Package NEST -Version 2.4.1      (然后回车确认安装)

如图: 

 

 安装成功:


 

2.  项目中CRUD案例

       首先根据数据对象 创建Model 类。

            并且在字段属性上面加上 :  [JsonProperty("字段名")]

 

[csharp] view plain copy
 
  1. <span style="font-size:10px;">using Newtonsoft.Json;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Runtime.Serialization;  
  6. using System.Web;  
  7.   
  8. namespace WebApplication1.Models  
  9. {  
  10.     // [DataContract]  
  11.     public class Orders  
  12.     {  
  13.       //  [DataMember]  
  14.         [JsonProperty("OrderID")]  //Newtonsoft.Json  命名空间  
  15.         public string OrderID { get; set; }  
  16.         [JsonProperty("IsPackageOrder")]  
  17.         public int IsPackageOrder { get; set; }  
  18.         [JsonProperty("PackageOrderID")]  
  19.         public string PackageOrderID { get; set; }  
  20.         [JsonProperty("CRSResvID")]  
  21.         public string CRSResvID { get; set; }  
  22.         [JsonProperty("GuaranteeModeCode")]  
  23.         public string GuaranteeModeCode { get; set; }  
  24.         [JsonProperty("HotelID")]  
  25.         public string HotelID { get; set; }  
  26.         [JsonProperty("GuestSrcCode")]  
  27.         public string GuestSrcCode { get; set; }  
  28.         [JsonProperty("HotelDiscountCode")]  
  29.         public string HotelDiscountCode { get; set; }  
  30.         [JsonProperty("MemberCardTypeCode")]  
  31.         public string MemberCardTypeCode { get; set; }  
  32.         [JsonProperty("ResvRouteCode")]  
  33.         public string ResvRouteCode { get; set; }  
  34.         [JsonProperty("GuestID")]  
  35.         public string GuestID { get; set; }  
  36.         [JsonProperty("AgreementID")]  
  37.         public string AgreementID { get; set; }  
  38.         [JsonProperty("MemberCardNo")]  
  39.         public string MemberCardNo { get; set; }  
  40.         [JsonProperty("TeamID")]  
  41.         public string TeamID { get; set; }  
  42.         [JsonProperty("Amount")]  
  43.         public string Amount { get; set; }  
  44.         [JsonProperty("ContactName")]  
  45.         public string ContactName { get; set; }  
  46.         [JsonProperty("ContactMobile")]  
  47.         public string ContactMobile { get; set; }  
  48.         [JsonProperty("ContactPhone")]  
  49.         public string ContactPhone { get; set; }  
  50.         [JsonProperty("ContactFax")]  
  51.         public string ContactFax { get; set; }  
  52.         [JsonProperty("ContactEmail")]  
  53.         public string ContactEmail { get; set; }  
  54.         [JsonProperty("Remark1")]  
  55.         public string Remark1 { get; set; }  
  56.         [JsonProperty("Remark2")]  
  57.         public string Remark2 { get; set; }  
  58.         [JsonProperty("ResvTime")]  
  59.         public string ResvTime { get; set; }  
  60.         [JsonProperty("ResvCityCode")]  
  61.         public string ResvCityCode { get; set; }  
  62.         [JsonProperty("IsPrePaid")]  
  63.         public int IsPrePaid { get; set; }  
  64.         [JsonProperty("OrderStatusCode")]  
  65.         public string OrderStatusCode { get; set; }  
  66.         [JsonProperty("CancelReasonCode")]  
  67.         public string CancelReasonCode { get; set; }  
  68.         [JsonProperty("ConfirmTypeCode")]  
  69.         public string ConfirmTypeCode { get; set; }  
  70.         [JsonProperty("InputStartTime")]  
  71.         public string InputStartTime { get; set; }  
  72.         [JsonProperty("InputSpanMS")]  
  73.         public int InputSpanMS { get; set; }  
  74.         [JsonProperty("InputWorkNo")]  
  75.         public string InputWorkNo { get; set; }  
  76.         [JsonProperty("CreatedOn")]  
  77.         public string CreatedOn { get; set; }  
  78.         [JsonProperty("ModifiedBy")]  
  79.         public string ModifiedBy { get; set; }  
  80.         [JsonProperty("ModifiedOn")]  
  81.         public string ModifiedOn { get; set; }  
  82.         [JsonProperty("TimeStamp")]  
  83.         public string TimeStamp { get; set; }  
  84.         [JsonProperty("CRSOldResvRouteCode")]  
  85.         public string CRSOldResvRouteCode { get; set; }  
  86.         [JsonProperty("ActualDiscount")]  
  87.         public float ActualDiscount { get; set; }  
  88.         [JsonProperty("AgentName")]  
  89.         public string AgentName { get; set; }  
  90.         [JsonProperty("DiscountTypeTag")]  
  91.         public int DiscountTypeTag { get; set; }  
  92.         [JsonProperty("FixedPrice")]  
  93.         public string FixedPrice { get; set; }  
  94.         [JsonProperty("AgentCode")]  
  95.         public string AgentCode { get; set; }  
  96.         [JsonProperty("IsApartment")]  
  97.         public int IsApartment { get; set; }  
  98.         [JsonProperty("TeamProtocalID")]  
  99.         public string TeamProtocalID { get; set; }  
  100.         [JsonProperty("InvoiceTitle")]  
  101.         public string InvoiceTitle { get; set; }  
  102.         [JsonProperty("PointIncrementalTimes")]  
  103.         public string PointIncrementalTimes { get; set; }  
  104.         [JsonProperty("ResvType")]  
  105.         public string ResvType { get; set; }  
  106.     }  
  107. }</span>  



 

  

[csharp] view plain copy
 
  1. /// <summary>  
  2. /// 创建客户端实例  
  3. /// </summary>  
  4. /// <returns></returns>  
  5. private static ElasticClient GetSearchClient()  
  6. {  
  7.     //服务器IP地址: 端口号 。(Elasticsearch默认端口:9200)   
  8.     var node = new Uri("http://192.168.210.31:9200");   
  9.     var settings = new ConnectionSettings(node);  
  10.     var client = new ElasticClient(settings);  
  11.   
  12.     //验证索引是否存在  
  13.     if (!client.IndexExists("order").Exists)    
  14.     {  
  15.         client.CreateIndex("order");    //索引   
  16.     }  
  17.     //返回Elasticsearch 操作实例  
  18.     return client;  
  19. }  

 

 

2.1  新增  

     

[csharp] view plain copy
 
  1. <span style="font-size:10px;">           //操作ElasticSearch实例  
  2.             ElasticClient client = GetSearchClient();  
  3.             //新增对象实例化  
  4.             Orders orderModel = new Orders();  
  5.             //赋值  
  6.             orderModel.OrderID = "79190545";  
  7.             orderModel.ContactName = "IT交流互助 QQ群: 79190545";  
  8.             //初始化插入对象  
  9.             IIndexRequest<Orders> o = new IndexRequest<Orders>(  
  10.                                                             "order",              //_index  :索引  
  11.                                                             "orderhis",           //_type   :类型  
  12.                                                              orderModel.OrderID   //_id     :标示ID  
  13.                                                             )  
  14.             {  
  15.                 Document = orderModel,  //新增数据对象  
  16.             };  
  17.             //调用新增  
  18.             IIndexResponse inxResponse = client.Index(o);  
  19.             if (inxResponse.IsValid)  
  20.             {  
  21.                 //操作成功    
  22.             }  
  23.             else  
  24.             {  
  25.                 //操作失败  
  26.             }</span>  

 

 

2.2  查询

 

[csharp] view plain copy
 
  1. <span style="font-size:32px;font-weight: bold;">     </span><span style="font-size:10px;">string key = "IT交流互助 群: 79190545";  // 需要查询的内容  
  2.             int ix = 1; //当前页数  
  3.             //实例化 ElasticSearch 操作对象  
  4.             ElasticClient client = GetSearchClient();  
  5.   
  6.             //执行查询  
  7.             var response = client.Search<Orders>(s => s  
  8.                          .From((ix - 1) * 5)    //起始页  
  9.                          .Size(5)               //每页条数  
  10.                          .Query(q =>            //查询筛选条件  
  11.                                                 //这样就查询不出来  
  12.                                                 //    q.Wildcard(t => t.ContactName, string.Format("*{0}*", key.ToLower()))  ||   
  13.                                                 //精确查找  
  14.                                                 // q.Term(t => t.OrderID, key.ToLower())  
  15.                                                 //|| q.Term(t => t.ContactMobile, key.ToLower())  
  16.                                                 //|| q.Term(t => t.ContactPhone, key.ToLower())  
  17.                                                 //模糊检索  
  18.                                    q.Wildcard(t => t.OrderID, string.Format("*{0}*", key.ToLower()))  
  19.                                   || q.Wildcard(t => t.ContactMobile, string.Format("*{0}*", key.ToLower()))  
  20.                                   || q.Wildcard(t => t.ContactPhone, string.Format("*{0}*", key.ToLower()))  
  21.   
  22.   
  23.                               //这样查询,默认分词检索(相当于  like '%第一个词%' or like '%第二个词%' or like '%第三个词%')  
  24.                               //而实际情况只需要 查询  like '%韩世平%'  
  25.                               //  q.Match(mq => mq.Field(f => f.OrderID).Analyzer(key.ToLower()))  
  26.                               //|| q.Match(mq => mq.Field(f => f.ContactName == key))  
  27.                               //|| q.Match(mq => mq.Field(f => f.ContactMobile).Query(key))  
  28.                               //|| q.Match(mq => mq.Field(f => f.ContactPhone).Query(key))   
  29.   
  30.                               )  
  31.              );  
  32.   
  33.             //查询出来的结果对象  
  34.             List<Orders> ResultList = response.Documents.ToList();</span><span style="font-size:32px;font-weight: bold;">  
  35.   
  36. </span>  

 

 

2.3   修改

 

[csharp] view plain copy
 
  1. <span style="font-weight: bold; font-size: 32px;">    </span><span style="font-size:10px;">//实例化 ElascticSearch 操作对象  
  2.             ElasticClient client = GetSearchClient();  
  3.             //实例化修改对象  
  4.             Orders orderModel = new Orders()  
  5.             {  
  6.                 ContactName = "IT交流互助 Q群: 79190545",    //需要修改的数据,不需要修改的可以不写  
  7.             };  
  8.             //实例化 请求修改对象  
  9.             UpdateRequest<Orders, Orders> updRequest = new UpdateRequest<Orders, Orders>(  
  10.                                                                                     "order",            //_index  :索引  
  11.                                                                                     "orderhis",         //_type   :类型  
  12.                                                                                     "R1401001950922"    //_id     :标示ID  
  13.                                                                                     )  
  14.             {  
  15.                 Doc = orderModel,   //需要求改的对象  
  16.             };  
  17.             //调用修改  
  18.             IUpdateResponse<Orders> updResponse = client.Update<Orders>(updRequest);  
  19.   
  20.             if (updResponse.IsValid)  
  21.             {  
  22.                 //操作成功    
  23.             }  
  24.             else  
  25.             {  
  26.                 //操作失败  
  27.             }  
  28.   
  29. </span>  



 

2.4   删除

 

[csharp] view plain copy
 
    1. <span style="font-weight: bold; font-size: 32px;">    </span><span style="font-size:10px;">//实例化 ElascticSearch 操作对象  
    2.             ElasticClient client = GetSearchClient();  
    3.             //实例化删除请求对象  
    4.             DocumentPath<Orders> docPath = new DocumentPath<Orders>(  
    5.                                                                     "R1401001950922"    //_id   :标示ID  
    6.                                                                     );  
    7.   
    8.             IDeleteResponse delResponse = client.Delete<Orders>(  
    9.                                                                 docPath,               //需要删除的对象  
    10.                                                                 p => p  
    11.                                                                 .Index("order")        //_index  :索引  
    12.                                                                 .Type("orderhis")      //_type   :类型  
    13.                                                                 );  
    14.             if (delResponse.IsValid)  
    15.             {  
    16.                 //操作成功    
    17.             }  
    18.             else  
    19.             {  
    20.                 //操作失败  
    21.             }</span><span style="font-weight: bold; font-size: 32px;">  
    22.   
    23. </span>  
posted @ 2017-06-30 15:43  a-du  阅读(745)  评论(0编辑  收藏  举报