• ElasticSearch使用C#操作文档


    一、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");
            }
        }
    }
    View Code

    通过连接池链接:

    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);
    View Code

    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}返回的结果:
     {JsonConvert.SerializeObject(result)}");
                    if (callResult.Success)
                    {
                        Console.WriteLine("创建索引成功!");
                    }
    
                    else
                    {
                        Console.WriteLine($"创建索引失败!
     {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}返回的结果:
     {JsonConvert.SerializeObject(result)}");
                    if (callResult.Success)
                    {
                        Console.WriteLine("删除索引成功!");
                    }
                    else
                    {
                        Console.WriteLine($"删除索引失败!
     {result.ServerError}");
                    }
                }
            }
    View Code
    //删除指定索引所在节点下的所有索引
    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($"添加数据返回的结果: 
     { JsonConvert.SerializeObject(response)}");
    
                //批量添加/更新文档
                //var list = new List<Student>();
                //client.IndexMany<Student>(list);
            }
    View Code

    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索引的数据:
     {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));
            }
    View Code
  • 相关阅读:
    Luogu P3731 [HAOI2017]新型城市化
    Luogu P3227 [HNOI2013]切糕 最小割
    Luogu P1654 OSU!
    CF235B Let's Play Osu! 期望dp
    Luogu P2057 [SHOI2007]善意的投票
    任意模数NTT学习笔记
    Burnside引理的感性证明
    JLOI2015 城池攻占
    BZOJ2957 楼房重建
    NOI2009 区间
  • 原文地址:https://www.cnblogs.com/peterYong/p/11041642.html
Copyright © 2020-2023  润新知