我Java DocumentDb bulk-executor
用来将json数组批量导入到中Azure Cosmos DB
。
样品JSON
:
[
{
"SId": "101",
"SName": "ABC"
},
{
"SId": "102",
"SName": "XYZ"
}
]
样例代码:
(PARTTION_KEY =“ \ SId”)
DocumentCollection collection = Utilities.createEmptyCollectionIfNotExists(client, DATABASE, CONTAINER, PARTITION_KEY, THROUGHPUT);
ArrayList<String> list = new ArrayList<String>();
JSONParser jsonParser = new JSONParser();
FileReader reader = new FileReader("C:\\samplejson.json");
Object obj = jsonParser.parse(reader);
JSONArray jsonArray = (JSONArray) obj;
if (jsonArray != null) {
int len = jsonArray.size();
for (int i=0;i<len;i++){
list.add(jsonArray.get(i).toString());
}
}
client.getConnectionPolicy().getRetryOptions().setMaxRetryWaitTimeInSeconds(30);
client.getConnectionPolicy().getRetryOptions().setMaxRetryAttemptsOnThrottledRequests(9);
DocumentBulkExecutor.Builder bulkExecutorBuilder = DocumentBulkExecutor.builder().from(client, DATABASE, CONTAINER,
collection.getPartitionKey(), 20000);
DocumentBulkExecutor bulkExecutor = bulkExecutorBuilder.build();
client.getConnectionPolicy().getRetryOptions().setMaxRetryWaitTimeInSeconds(0);
client.getConnectionPolicy().getRetryOptions().setMaxRetryAttemptsOnThrottledRequests(0);
BulkImportResponse bulkImportResponse = bulkExecutor.importAll(list, false, false, null);
System.out.println(bulkImportResponse.getNumberOfDocumentsImported());
现在,如果我有另一个JSON:
[
{
"SId": "101, // Item with this SID has already been inserted
"SName": "ABCDEF"
},
{
"SId": "103",
"SName": "PQR"
}
]
我想将此JSON插入同一容器。但是它只是存储为一个新条目,并带有一个由Cosmos DB自动创建的不同“ id”。
如何根据“ SId”(如果已存在)同时批量导入和覆盖项目(如果已存在)?
请帮忙!
您需要在对importAll的调用中将isUpsert标志更改为true。这将启用Upsert操作,这意味着如果该ID不存在,它将添加一个新文档,或者如果该ID已经存在,它将更新一个现有文档。
换线:
BulkImportResponse bulkImportResponse = bulkExecutor.importAll(list, false, false, null);
至
BulkImportResponse bulkImportResponse = bulkExecutor.importAll(list, true, false, null);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句