建立索引CreateIndex

nuget引用NESThtml

new一个客户端

源码可查ElasticClient.csgit

new一个ElasticClient有多种方式github

第一种

ES地址是http://localhost:9200,能够直接new,以下所示api

var client = new ElasticClient();

源码中显示 new ElasticClient()安全

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

第二种

由此能够推断一下,若是本地安装的使用不是9200端口或者远程链接ES服务端,能够这么写app

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的运行机制,留个疑问。elasticsearch

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官方文档ide

建立索引

判断索引是否存在ui

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

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

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

//基本配置
                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

相关文章
相关标签/搜索