3

I'm using the java-sdk for CRUD operation in cosmosdb, I was able to do basic insert of a employee DTO and all looks good. But now I want to do batch insert and could not able to find appropriate api for this.

I come across the cosmosdb documentation where they are recommend using stored procedure(server side JS) but I prefer a direct java driver option like other nosql provides are giving.

Is there anything I'm missing and which one will be preferable, the stored procedure or the java driver option(if exist)? Below is the code snippet I'm using for inserting single document.

documentClient.createDocument(getCollection().getSelfLink(), document, null, false).getResource();
lambodar
  • 3,495
  • 5
  • 34
  • 58

1 Answers1

4

On the client side, you may do single writes to your collection, just like you're currently doing. There is no client side batch insert API call. There is now also transaction support built into the Java (and .NET) SDK (which wasn't available when the question was originally asked, 6 years ago). The basic flow for SDK-based batch operations:

  • create a transaction, based on partition key value (transactions still take place within a partition)
  • specify write operations
  • execute batch

So... something like...

CosmosBatch batchSample = CosmosBatch.createCosmosBatch(new PartitionKey("someKeyValue"));
batchSample.createItemOperation(someItem)
batchSample.createItemOperation(anotherItem)
CosmosBatchResponse response = container.executeCosmosBatch(batchSample);

With a stored procedure, you would be able to pass any payload you wanted to the stored proc,and then you could transactionally insert multiple documents to a collection (or a partition if using a partitioned collection). With a single client side call to that stored procedure.

So, using a stored procedure, you're still able to do a single client side call, effectively accomplishing what you're specifically looking for. You'll just need to set up your payload appropriately so that your stored procedure code can separate each individual document to be inserted.

David Makogon
  • 69,407
  • 21
  • 141
  • 189