创建索引CreateIndex

nuget引用NEST

new一个客户端

源码可查ElasticClient.cs

new一个ElasticClient有多种方式

第一种

ES地址是http://localhost:9200,可以直接new,如下所示

var client = new ElasticClient();

源码中显示 new ElasticClient()

public ElasticClient() : this(new ConnectionSettings(new Uri("http://localhost:9200"))) { }

第二种

由此可以推断一下,如果本地安装的使用不是9200端口或者远程连接ES服务端,可以这么写

string uri = "http://example.com:9200";
var settings = new ConnectionSettings(new Uri(uri)).
            DefaultIndex("people");

var client = new ElasticClient(settings);

第三种

Uri uri = new Uri("http://example.com:9200");
var client = new ElasticClient(uri);

第四种 连接池

这里只举例官方文档中推荐使用的SniffingConnectionPool
SniffingConnectionPool线程安全,开销很小,允许运行时reseeded。不明白reseeded的运行机制,留个疑问。

        public static ElasticClient GetElasticClientByPool()
        {
            var uris = new[]
            {
                new Uri("http://localhost:9200"),
                new Uri("http://localhost:9201"),
                new Uri("http://localhost:9202"),
            };

            var connectionPool = new SniffingConnectionPool(uris);
            var settings = new ConnectionSettings(connectionPool)
                .DefaultIndex("people");

            var client = new ElasticClient(settings);

            return client;
        }

参考:elastic官方文档

创建索引

判断索引是否存在

var existsResponse = _elasticClient.IndexExists(_indexName);
var indexExists = existsResponse.Exists 

indexExists 为true,索引存在;为false,索引不存在。

创建索引并初始化索引配置和结构

                //基本配置
                IIndexState indexState = new IndexState
                {
                    Settings = new IndexSettings
                    {
                        NumberOfReplicas = 1,//副本数
                        NumberOfShards = 6//分片数
                    }
                };

                ICreateIndexResponse response = _elasticClient.CreateIndex(_indexName, p => p
                    .InitializeUsing(indexState)
                    .Mappings(m => m.Map<People>(r => r.AutoMap()))
                );

                if (response.IsValid)
                {
                    Console.WriteLine("索引创建成功");
                }
                else
                {
                    Console.WriteLine("索引创建失败");
                }

注意:索引名称必须为小写,如果含有大写字母,异常信息为"Invalid index name [TEST], must be lowercase"

demo地址:CreateIndex

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值