基于Linux系统的Elasticsearch-6.2.4 封装.Net调用Elasticsearch的帮助类(六)

※ 简介
  Elasticsearch官网提供两个DLL供.Net调用,一个是Elasticsearch.Net,另一个Nest;之前项目用的是Elasticsearch.Net,但个人感觉用起来没有Nest方便。
  
※区别
  1. Elasticsearch.Net是一个非常底层且灵活的客户端,它不在意你如何的构建自己的请求和响应。它非常抽象,因此所有的Elasticsearch API被表示为方法,没有太多关于你想如何构建json/request/response对象的东东,并且它还内置了可配置、可重写的集群故障转移机制。
  2. Elasticsearch.Net有非常大的弹性,如果你想更好的提升你的搜索服务,你完全可以使用它来做为你的客户端。
  3. NEST是一个高层的客户端,可以映射所有请求和响应对象,拥有一个强类型查询DSL(领域特定语言),并且可以使用.net的特性比如协变、Auto Mapping Of POCOs,NEST内部使用的依然是Elasticsearch.Net客户端。
  
※帮助类

using Elasticsearch.Net;
using Nest;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using WebElasticsearch.Model;
/*
    Elasticsear帮助类
    注意:Nest版本号需要跟安装在服务器的Elasticsearch版本一致,不然批量导入会报错.
 */
namespace WebElasticsearch.Helper
{
     

    public class ElasticsearchHelper
    {
     
        #region 属性

        private  readonly ElasticClient elasticClient;
        private readonly string elasticUrl = "http://192.168.220.128:9200,http://192.168.220.129:9200,http://192.168.220.130:9200";
        
        #endregion

        #region 构造函数
        /// 
        /// 构造函数,通过连接池链接 Elastic 集群
        /// 
        public ElasticsearchHelper()
        {
     

            //获取Elastic集群地8
            string[] _elasticUrl = elasticUrl.Split(',');
            var nodes = new Uri[_elasticUrl.Length];
            for (int i = 0; i < _elasticUrl.Length; i++)
            {
     
                nodes[i] = new Uri(_elasticUrl[i]);
            }
            var pool = new StaticConnectionPool(nodes);
            var settings = new ConnectionSettings(pool);
            elasticClient = new ElasticClient(settings);
        }

        #endregion

        #region Nest 6.0 版本

        #region 添加


        /// 
        /// 异步添加数据 
        /// 
        /// 实体类
        /// 索引名称[可为空]
        /// 
        public async Task AddIndexAsync(Object model, string indexName = "")
        {
     
            string _indexName = indexName.ToLower();
            if (string.IsNullOrEmpty(_indexName))
            {
     
                //获取索引
                string modelStr = model.ToString();
                _indexName = modelStr.Substring(modelStr.LastIndexOf('.') + 1, modelStr.Length - modelStr.LastIndexOf('.') - 1).ToLower();
            }
            var response = await elasticClient.IndexAsync(model, i => i.Index(_indexName));
        }
        /// 
        /// 同步添加数据
        /// 
        /// 实体类
        /// 索引名称[可为空]
        /// 
        public IIndexResponse AddIndex(Object model, string indexName = "")
        {
     
            string _indexName = indexName.ToLower();
            if (string.IsNullOrEmpty(_indexName))
            {
     
                //获取索引
                string modelStr = model.ToString();
                _indexName = modelStr.Substring(modelStr.LastIndexOf('.') + 1, modelStr.Length - modelStr.LastIndexOf('.') - 1).ToLower();
            }


            IIndexResponse response = elasticClient.Index(model, i => i.Index(_indexName));
            return response;
        }


        #endregion

