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

      IT交流互助QQ群:79190545    (Sql Server / Java / Asp.Net / C# / JS / Jquery / Oracle / My Sql / ) 
           -- 欢迎大家进来 聊天,交流 !!。(定期清理 不说话、潜水太深的同学)

1. 项目中引用 Elasticsearch.Net  

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

          本文以 2.4.1版本为例

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

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

如图: Elasticsearch入门CRUD(新增、查询、修改、删除)_第1张图片

 安装成功:

Elasticsearch入门CRUD(新增、查询、修改、删除)_第2张图片


2.  项目中CRUD案例

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

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

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;

namespace WebApplication1.Models
{
    // [DataContract]
    public class Orders
    {
      //  [DataMember]
        [JsonProperty("OrderID")]  //Newtonsoft.Json  命名空间
        public string OrderID { get; set; }
        [JsonProperty("IsPackageOrder")]
        public int IsPackageOrder { get; set; }
        [JsonProperty("PackageOrderID")]
        public string PackageOrderID { get; set; }
        [JsonProperty("CRSResvID")]
        public string CRSResvID { get; set; }
        [JsonProperty("GuaranteeModeCode")]
        public string GuaranteeModeCode { get; set; }
        [JsonProperty("HotelID")]
        public string HotelID { get; set; }
        [JsonProperty("GuestSrcCode")]
        public string GuestSrcCode { get; set; }
        [JsonProperty("HotelDiscountCode")]
        public string HotelDiscountCode { get; set; }
        [JsonProperty("MemberCardTypeCode")]
        public string MemberCardTypeCode { get; set; }
        [JsonProperty("ResvRouteCode")]
        public string ResvRouteCode { get; set; }
        [JsonProperty("GuestID")]
        public string GuestID { get; set; }
        [JsonProperty("AgreementID")]
        public string AgreementID { get; set; }
        [JsonProperty("MemberCardNo")]
        public string MemberCardNo { get; set; }
        [JsonProperty("TeamID")]
        public string TeamID { get; set; }
        [JsonProperty("Amount")]
        public string Amount { get; set; }
        [JsonProperty("ContactName")]
        public string ContactName { get; set; }
        [JsonProperty("ContactMobile")]
        public string ContactMobile { get; set; }
        [JsonProperty("ContactPhone")]
        public string ContactPhone { get; set; }
        [JsonProperty("ContactFax")]
        public string ContactFax { get; set; }
        [JsonProperty("ContactEmail")]
        public string ContactEmail { get; set; }
        [JsonProperty("Remark1")]
        public string Remark1 { get; set; }
        [JsonProperty("Remark2")]
        public string Remark2 { get; set; }
        [JsonProperty("ResvTime")]
        public string ResvTime { get; set; }
        [JsonProperty("ResvCityCode")]
        public string ResvCityCode { get; set; }
        [JsonProperty("IsPrePaid")]
        public int IsPrePaid { get; set; }
        [JsonProperty("OrderStatusCode")]
        public string OrderStatusCode { get; set; }
        [JsonProperty("CancelReasonCode")]
        public string CancelReasonCode { get; set; }
        [JsonProperty("ConfirmTypeCode")]
        public string ConfirmTypeCode { get; set; }
        [JsonProperty("InputStartTime")]
        public string InputStartTime { get; set; }
        [JsonProperty("InputSpanMS")]
        public int InputSpanMS { get; set; }
        [JsonProperty("InputWorkNo")]
        public string InputWorkNo { get; set; }
        [JsonProperty("CreatedOn")]
        public string CreatedOn { get; set; }
        [JsonProperty("ModifiedBy")]
        public string ModifiedBy { get; set; }
        [JsonProperty("ModifiedOn")]
        public string ModifiedOn { get; set; }
        [JsonProperty("TimeStamp")]
        public string TimeStamp { get; set; }
        [JsonProperty("CRSOldResvRouteCode")]
        public string CRSOldResvRouteCode { get; set; }
        [JsonProperty("ActualDiscount")]
        public float ActualDiscount { get; set; }
        [JsonProperty("AgentName")]
        public string AgentName { get; set; }
        [JsonProperty("DiscountTypeTag")]
        public int DiscountTypeTag { get; set; }
        [JsonProperty("FixedPrice")]
        public string FixedPrice { get; set; }
        [JsonProperty("AgentCode")]
        public string AgentCode { get; set; }
        [JsonProperty("IsApartment")]
        public int IsApartment { get; set; }
        [JsonProperty("TeamProtocalID")]
        public string TeamProtocalID { get; set; }
        [JsonProperty("InvoiceTitle")]
        public string InvoiceTitle { get; set; }
        [JsonProperty("PointIncrementalTimes")]
        public string PointIncrementalTimes { get; set; }
        [JsonProperty("ResvType")]
        public string ResvType { get; set; }
    }
}


  

        /// 
        /// 创建客户端实例
        /// 
        /// 
        private static ElasticClient GetSearchClient()
        {
            //服务器IP地址: 端口号 。(Elasticsearch默认端口:9200) 
            var node = new Uri("http://192.168.210.31:9200"); 
            var settings = new ConnectionSettings(node);
            var client = new ElasticClient(settings);

            //验证索引是否存在
            if (!client.IndexExists("order").Exists)  
            {
                client.CreateIndex("order");    //索引 
            }
            //返回Elasticsearch 操作实例
            return client;
        }


2.1  新增  

     

           //操作ElasticSearch实例
            ElasticClient client = GetSearchClient();
            //新增对象实例化
            Orders orderModel = new Orders();
            //赋值
            orderModel.OrderID = "79190545";
            orderModel.ContactName = "IT交流互助 QQ群: 79190545";
            //初始化插入对象
            IIndexRequest o = new IndexRequest(
                                                            "order",              //_index  :索引
                                                            "orderhis",           //_type   :类型
                                                             orderModel.OrderID   //_id     :标示ID
                                                            )
            {
                Document = orderModel,  //新增数据对象
            };
            //调用新增
            IIndexResponse inxResponse = client.Index(o);
            if (inxResponse.IsValid)
            {
                //操作成功  
            }
            else
            {
                //操作失败
            }

2.2  查询

     string key = "IT交流互助 群: 79190545";  // 需要查询的内容
            int ix = 1; //当前页数
            //实例化 ElasticSearch 操作对象
            ElasticClient client = GetSearchClient();

            //执行查询
            var response = client.Search(s => s
                         .From((ix - 1) * 5)    //起始页
                         .Size(5)               //每页条数
                         .Query(q =>            //查询筛选条件
                                                //这样就查询不出来
                                                //    q.Wildcard(t => t.ContactName, string.Format("*{0}*", key.ToLower()))  || 
                                                //精确查找
                                                // q.Term(t => t.OrderID, key.ToLower())
                                                //|| q.Term(t => t.ContactMobile, key.ToLower())
                                                //|| q.Term(t => t.ContactPhone, key.ToLower())
                                                //模糊检索
                                   q.Wildcard(t => t.OrderID, string.Format("*{0}*", key.ToLower()))
                                  || q.Wildcard(t => t.ContactMobile, string.Format("*{0}*", key.ToLower()))
                                  || q.Wildcard(t => t.ContactPhone, string.Format("*{0}*", key.ToLower()))


                              //这样查询,默认分词检索(相当于  like '%第一个词%' or like '%第二个词%' or like '%第三个词%')
                              //而实际情况只需要 查询  like '%韩世平%'
                              //  q.Match(mq => mq.Field(f => f.OrderID).Analyzer(key.ToLower()))
                              //|| q.Match(mq => mq.Field(f => f.ContactName == key))
                              //|| q.Match(mq => mq.Field(f => f.ContactMobile).Query(key))
                              //|| q.Match(mq => mq.Field(f => f.ContactPhone).Query(key)) 

                              )
             );

            //查询出来的结果对象
            List ResultList = response.Documents.ToList();


2.3   修改

    //实例化 ElascticSearch 操作对象
            ElasticClient client = GetSearchClient();
            //实例化修改对象
            Orders orderModel = new Orders()
            {
                ContactName = "IT交流互助 Q群: 79190545",    //需要修改的数据,不需要修改的可以不写
            };
            //实例化 请求修改对象
            UpdateRequest updRequest = new UpdateRequest(
                                                                                    "order",            //_index  :索引
                                                                                    "orderhis",         //_type   :类型
                                                                                    "R1401001950922"    //_id     :标示ID
                                                                                    )
            {
                Doc = orderModel,   //需要求改的对象
            };
            //调用修改
            IUpdateResponse updResponse = client.Update(updRequest);

            if (updResponse.IsValid)
            {
                //操作成功  
            }
            else
            {
                //操作失败
            }



2.4   删除

    //实例化 ElascticSearch 操作对象
            ElasticClient client = GetSearchClient();
            //实例化删除请求对象
            DocumentPath docPath = new DocumentPath(
                                                                    "R1401001950922"    //_id   :标示ID
                                                                    );

            IDeleteResponse delResponse = client.Delete(
                                                                docPath,               //需要删除的对象
                                                                p => p
                                                                .Index("order")        //_index  :索引
                                                                .Type("orderhis")      //_type   :类型
                                                                );
            if (delResponse.IsValid)
            {
                //操作成功  
            }
            else
            {
                //操作失败
            }




      IT交流互助QQ群:79190545    (Sql Server / Java / Asp.Net / C# / JS / Jquery / Oracle / My Sql / ) 
           -- 欢迎大家进来 聊天,交流 !!。(定期清理 不说话、潜水太深的同学)

你可能感兴趣的:(Elasticsearch入门CRUD(新增、查询、修改、删除))