Search in sources :

Example 6 with Family

use of com.azure.cosmos.examples.common.Family in project azure-cosmos-java-sql-api-samples by Azure-Samples.

the class DocumentCRUDQuickstart method readDocumentOnlyIfChanged.

private void readDocumentOnlyIfChanged() throws Exception {
    logger.info("Read document " + documentId + " only if it has been changed, utilizing an ETag check.");
    // Read document
    CosmosItemResponse<Family> famResp = container.readItem(documentId, new PartitionKey(documentLastName), Family.class);
    logger.info("Read doc with status code of {}", famResp.getStatusCode());
    // Re-read but with conditional access requirement that ETag has changed.
    // This should fail.
    String etag = famResp.getResponseHeaders().get("etag");
    CosmosItemRequestOptions requestOptions = new CosmosItemRequestOptions();
    requestOptions.setIfNoneMatchETag(etag);
    CosmosItemResponse<Family> failResp = container.readItem(documentId, new PartitionKey(documentLastName), requestOptions, Family.class);
    logger.info("Re-read doc with status code of {} (we anticipate failure due to ETag not having changed.)", failResp.getStatusCode());
    // Replace the doc with a modified version, which will update ETag
    Family family = famResp.getItem();
    family.setRegistered(!family.isRegistered());
    CosmosItemResponse<Family> failedFamResp = container.replaceItem(family, family.getId(), new PartitionKey(family.getLastName()), new CosmosItemRequestOptions());
    logger.info("Modified and replaced the doc (updates ETag.)");
    // Re-read doc again, with conditional acccess requirements.
    // This should succeed since ETag has been updated.
    CosmosItemResponse<Family> succeedResp = container.readItem(documentId, new PartitionKey(documentLastName), requestOptions, Family.class);
    logger.info("Re-read doc with status code of {} (we anticipate success due to ETag modification.)", succeedResp.getStatusCode());
    logger.info("Done.");
}
Also used : CosmosItemRequestOptions(com.azure.cosmos.models.CosmosItemRequestOptions) Family(com.azure.cosmos.examples.common.Family) PartitionKey(com.azure.cosmos.models.PartitionKey)

Example 7 with Family

use of com.azure.cosmos.examples.common.Family in project azure-cosmos-java-sql-api-samples by Azure-Samples.

the class DocumentCRUDQuickstart method replaceDocument.

private void replaceDocument() throws Exception {
    logger.info("Replace document " + documentId);
    // Replace existing document with new modified document
    Family family = new Family();
    family.setLastName(documentLastName);
    family.setId(documentId);
    // Document modification
    family.setDistrict("Columbia");
    CosmosItemResponse<Family> famResp = container.replaceItem(family, family.getId(), new PartitionKey(family.getLastName()), new CosmosItemRequestOptions());
    logger.info("Request charge of replace operation: {} RU", famResp.getRequestCharge());
    logger.info("Done.");
}
Also used : CosmosItemRequestOptions(com.azure.cosmos.models.CosmosItemRequestOptions) Family(com.azure.cosmos.examples.common.Family) PartitionKey(com.azure.cosmos.models.PartitionKey)

Example 8 with Family

use of com.azure.cosmos.examples.common.Family in project azure-cosmos-java-sql-api-samples by Azure-Samples.

the class DocumentCRUDQuickstart method upsertDocument.

private void upsertDocument() throws Exception {
    logger.info("Replace document " + documentId);
    // Replace existing document with new modified document (contingent on modification).
    Family family = new Family();
    family.setLastName(documentLastName);
    family.setId(documentId);
    // Document modification
    family.setDistrict("Columbia");
    CosmosItemResponse<Family> famResp = container.upsertItem(family, new CosmosItemRequestOptions());
    logger.info("Done.");
}
Also used : CosmosItemRequestOptions(com.azure.cosmos.models.CosmosItemRequestOptions) Family(com.azure.cosmos.examples.common.Family)

Example 9 with Family

use of com.azure.cosmos.examples.common.Family in project azure-cosmos-java-sql-api-samples by Azure-Samples.

the class SampleIndexManagementAsync method queryItems.

private void queryItems() {
    // <QueryItems>
    // Set some common query options
    int preferredPageSize = 10;
    CosmosQueryRequestOptions queryOptions = new CosmosQueryRequestOptions();
    // Set populate query metrics to get metrics around query executions
    queryOptions.setQueryMetricsEnabled(true);
    CosmosPagedFlux<Family> pagedFluxResponse = container.queryItems("SELECT * FROM Family WHERE Family.lastName IN ('Andersen', 'Wakefield', 'Johnson')", queryOptions, Family.class);
    final CountDownLatch completionLatch = new CountDownLatch(1);
    pagedFluxResponse.byPage(preferredPageSize).subscribe(fluxResponse -> {
        logger.info("Got a page of query result with " + fluxResponse.getResults().size() + " items(s)" + " and request charge of " + fluxResponse.getRequestCharge());
        logger.info("Item Ids " + fluxResponse.getResults().stream().map(Family::getId).collect(Collectors.toList()));
    }, err -> {
        if (err instanceof CosmosException) {
            // Client-specific errors
            CosmosException cerr = (CosmosException) err;
            cerr.printStackTrace();
            logger.error(String.format("Read Item failed with %s\n", cerr));
        } else {
            // General errors
            err.printStackTrace();
        }
        completionLatch.countDown();
    }, () -> {
        completionLatch.countDown();
    });
    try {
        completionLatch.await();
    } catch (InterruptedException err) {
        throw new AssertionError("Unexpected Interruption", err);
    }
// </QueryItems>
}
Also used : CosmosQueryRequestOptions(com.azure.cosmos.models.CosmosQueryRequestOptions) Family(com.azure.cosmos.examples.common.Family) CosmosException(com.azure.cosmos.CosmosException) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 10 with Family

