關注我,能夠獲取最新知識、經典面試題以及微服務技術分享面試
在使用MongoDB時,在建立索引會涉及到在複製集(replication)以及分片(Shard)中建立,爲了最大限度地減小構建索引的影響,在副本和分片中建立索引,使用滾動索引構建過程。若是不使用滾動索引構建過程:shell
那麼該如何建立呢?具體步驟呢?請看接下來的具體過程。**數據庫
必須在索引構建期間中止對集合的全部寫入,不然可能會在副本集成員中得到不一致的數據。緩存
在副本集中以滾動方式構建惟一索引包括如下過程:服務器
例如:微服務
//修改配置 net: bindIp: localhost,<hostname(s)|ip address(es)> port: 27217 #port: 27017 #replication: #replSetName: myRepl setParameter: disableLogicalSessionCacheRefresh: true //從新啓動 mongod --config <path/To/ConfigFile>
從新開啓Replica Set 模式:索引構建完成後,關閉mongod實例。撤消做爲獨立啓動時所作的配置更改,以返回其原始配置並做爲副本集的成員從新啓動。學習
//回退原來的配置:net: bindIp: localhost,<hostname(s)|ip address(es)> port: 27017 replication: replSetName: myRepl //從新啓動: mongod --config <path/To/ConfigFile>
主節點建立索引,當全部從節點都有新索引時,下降主節點,使用上述過程做爲單機模式從新啓動它,並在原主節點上構建索引:spa
建立惟一索引,必須在索引構建期間中止對集合的全部寫入。 不然,您可能會在副本集成員中得到不一致的數據。若是沒法中止對集合的全部寫入,請不要使用如下過程來建立惟一索引。.net
1.中止Balancer:將mongo shell鏈接到分片羣集中的mongos實例,而後運行sh.stopBalancer()以禁用Balancer。若是正在進行遷移,系統將在中止平衡器以前完成正在進行的遷移。code
2.肯定Collection的分佈:刷新該mongos的緩存路由表,以免返回該Collection舊的分發信息。刷新後,對要構建索引的集合運行db.collection.getShardDistribution()。
例如:在test數據庫中的records字段中建立上升排序的索引
db.adminCommand( { flushRouterConfig: "test.records" } ); db.records.getShardDistribution();
例如,考慮一個帶有3個分片shardA,shardB和shardC的分片集羣,db.collection.getShardDistribution()返回如下內容
Shard shardA at shardA/s1-mongo1.example.net:27018,s1-mongo2.example.net:27018,s1-mongo3.example.net:27018 data : 1KiB docs : 50 chunks : 1 estimated data per chunk : 1KiB estimated docs per chunk : 50 Shard shardC at shardC/s3-mongo1.example.net:27018,s3-mongo2.example.net:27018,s3-mongo3.example.net:27018 data : 1KiB docs : 50 chunks : 1 estimated data per chunk : 1KiB estimated docs per chunk : 50 Totals data : 3KiB docs : 100 chunks : 2 Shard shardA contains 50% data, 50% docs in cluster, avg obj size on shard : 40B Shard shardC contains 50% data, 50% docs in cluster, avg obj size on shard : 40B 從輸出中,您只在shardA和shardC上爲test.records構建索引。
3.在包含集合Chunks的分片建立索引
C1.中止從節點,並以單機模式從新啓動:對於受影響的分片,中止從節點與其中一個分區相關聯的mongod進程,進行配置文件/命令模式更新後從新啓動。
配置文件:
在setParameter部分中將參數disableLogicalSessionCacheRefresh設置爲true。
net: bindIp: localhost,<hostname(s)|ip address(es)> port: 27218 # port: 27018 #replication: # replSetName: shardA #sharding: # clusterRole: shardsvr setParameter: skipShardingConfigurationChecks: true disableLogicalSessionCacheRefresh: true //重啓: mongod --config <path/To/ConfigFile>
C2.建立索引:直接鏈接到在新端口上做爲獨立運行的mongod實例,併爲此實例建立新索引。
//例如:在record Collection的username建立索引 db.records.createIndex( { username: 1 } )
C3.恢復C1的配置,並做爲 Replica Set成員啓動:索引構建完成後,關閉mongod實例。 撤消做爲單機模式時所作的配置更改,以返回其原始配置並從新啓動。
配置文件模式:
在setParameter部分中刪除參數disableLogicalSessionCacheRefresh。
net: bindIp: localhost,<hostname(s)|ip address(es)> port: 27018 replication: replSetName: shardA sharding: clusterRole: shardsvr 重啓:mongod --config <path/To/ConfigFile>
4.在其餘受影響的分片重複C步驟;
5.重啓Balancer,一旦所有分片建立完索引,重啓Balancer:sh.startBalancer()。
後續還有關於實踐中複製集以及分片的搭建過程,複製集成員節點增長刪除等一系列實戰操做。
最後可關注公衆號,一塊兒學習,天天會分享乾貨,還有學習視頻領取!