【问题标题】:Programmatically enable sharding + choosing shard key on a collection using casbah with Mongo 2.4使用 casbah 和 Mongo 2.4 以编程方式启用分片 + 在集合上选择分片键
【发布时间】:2013-06-10 03:01:33
【问题描述】:

我正在尝试以编程方式“启用分片”并使用 java/scala API 特别是 casbah 设置“分片键”

我们的配置

scala 2.10
casbah 2.6 - "org.mongodb" % "casbah_2.10" % "2.6.0",
MongoDB 2.4.4

还有什么是 mongo 2.4.4(带有 scala 2.10)的 casbah 驱动程序版本

我们的用例是这样的,集合 + 索引是使用 casbah scala API dbConnection.getCollection(....)collection.ensureIndex(DBObject("orgId" -> 1), DBObject("background" -> true, "name" -> "org_idx", "unique" -> false)) 以编程方式创建的

是否有等效的 casbah API 以编程方式启用分片并选择 shardKey 以及我们目前正在对 mongo 集群进行分片以进行横向扩展。 我们的数据库 + 集合名称提前未知,并且使用 API 动态创建,因此使用 mongo shell 启用分片根本不是一种选择。

有没有更好的方法来做到这一点?有什么建议吗?

【问题讨论】:

  • 因为您正在动态创建数据库,它们将围绕分片循环 - 为什么需要对任何集合进行分片?通过将不同的数据库放在不同的分片上来平衡负载还不够吗?
  • 如果没有 enableShard 命令或在集合上选择分片键,如何对数据库进行分片?必须发出某些管理命令才能做到这一点
  • 当您对集群进行分片并添加一个新数据库时,它将自动放置在一个新的(er)分片上。数据库不会被分区,但它们都将继续放置在下一个分片上。唯一需要 enableShard 和 shardCollection 的时候是您想要对集合进行分区 - 我不明白为什么您需要对以编程方式生成的所有这些集合进行分区。
  • 感谢您的洞察力,Asya .. 我会试一试...

标签: mongodb scala casbah


【解决方案1】:

以下是对我有用的方法,以@Ross 的回答为基础,但对我来说不太奏效:

import com.mongodb.casbah.Imports._

// Connect to MongoDB
val conn = MongoClient()
val adminDB = conn("admin")

// Enable sharding on the DB
adminDB.command(MongoDBObject("enableSharding" -> <database>))

// Create the index for our shard key
val shardKey = MongoDBObject("_id" -> "hashed")
conn(<database>)(<collection>).ensureIndex(shardKey)

// Enable sharding on the collection
adminDB.command(MongoDBObject("shardCollection" -> "<database>.<collection>", 
    "key" -> shardkey))

【讨论】:

    【解决方案2】:

    为了完整性和帮助他人 - enableSharding 是一个命令(请参阅 enableSharding docs),您可以使用 db.command 从 casbah 运行任何命令。

    import com.mongodb.casbah.Imports._
    
    // Connect to MongoDB
    val conn = MongoClient()
    val adminDB = conn("admin")
    
    
    // Enable sharding
    adminDB.command(MongoDBObject("shardCollection" -> "<database>.<collection>", "key" -> <shardkey>))
    

    该部分应该是一个 MongoDBObject 定义分片键。

    正如 Asya 所提到的,这可能不是您的用例的正确解决方案,但使用 casbah 肯定可以务实地做。

    【讨论】:

      猜你喜欢
      • 2017-03-10
      • 1970-01-01
      • 1970-01-01
      • 2016-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-31
      • 2013-11-09
      相关资源
      最近更新 更多