use of com.azure.cosmos.examples.common.Family in project azure-cosmos-java-sql-api-samples by Azure-Samples.

the class SampleIndexManagementAsync method createFamilies.

private void createFamilies(Flux<Family> families) throws Exception {
    // <CreateItem>
    final CountDownLatch completionLatch = new CountDownLatch(1);
    // Combine multiple item inserts, associated success println's, and a final aggregate stats println into one Reactive stream.
    families.flatMap(family -> {
        return container.createItem(family);
    }).flatMap(itemResponse -> {
        logger.info(String.format("Created item with request charge of %.2f within" + " duration %s", itemResponse.getRequestCharge(), itemResponse.getDuration()));
        logger.info(String.format("Item ID: %s\n", itemResponse.getItem().getId()));
        return Mono.just(itemResponse.getRequestCharge());
    }).reduce(0.0, (charge_n, charge_nplus1) -> charge_n + charge_nplus1).subscribe(charge -> {
        logger.info(String.format("Created items with total request charge of %.2f\n", charge));
    }, err -> {
        if (err instanceof CosmosException) {
            // Client-specific errors
            CosmosException cerr = (CosmosException) err;
            cerr.printStackTrace();
            logger.info(String.format("Read Item failed with %s\n", cerr));
        } else {
            // General errors
            err.printStackTrace();
        }
        completionLatch.countDown();
    }, () -> {
        completionLatch.countDown();
    });
    try {
        completionLatch.await();
    } catch (InterruptedException err) {
        throw new AssertionError("Unexpected Interruption", err);
    }
// </CreateItem>
}
Also used : PartitionKey(com.azure.cosmos.models.PartitionKey) LoggerFactory(org.slf4j.LoggerFactory) CosmosQueryRequestOptions(com.azure.cosmos.models.CosmosQueryRequestOptions) ExcludedPath(com.azure.cosmos.models.ExcludedPath) ArrayList(java.util.ArrayList) Families(com.azure.cosmos.examples.common.Families) Family(com.azure.cosmos.examples.common.Family) CosmosAsyncContainer(com.azure.cosmos.CosmosAsyncContainer) ThroughputProperties(com.azure.cosmos.models.ThroughputProperties) Duration(java.time.Duration) ConsistencyLevel(com.azure.cosmos.ConsistencyLevel) CosmosException(com.azure.cosmos.CosmosException) CosmosContainerProperties(com.azure.cosmos.models.CosmosContainerProperties) IndexingPolicy(com.azure.cosmos.models.IndexingPolicy) Logger(org.slf4j.Logger) IncludedPath(com.azure.cosmos.models.IncludedPath) IndexingMode(com.azure.cosmos.models.IndexingMode) CosmosContainerResponse(com.azure.cosmos.models.CosmosContainerResponse) Mono(reactor.core.publisher.Mono) CosmosItemResponse(com.azure.cosmos.models.CosmosItemResponse) CosmosClientBuilder(com.azure.cosmos.CosmosClientBuilder) Collectors(java.util.stream.Collectors) Flux(reactor.core.publisher.Flux) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) CosmosAsyncClient(com.azure.cosmos.CosmosAsyncClient) CosmosAsyncDatabase(com.azure.cosmos.CosmosAsyncDatabase) CosmosDatabaseResponse(com.azure.cosmos.models.CosmosDatabaseResponse) CosmosPagedFlux(com.azure.cosmos.util.CosmosPagedFlux) AccountSettings(com.azure.cosmos.examples.common.AccountSettings) CosmosException(com.azure.cosmos.CosmosException) CountDownLatch(java.util.concurrent.CountDownLatch)

Aggregations

Family (com.azure.cosmos.examples.common.Family)58 PartitionKey (com.azure.cosmos.models.PartitionKey)37 CosmosItemRequestOptions (com.azure.cosmos.models.CosmosItemRequestOptions)19 CosmosQueryRequestOptions (com.azure.cosmos.models.CosmosQueryRequestOptions)12 CosmosDiagnostics (com.azure.cosmos.CosmosDiagnostics)11 CosmosException (com.azure.cosmos.CosmosException)11 CosmosPatchOperations (com.azure.cosmos.models.CosmosPatchOperations)11 ArrayList (java.util.ArrayList)11 CosmosClientBuilder (com.azure.cosmos.CosmosClientBuilder)10 CosmosItemResponse (com.azure.cosmos.models.CosmosItemResponse)10 CosmosPatchItemRequestOptions (com.azure.cosmos.models.CosmosPatchItemRequestOptions)9 Duration (java.time.Duration)7 ConsistencyLevel (com.azure.cosmos.ConsistencyLevel)6 CosmosAsyncContainer (com.azure.cosmos.CosmosAsyncContainer)6 CosmosContainerProperties (com.azure.cosmos.models.CosmosContainerProperties)6 ThroughputProperties (com.azure.cosmos.models.ThroughputProperties)6 Logger (org.slf4j.Logger)6 LoggerFactory (org.slf4j.LoggerFactory)6 CosmosAsyncClient (com.azure.cosmos.CosmosAsyncClient)5 CosmosAsyncDatabase (com.azure.cosmos.CosmosAsyncDatabase)5