【问题标题】:Insert document in Cosmos DB using PowerShell (SQL API)使用 PowerShell (SQL API) 在 Cosmos DB 中插入文档
【发布时间】:2019-01-23 07:54:50
【问题描述】:

当我尝试在具有分区键的 Cosmos DB 集合中插入数据时出现错误。

没有分区键,它工作正常

$resourceGroupName = "myrg"
$cosmosDbAccountName = "mydb"
$databaseName = "test"

$cosmosDbContext = New-CosmosDbContext -Account $cosmosDbAccountName -        
Database $databaseName -ResourceGroup $resourceGroupName    

New-CosmosDbCollection -Context $cosmosDbContext -Id 'events' -OfferThroughput 1000 -PartitionKey 'RuleType' -DefaultTimeToLive 604800

$document = @"
{
        "id": "$([Guid]::NewGuid().ToString())",
        "createTime": "2018-05-21T22:59:59.999Z",
        "RuleType": "FTOD"
    }

"@
New-CosmosDbDocument -Context $cosmosDbContext -CollectionId 'events' - 
DocumentBody $document  -PartitionKey 'RuleType'

“RuleType”:这是我的分区键

Invoke-WebRequest :远程服务器返回错误:(400) Bad Request。 在 C:\Program Files\WindowsPowerShell\Modules\CosmosDB\2.1.4.536\lib\utils.ps1:554 char:30 + ... estResult = Invoke-WebRequest -UseBasicParsing @invokeWebRequestParam ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~ + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

有人知道吗?

【问题讨论】:

  • 我真的建议您将错误消息添加为文本,而不是图像。它使阅读、复制、评估、搜索等变得更容易
  • 为什么将$document 实例化为字符串?你可以使用ConvertTo-Json。它可以帮助您确保您的 json 是有效的。
  • 好建议!没有任何具体原因。

标签: powershell azure-cosmosdb


【解决方案1】:

我在我这边复制了你的问题。

基于Get-Help New-CosmosDbDocument 命令显示的参数列表:

需要添加partitionkey才能成功插入文档。

$resourceGroupName = "***"
$cosmosDbAccountName = "***"
$databaseName = "db"

$cosmosDbContext = New-CosmosDbContext -Account $cosmosDbAccountName -Database $databaseName -ResourceGroup $resourceGroupName    

$document = @"
{
        "id": "6fa9b3d5-ce1a-4b38-9068-9d17de5b1c69",
        "createTime": "2018-05-21T22:59:59.999Z",
        "RuleType": "FTOD"           
    }

"@
$partitionkey = "FTOD"
New-CosmosDbDocument -Context $cosmosDbContext -CollectionId 'part' -DocumentBody $document -PartitionKey $partitionkey

希望对你有帮助。

【讨论】:

  • 你能插入数据吗??我已经尝试过了(我用完整的命令更新了我的问题)但仍然收到 400 错误。
  • 为什么你使用 $partitionkey = "A" If partitionKey 属性名称是 RuleType??
  • 是的,我插入数据成功。在您的情况下,请使用 $partitionkey = "FTOD"
猜你喜欢
  • 2022-07-22
  • 2018-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-13
  • 2018-12-17
  • 2020-06-03
  • 1970-01-01
相关资源
最近更新 更多