use of com.azure.cosmos.models.CosmosBatchPatchItemRequestOptions in project azure-cosmos-java-sql-api-samples by Azure-Samples.
the class SamplePatchQuickstart method patchTransactionalBatchAdvanced.
// demonstrates a variety of patch operation in the context of a transactional
// batch - including a conditional predicate
private void patchTransactionalBatchAdvanced() {
logger.info("Executing Multiple Patch operations on multiple documents as part of a Transactional Batch");
String lastName = "testLastName";
// generating two random Family objects. these will be created and then patched
// (within a transaction)
Family family1 = Families.getWakefieldFamilyItem();
Family family2 = Families.getJohnsonFamilyItem();
// setting a fixed last name so that we can use it as a partition key for the
// transactional batch
family1.setLastName(lastName);
family2.setLastName(lastName);
// TransactionalBatch batch = TransactionalBatch.createTransactionalBatch(new
// PartitionKey(lastName));
CosmosBatch batch = CosmosBatch.createCosmosBatch(new PartitionKey(lastName));
batch.createItemOperation(family1);
batch.createItemOperation(family2);
CosmosPatchOperations commonPatchOperation = CosmosPatchOperations.create();
commonPatchOperation.replace("/district", "new_replaced_value");
// replacing 'district' via patch
batch.patchItemOperation(family1.getId(), commonPatchOperation);
batch.patchItemOperation(family2.getId(), commonPatchOperation);
// if registered is false (predicate/condition), vaccinated status has to be
// false as well (defining this via conditional patch operation)
CosmosPatchOperations addVaccinatedStatus = CosmosPatchOperations.create().add("/vaccinated", false);
// TransactionalBatchPatchItemRequestOptions options = new
// TransactionalBatchPatchItemRequestOptions();
CosmosBatchPatchItemRequestOptions options = new CosmosBatchPatchItemRequestOptions();
options.setFilterPredicate("from f where f.registered = false");
batch.patchItemOperation(family2.getId(), addVaccinatedStatus, options);
try {
CosmosBatchResponse response = container.executeCosmosBatch(batch);
for (CosmosBatchOperationResult batchOpResult : response.getResults()) {
if (response.isSuccessStatusCode()) {
logger.info("{} operation for ID {} was successful", batchOpResult.getOperation().getOperationType().name(), batchOpResult.getItem(Family.class).getId());
} else {
logger.info("{} operation failed. Status code: {}", batchOpResult.getOperation().getOperationType().name(), batchOpResult.getStatusCode());
}
}
} catch (Exception e) {
logger.error("failed", e);
}
}
Aggregations