在MongoDB中正确实现哈希分片键

6

我有一个集合,目前是通过内置的 "_id" (ObjectId) 进行索引/查询的。由于它是连续的(以日期为前缀),我不想在这个键上进行分片。Mongo 2.4的文档说我可以对这个键的哈希值进行分片,这听起来很棒。如下所示:

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

问题:我是否必须首先在活动集合上创建哈希索引?使用以下命令:

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

还是不需要?我不想浪费更多的空间来进行额外的索引。

相关问题:如果我确实使用 ensureIndex({ _id: "hashed"}) 创建了一个哈希索引,那么我能否删除默认的 "id" 索引?Mongo会知道对 _id 字段的查询应该哈希并运行它们吗?

谢谢...

2个回答

3
在 MongoDB 中,需要使用 _id 索引和 hashed _id 索引。在 MongoDB 2.4 中,不需要在分片集合之前显式调用 db.active.ensureIndex({ _id: "hashed" }),但如果不这样做,则 sh.shardCollection("records.active", { _id: "hashed" }) 将为您创建散列索引。
复制需要使用 _id 索引。
要在 MongoDB 中对集合进行分片,必须在分片键上拥有索引。这在 MongoDB 2.4 中没有改变,因此需要使用 hashed _id 索引才能实现分片。

1
我尝试过使用mongoDB 2.4.11,创建并插入文档到一个新的集合中。查询被发送到mongos服务器。所有我插入的100万个文档都被分配到作为shard集群主节点的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" } )


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接