        #region 查询
        /// 
        /// 查询所有索引库
        /// 
        /// 检索关键字
        /// 高亮字段
        /// 
        public ResultData SearchAll<T>(string keyword,string highlightField) where T : class
        {
     
            ResultData r = new ResultData();
            var response = elasticClient.Search<T>(s => s
                .AllIndices()
                .From(0)
                .Size(50)
                .Query(q => q.QueryString(qs => qs.Query(keyword).DefaultOperator(Operator.And)))
                .Highlight(h => h
                    .PreTags("")
                    .PostTags("")
                    .Encoder(HighlighterEncoder.Html)
                    .Fields(
                        fs => fs.Field(highlightField)
                    )
                )
            );

            r.Total = response.Total;
            r.Took = response.Took;
            r.IsValid = response.IsValid;
            r.data = response.Documents;
            r.highlightData = response.Hits;
            return r;
        }
        /// 
        /// 查询指定索引库
        /// 
        /// 索引名称(记得小写)
        /// 检索关键字
        /// 排序字段,降序
        /// 高亮字段
        /// 
        public ResultData SearchIndexName<T>(string indexName, string keyword, string highlightField) where T : class
        {
     
            ResultData r = new ResultData();
            var response = elasticClient.Search<T>(s => s
                .Index(indexName)
                .From(0)
                .Size(50)
                .Query(q => q.QueryString(qs => qs.Query(keyword).DefaultOperator(Operator.And)))
                //.Query(q => q.Match(m => m.Field("code").Query(keyword)))
                .Highlight(h => h
                    .PreTags("")
                    .PostTags("")
                    .Encoder(HighlighterEncoder.Html)
                    .Fields(
                        fs => fs.Field(highlightField)
                    )
                )
            );
            r.Total = response.Total;
            r.Took = response.Took;
            r.IsValid = response.IsValid;
            r.data = response.Documents;
            r.highlightData = response.Hits;
            return r;

        }


        #endregion

        #region 批量添加
        /// 
        /// 批量导入-10万条数据只需要6-8秒
        /// 
        /// 
        /// 
        public int CreateIndex(BulkDescriptor param)
        {
     
            int count = 0;
            var result = elasticClient.Bulk(param);
            if (!result.Errors)
                count = result.Items.Count();
            return count;
        }
        #endregion

        #region 删除

        /// 
        /// 删除全部或者指定-----索引 
        /// 
        /// 
        public ResultData DeleteIndexName(string indexName)
        {
     
            ResultData r = new ResultData();
            IDeleteIndexResponse response;
            if (string.IsNullOrEmpty(indexName))
            {
     
                var descriptor = new DeleteIndexDescriptor(Indices.All).Index(Indices.All);
                response = elasticClient.DeleteIndex(descriptor);
            }
            else
            {
     
                var descriptor = new DeleteIndexDescriptor(indexName).Index(indexName);
                response = elasticClient.DeleteIndex(descriptor);
            }
            r.IsValid = response.IsValid;
            return r;
        }
        /// 
        /// 删除全部或者指定-----索引数据
        /// 
        /// 
        public ResultData DeleteIndexData<T>(string indexName) where T : class
        {
     
            ResultData r = new ResultData();
            IDeleteByQueryResponse response;
            if (!string.IsNullOrEmpty(indexName))
                response = elasticClient.DeleteByQuery<T>(descriptor => descriptor.Index(indexName).Query(q => q.MatchAll()));
            else
                response = elasticClient.DeleteByQuery<T>(descriptor => descriptor.AllIndices().Query(q => q.MatchAll()));
            r.Total = response.Total;
            r.Took = response.Took;
            r.IsValid = response.IsValid;

            return r;
        }


        #endregion

        #endregion

        #region Nest 7.0以上版本才能使用方法

        #region 删除

        /// 
        /// 删除全部或者指定-----索引 
        /// 
        /// 
        //public ResultData DeleteIndexName(string indexName)
        //{
     
        //    ResultData r = new ResultData();
        //    DeleteIndexResponse response = new DeleteIndexResponse();
        //    if(string.IsNullOrEmpty(indexName))
        //        response = elasticClient.Indices.Delete(new DeleteIndexRequest(Indices.All));
        //    else
        //        response = elasticClient.Indices.Delete(new DeleteIndexRequest(indexName));
        //    r.IsValid = response.IsValid;
        //    return r;
        //}
        /// 
        /// 删除全部或者指定-----索引数据
        /// 
        /// 
        //public ResultData DeleteIndexData(string indexName) where T : class
        //{
     
