【问题标题】:Azure Cosmos MongoDB - Create collection with shard keyAzure Cosmos MongoDB - 使用分片键创建集合
【发布时间】:2019-01-20 08:08:51
【问题描述】:

我需要在 Azure 的 Cosmos MongoDB 中创建一个集合,但需要使用分区/分片键,因为所需的配置是数据库将具有预配置的吞吐量(一组 RU),并且其中的集合将具有共享的吞吐量.

集群的 API 设置为 Cosmos DB Mongo API - 如果我在 cosmos 中创建集合,插入/删除没有问题,但如果我使用下面的代码创建集合,我将收到错误消息 {"Command insert failed: document does not contain shard key."} 甚至虽然查看门户中的集合和代码中的集合看起来相同。

client.CreateDocumentCollectionAsync(database.SelfLink,
new DocumentCollection
{
    Id = "CollectionName",
    PartitionKey = new PartitionKeyDefinition { Paths = new Collection<string> { "/_id" } }
}).Wait();

我已与微软代表谈过,但我缺乏“答案”。他建议使用Mongo CSharp Driver,但似乎这个驱动程序无法定义分区键(这是有道理的)。

如何使用分区键创建集合?

谢谢。

【问题讨论】:

    标签: c# azure-cosmosdb azure-cosmosdb-mongoapi


    【解决方案1】:

    我正在处理同样的事情。使用 MongoDB csharp 驱动程序时,不应调用 db.CreateCollection,而应使用 sharding 命令。这将为您创建带有分区键的无限集合。

    //Sharded collection must be initialized this way
    var bson = new BsonDocument
    {
        { "shardCollection", mongoClientProvider.DatabaseName + "." + CollectionName },
        { "key", new BsonDocument(ShardKeyName, "hashed") }
    };
    
    var shellCommand = new BsonDocumentCommand<BsonDocument>(bson);
    
    try
    {
        var commandResult = database.RunCommand(shellCommand);
    }
    catch (MongoCommandException ex)
    {
        logger.LogError(ex, ex.Result.ToString());
    }
    

    【讨论】:

    • 我收到MongoDB.Driver.MongoCommandException: 'Command shardCollection failed: Sharding is not supported for existing collections..'
    【解决方案2】:

    您可以使用customCommand 创建一个带有 ShardKey 的集合。像这样的东西:

    var createCollectionCommand = new BsonDocument
                    {
                        { "customAction", "CreateCollection" },
                        { "collection", "YourCollectionName" },
                        { "shardKey", "YourShardKey" }
                    };
    cosmosDatabase.RunCommand<BsonDocument>(createCollectionCommand);
    

    【讨论】:

      猜你喜欢
      • 2019-08-05
      • 1970-01-01
      • 2021-12-01
      • 1970-01-01
      • 2020-12-22
      • 2020-09-29
      • 2018-11-30
      • 2018-10-12
      • 2017-12-18
      相关资源
      最近更新 更多