創建索引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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM