can't shard collection: Uniqueness can't be maintained unless shard key is a prefix

跟着前一篇搭建MongoDB 3.4分片及副本集集群,接着进行分片,一开始是按照如下方式进行建立唯一索引以及片键(我是先对集合建立唯一索引以及分片索引,再对集合分片)

       // 索引
        DBObject dbObj = new BasicDBObject();
        dbObj.put("notifyTime", 1);
        dbObj.put("uid", 1);

       //建立唯一索引
        DBObject option=new BasicDBObject();
        option.put("unique",true);
        dbCollection.createIndex(dbObj,option);

        // 分片索引
        dbObj = new BasicDBObject();
        dbObj.put("sharedKey", "hashed");
        dbCollection.createIndex(dbObj);

结果建立索引后对该集合进行分片,报错:

can't shard collection 'test_collection' with unique index on { notifyTime: 1, uid: 1 } and proposed shard key { sharedKey: "hashed" }. Uniqueness can't be maintained unless shard key is a prefix

报错的意思是:无法对在字段notifyTimeuid上建立唯一索引的集合使用sharedKey字段作为片键对集合进行分片,除非片键是唯一索引的键的前缀,否则唯一性无法保证。

1)不建立唯一索引,即如下所示:

       // 索引
        DBObject dbObj = new BasicDBObject();
        dbObj.put("notifyTime", 1);
        dbObj.put("uid", 1);

        dbCollection.createIndex(dbObj);

        // 分片索引
        dbObj = new BasicDBObject();
        dbObj.put("sharedKey", "hashed");
        dbCollection.createIndex(dbObj);

2)建立唯一索引,将片键作为唯一索引键的前缀,如下所示:

        // 索引
        DBObject dbObj = new BasicDBObject();
        //sharedKey片键要放在唯一组合键开头,即为prefix
        dbObj.put("sharedKey",1);
        dbObj.put("notifyTime", 1);
        dbObj.put("uid", 1);


        DBObject option=new BasicDBObject();
        option.put("unique",true);
        dbCollection.createIndex(dbObj,option);

        // 分片索引
        dbObj = new BasicDBObject();
        dbObj.put("sharedKey", "hashed");
        dbCollection.createIndex(dbObj);
阅读更多
换一批

没有更多推荐了,返回首页