【问题标题】:Proper Implementation of Hashed Shard Key In MongoDB在 MongoDB 中正确实现散列分片键
【发布时间】:2013-03-18 22:10:07
【问题描述】:

我有一个当前由内置“_id”(ObjectId)索引/查询的集合。我不想在这个键上分片,因为它是顺序的(以日期为前缀)。 Mongo 2.4 的文档说我可以对这个键的哈希进行分片,这听起来很棒。像这样:

sh.shardCollection("records.active", { _id: "hashed" })

问题:我是否必须首先在活动集合上创建散列索引:

db.active.ensureIndex({ _id: "hashed" })

或者这不是必需的吗?我不想在不必要的索引上浪费空间。

相关问题:如果我确实使用 ensureIndex({ _id: "hashed"}) 创建了一个散列索引,我可以删除默认的“id”索引吗? Mongo 会知道对 _id 字段进行查询,对它们进行哈希处理并针对哈希索引运行它们吗?

谢谢...

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    _id 索引和 散列 _id 索引都需要。在 MongoDB 2.4 中,您不必在对集合进行分片之前显式调用 db.active.ensureIndex({ _id: "hashed" }),但如果你不这样做 sh.shardCollection( "records.active", { _id: "hashed" }) 将为您创建哈希索引。

    _id 索引是复制所必需的。

    要在 MongoDB 中对集合进行分片,您必须在分片键上有一个索引。这在 MongoDB 2.4 中没有改变,并且分片需要 hashed _id 索引才能工作。

    【讨论】:

      【解决方案2】:

      我自己尝试过,使用 mongoDB 2.4.11。

      我创建文档并将其插入到新集合中。查询被触发到 mongos 服务器。我插入的所有 1,000,000 个文档都作为分片集群主分片 A 进入(您可以使用 sh.status() 检查它)。

      但是,当我尝试按照以下命令执行分片收集时,

      sh.shardCollection("database.collection",{_id:"hashed"})
      

      显示错误如下

      {
          "proposedKey" : {
              "_id" : "hashed"
          },
          "curIndexes" : [
              {
                  "v" : 1,
                  "name" : "_id_",
                  "key" : {
                      "_id" : 1
                  },
                  "ns" : "database.collection"
              }
          ],
          "ok" : 0,
          "errmsg" : "please create an index that starts with the shard key before sharding."
      }
      

      所以答案是

      1. 是的,它需要散列索引
      2. 您必须事先创建它,MongoDB 要求您使用以下命令手动创建它:

        db.collection.ensureIndex({ _id: "hashed" })

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-15
        • 1970-01-01
        • 2018-06-26
        • 2014-09-08
        • 2016-02-27
        • 1970-01-01
        相关资源
        最近更新 更多