        //    ResultData r = new ResultData();
        //    DeleteByQueryResponse response = new DeleteByQueryResponse();
        //    if (!string.IsNullOrEmpty(indexName))
        //        response = elasticClient.DeleteByQuery(descriptor => descriptor.Index(indexName).Query(q => q.MatchAll()));
        //    else
        //        response = elasticClient.DeleteByQuery(descriptor => descriptor.AllIndices().Query(q => q.MatchAll()));
        //    r.Total = response.Total;
        //    r.Took = response.Took;
        //    r.IsValid = response.IsValid;

        //    return r;
        //}

        #endregion

        #region 判断索引是否存在
        /// 
        /// 判断索引是否存在 Nest 7.0以上版本
        /// 
        /// 
        /// 
        //public bool ExistsIndex(string indexName)
        //{
     
        //    var existsResponse = elasticClient.Indices.Exists(indexName);
        //    return existsResponse.Exists;
        //} 
        #endregion

        #region 同步添加数据
        /// 
        /// 同步添加数据 Nest 7.0以上版本
        /// 
        /// 实体类
        /// 索引名称[可为空]
        /// 
        //public IndexResponse AddIndex(Object model, string indexName = "")
        //{
     
        //    string _indexName = indexName.ToLower();
        //    if (string.IsNullOrEmpty(_indexName))
        //    {
     
        //        //获取索引
        //        string modelStr = model.ToString();
        //        _indexName = modelStr.Substring(modelStr.LastIndexOf('.') + 1, modelStr.Length - modelStr.LastIndexOf('.') - 1).ToLower();
        //    }


        //    IndexResponse response = elasticClient.Index(model, i => i.Index(_indexName));
        //    return response;
        //}

        #endregion

        #endregion


    }
}

※界面调用

using Nest;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebElasticsearch.Helper;
using WebElasticsearch.Model;

namespace WebElasticsearch.Controllers
{
     
    public class ElasticsearchController : Controller
    {
     
        // GET: /Elasticsearch/
        //访问地址:http://localhost:32847/Elasticsearch
        public ActionResult Index()
        {
     

            ElasticsearchHelper es = new ElasticsearchHelper();


            //同步添加数据
            //var user = new User
            //{
     
            //    guid = System.Guid.NewGuid().ToString(),
            //    name = "张员外",
            //    code = "445281111312312412412412",
            //    position = "科员",
            //    createTime = DateTime.Now
            //};

            //es.AddIndex(user);

            //var role = new Role
            //{
     
            //    guid = System.Guid.NewGuid().ToString(),
            //    name = "超级管理员",
            //    remarks="拥有很多权限"
            //};

            //es.AddIndex(role);


            //异步添加数据
            //var user1 = new User
            //{
     
            //    guid = System.Guid.NewGuid().ToString(),
            //    name = "张三4",
            //    code = "445281111312312412412412",
            //    position = "科员4",
            //    createTime = DateTime.Now
            //};
            //es.AddIndexAsync(user1);

            //批量添加
            //BulkDescriptor descriptor = new BulkDescriptor();

            //foreach (var i in Enumerable.Range(0, 100000))
            //{
     
            //    //var user = new User
            //    //{
     
            //    //    guid = System.Guid.NewGuid().ToString(),
            //    //    name = "长林军士兵" + i,
            //    //    code = i.ToString(),
            //    //    position = "士兵" + i,
            //    //    createTime = DateTime.Now
            //    //};
            //    //descriptor.Index(op => op.Index("user").Document(user));
            //    var role = new Role
            //    {
     
            //        guid = System.Guid.NewGuid().ToString(),
            //        name = "梁国管理员" + i,
            //        remarks= "梁朝,拥有很多长林士兵"
            //    };
            //    descriptor.Index(op => op.Index("role").Document(role));
            //}
            //es.CreateIndex(descriptor);



            //查询
            ResultData r = es.SearchIndexName<User>("user", "林","name");
            ResultData r1 = es.SearchAll<User>("长","name");


            删除
            //es.DeleteIndexName("");

            return View();
        }
    }
}

你可能感兴趣的:(Elasticsearch,elasticsearch,.net,linux,大数据)