隐藏

在C#中如何操作ElasticSearch的增册改查

发布:2023/1/16 11:50:51作者:管理员 来源:本站 浏览次数:319

目录


   一、ElasticSearch的.net客户端驱动程序

   二、NEST驱动程序的简单使用


 


正文

回到顶部

一、ElasticSearch的.net客户端驱动程序


ElasticSearch官方网站提供了两个.net客户端驱动程序,其中Elasticsearch.Net是一个非常底层且灵活的客户端驱动程序,用户需要手动创建请求(Request)和响应(Response);而NEST是一个高层的客户端,其内部使用的依然是Elasticsearch.Net驱动程序,NEST拥有查询DSL(领域特定语言),能够映射所有请求和响应对象,使用起来比较方便。不同版本的NEST驱动程序,其提供的接口变化很大,在熟悉Nest之后,可以使用Elasticsearch.Net驱动程序来编写自己的代码,免受更新之苦。

回到顶部

二、NEST驱动程序的简单使用


参考:github.com/elastic/elasticsearch-net


1、连接到ElasticSearch引擎服务器


注意,默认索引的名称必须小写,建议将索引名,文档类型名称,和字段名称都小写。


可以通过单个节点或者指定多个节点使用连接池链接到Elasticsearch集群,使用连接池要比单个节点链接到Elasticsearch更有优势,比如支持负载均衡、故障转移等。


通过单点链接:

复制代码


using Nest;    

public static class Setting

{

   public static string strConnectionString=@"http://localhost:9200";

   public static Uri Node

   {

       get

       {

           return new Uri(strConnectionString);

       }

   }

   public static ConnectionSettings ConnectionSettings

   {

       get

       {

           return new ConnectionSettings(Node).DefaultIndex("default");

       }

   }

}


复制代码


通过连接池链接:

复制代码


var nodes = new Uri[]

{

   new Uri("http://myserver1:9200"),

   new Uri("http://myserver2:9200"),

   new Uri("http://myserver3:9200")

};


var pool = new StaticConnectionPool(nodes);

var settings = new ConnectionSettings(pool);

var client = new ElasticClient(settings);


复制代码


 


2、索引创建、删除


为了知道请求需要操作哪个索引,Elasticsearch API期望收到一个或多个索引名称作为请求的一部分。

复制代码


/// <summary>

       /// 创建索引

       /// </summary>

       /// <param name="indexName"></param>

       public static void CreateIndex(string indexName)

       {

           var descriptor = new CreateIndexDescriptor(indexName)

               .Settings(s => s.NumberOfShards(6).NumberOfReplicas(2));//该索引的分片数为6、副本数为2。

           var result = client.CreateIndex(descriptor);

           if (result != null && result.ApiCall != null)

           {

               var callResult = result.ApiCall;

               Console.WriteLine($"创建索引{indexName}返回的结果:\r\n {JsonConvert.SerializeObject(result)}");

               if (callResult.Success)

               {

                   Console.WriteLine("创建索引成功!");

               }


               else

               {

                   Console.WriteLine($"创建索引失败!\r\n {result.ServerError}");

               }

           }

       }


       /// <summary>

       /// 删除索引

       /// </summary>

       /// <param name="indexName"></param>

       public static void DeleteIndex(string indexName)

       {

           var descriptor = new DeleteIndexDescriptor(indexName).Index(indexName);

           var result = client.DeleteIndex(descriptor);

           if (result != null && result.ApiCall != null)

           {

               var callResult = result.ApiCall;

               Console.WriteLine($"删除索引{indexName}返回的结果:\r\n {JsonConvert.SerializeObject(result)}");

               if (callResult.Success)

               {

                   Console.WriteLine("删除索引成功!");

               }

               else

               {

                   Console.WriteLine($"删除索引失败!\r\n {result.ServerError}");

               }

           }

       }


复制代码


//删除指定索引所在节点下的所有索引

var descriptor = new DeleteIndexDescriptor("db_student").AllIndices();


3、添加数据(类型和文档)


 

复制代码


/// <summary>

       /// 直接添加数据,通过索引

       /// </summary>

       public static void IndexDocument()

       {

           var student = new Student

           {

               Id = 2,

               User = "kimchyTwo",

               PostDate = new DateTime(2019, 11, 15),

               Message = "Trying out NEST, so far so good?"

           };

           //添加/更新 单一文档

           //var response = client.Index(student, idx => idx.Index("studentdb"));

           //or specify index via settings.DefaultIndex("mytweetindex");

           var response = client.IndexAsync(student, idx => idx.Index("studentdb"));

           Console.WriteLine($"添加数据返回的结果: \r\n { JsonConvert.SerializeObject(response)}");


           //批量添加/更新文档

           //var list = new List<Student>();

           //client.IndexMany<Student>(list);

       }


复制代码


4、获取数据


NEST提供了支持Lambda链式query DLS(领域特定语言)方式

复制代码


/// <summary>

       /// 获取数据

       /// </summary>

       public static void GetDocument()

       {

           var response = client.Get<Student>(1, idx => idx.Index("studentdb")); // returns an IGetResponse mapped 1-to-1 with the Elasticsearch JSON response

           var tweet = response.Source; // the original document

           Console.WriteLine($"获取studentdb索引的数据:\r\n {JsonConvert.SerializeObject(tweet)}");

       }


       /// <summary>

       /// 查询数据

       /// </summary>

       public static void QueryDocument()

       {

           var response = client.Search<Student>(s => s.From(0).Size(10)

               .Index("studentdb")   //需要自己指定index

               .Query(q => q

                   .Term(t => t.User, "kimchy") || q

                   .Match(mq => mq.Field(f => f.User).Query("nest"))

                       )

               );

           Console.WriteLine(JsonConvert.SerializeObject(response.Documents));

       }


复制代码