nuget引用NESThtml
源碼可查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