抛出异常:"Microsoft.Azure.Cosmos.CosmosException",将JSON批量导入Azure Cosmos DB时出现错误请求 [英] Exception thrown: 'Microsoft.Azure.Cosmos.CosmosException', Bad Request while bulk importing JSON to Azure Cosmos DB

查看:24
本文介绍了抛出异常:"Microsoft.Azure.Cosmos.CosmosException",将JSON批量导入Azure Cosmos DB时出现错误请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图从.Net 4.6.1控制台应用程序将包含JSONs列表的JSON文件批量导入到Azure Cosmos DB.

I'm trying to bulk import a JSON file containing list of JSONs to Azure Cosmos DB from .Net 4.6.1 console application.

我能够成功创建数据库和容器. 但是我在第40行遇到以下错误,并且没有创建项目. 错误:

I'm successfully able to create the database and the container. However I'm getting the following error at Line 40 and the items aren't getting created. Error :

DocDBTrace错误:0:将不会重试该操作.当前尝试0,状态代码:BadRequest引发的异常:Microsoft.Azure.Cosmos.Client.dll中的'Microsoft.Azure.Cosmos.CosmosException'引发的异常:mscorlib.dll中的'System.AggregateException'

DocDBTrace Error: 0 : Operation will NOT be retried. Current attempt 0, Status Code: BadRequest Exception thrown: 'Microsoft.Azure.Cosmos.CosmosException' in Microsoft.Azure.Cosmos.Client.dll Exception thrown: 'System.AggregateException' in mscorlib.dll

示例代码:

class Program
{

private static string EndpointUrl = $"";
private const string AuthorizationKey = "";
private const string DatabaseName = "TestDB";
private const string ContainerName = "BulkImportTest";
public static async Task Main(string[] args)
{
    string json = File.ReadAllText(@"BulkImport.json");

    List<StudentInfo> lists = JsonConvert.DeserializeObject<List<StudentInfo>>(json);

    CosmosClientOptions options = new CosmosClientOptions() { ConnectionMode = ConnectionMode.Gateway, AllowBulkExecution = true };
    CosmosClient cosmosClient = new CosmosClient(EndpointUrl, AuthorizationKey, options);

    try
    {
        Database database = await cosmosClient.CreateDatabaseIfNotExistsAsync(DatabaseName);
        Console.WriteLine(database.Id);
        Container container = await database.CreateContainerIfNotExistsAsync(ContainerName, "/SId");
        Console.WriteLine(container.Id);
        List<Task> tasks = new List<Task>();
        foreach (StudentInfo item in lists)
        {
                tasks.Add(container.CreateItemAsync(item, new PartitionKey(item.SId)));
        }
        await Task.WhenAll(tasks); // Line 40
        }

    catch(Exception ex)
    {
            Console.WriteLine("Exception = " + ex.Message);
    }


    Console.ReadLine();
}
    class StudentInfo
    {
        public string SId { get; set; }
        public string SName { get; set; }
    }}

BulkImport.json:

BulkImport.json :

  [
  {
    "SId": "101",
    "SName": "ABC",
  },
  {
    "SId": "102",
    "SName": "XYZ",
  }
  ]

请对此提供帮助.

进行建议的更新后,我仍然面临类似的问题:

After making the suggested updates I'm still facing similar issue :

DocDBTrace错误:0:将不会重试该操作.当前尝试0,状态代码:BadRequest 引发异常:Microsoft.Azure.Cosmos.Client.dll中的"Microsoft.Azure.Cosmos.CosmosException" 引发异常:mscorlib.dll中的"Microsoft.Azure.Cosmos.CosmosException"

DocDBTrace Error: 0 : Operation will NOT be retried. Current attempt 0, Status Code: BadRequest Exception thrown: 'Microsoft.Azure.Cosmos.CosmosException' in Microsoft.Azure.Cosmos.Client.dll Exception thrown: 'Microsoft.Azure.Cosmos.CosmosException' in mscorlib.dll

推荐答案

根据我的测试,当我们创建新文档时,必须提供"id"属性.有关更多详细信息,请参阅

According to my test, when we create a new document, we must provide "id" property. For more details, please refer to the document.

例如

我的.json文件

 [{
         "SId": "101",
         "SName": "ABC"
     }, {
         "SId": "102",
         "SName": "XYZ"
     }
 ]

我的代码

        async static Task Main(string[] args)
        {
            string json = File.ReadAllText(@"E:\test.json");
            List<StudentInfo> lists = JsonConvert.DeserializeObject<List<StudentInfo>>(json);            
            CosmosClientOptions options = new CosmosClientOptions() { AllowBulkExecution = true, ConnectionMode = ConnectionMode.Gateway };
            CosmosClient cosmosClient = new CosmosClient(EndpointUrl, AuthorizationKey, options);
            Database database = await cosmosClient.CreateDatabaseIfNotExistsAsync(DatabaseName);
            Console.WriteLine(database.Id);
            Container container = await database.CreateContainerIfNotExistsAsync(ContainerName,"/SId");
            Console.WriteLine(container.Id);
            List<Task> tasks = new List<Task>();
            foreach (StudentInfo item in lists)
            {
                item.Id = Guid.NewGuid().ToString();// add the line in your code
                tasks.Add(container.CreateItemAsync(item, new PartitionKey(item.SId))
                    .ContinueWith((Task<ItemResponse<StudentInfo>> task) =>
                    {
                        Console.WriteLine("Status: " + task.Result.StatusCode + "    Resource: " + task.Result.Resource.SId);
                    }));
            }
            await Task.WhenAll(tasks);
            Console.ReadLine();
        }
        class StudentInfo
        {            
            public string SId { get; set; }
            public string SName { get; set; }
            [JsonProperty(PropertyName = "id")]// add the code in your custom object
            public string Id { get; set; }//add the code in your custom object

        }
    }

这篇关于抛出异常:"Microsoft.Azure.Cosmos.CosmosException",将JSON批量导入Azure Cosmos DB时出现错误请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