Search in sources :

Example 11 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 readItems.

private void readItems(Flux<Family> familiesToCreate) {
    // Using partition key for point read scenarios.
    // This will help fast look up of items because of partition key
    // <ReadItem>
    final CountDownLatch completionLatch = new CountDownLatch(1);
    familiesToCreate.flatMap(family -> {
        Mono<CosmosItemResponse<Family>> asyncItemResponseMono = container.readItem(family.getId(), new PartitionKey(family.getLastName()), Family.class);
        return asyncItemResponseMono;
    }).subscribe(itemResponse -> {
        double requestCharge = itemResponse.getRequestCharge();
        Duration requestLatency = itemResponse.getDuration();
        logger.info(String.format("Item successfully read with id %s with a charge of %.2f and within duration %s", itemResponse.getItem().getId(), requestCharge, requestLatency));
    }, 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);
    }
// </ReadItem>
}
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) Mono(reactor.core.publisher.Mono) Family(com.azure.cosmos.examples.common.Family) PartitionKey(com.azure.cosmos.models.PartitionKey) Duration(java.time.Duration) CosmosException(com.azure.cosmos.CosmosException) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 12 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 indexManagementDemo.

// </Main>
private void indexManagementDemo() throws Exception {
    logger.info("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST);
    ArrayList<String> preferredRegions = new ArrayList<String>();
    preferredRegions.add("West US");
    // Create async client
    // <CreateAsyncClient>
    client = new CosmosClientBuilder().endpoint(AccountSettings.HOST).key(AccountSettings.MASTER_KEY).preferredRegions(preferredRegions).consistencyLevel(ConsistencyLevel.EVENTUAL).contentResponseOnWriteEnabled(true).buildAsyncClient();
    // </CreateAsyncClient>
    createDatabaseIfNotExists();
    // Here is where index management is performed
    createContainerIfNotExistsWithSpecifiedIndex();
    Family andersenFamilyItem = Families.getAndersenFamilyItem();
    Family wakefieldFamilyItem = Families.getWakefieldFamilyItem();
    Family johnsonFamilyItem = Families.getJohnsonFamilyItem();
    Family smithFamilyItem = Families.getSmithFamilyItem();
    // Setup family items to create
    Flux<Family> familiesToCreate = Flux.just(andersenFamilyItem, wakefieldFamilyItem, johnsonFamilyItem, smithFamilyItem);
    createFamilies(familiesToCreate);
    familiesToCreate = Flux.just(andersenFamilyItem, wakefieldFamilyItem, johnsonFamilyItem, smithFamilyItem);
    logger.info("Reading items.");
    readItems(familiesToCreate);
    logger.info("Querying items.");
    queryItems();
}
Also used : CosmosClientBuilder(com.azure.cosmos.CosmosClientBuilder) ArrayList(java.util.ArrayList) Family(com.azure.cosmos.examples.common.Family)

Example 13 with Family

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

the class SampleIndexManagement method createFamilies.

private void createFamilies(List<Family> families) throws Exception {
    double totalRequestCharge = 0;
    for (Family family : families) {
        // <CreateItem>
        // Create item using container that we created using sync client
        // Use lastName as partitionKey for cosmos item
        // Using appropriate partition key improves the performance of database operations
        CosmosItemRequestOptions cosmosItemRequestOptions = new CosmosItemRequestOptions();
        CosmosItemResponse<Family> item = container.createItem(family, new PartitionKey(family.getLastName()), cosmosItemRequestOptions);
        // </CreateItem>
        // Get request charge and other properties like latency, and diagnostics strings, etc.
        logger.info(String.format("Created item with request charge of %.2f within" + " duration %s", item.getRequestCharge(), item.getDuration()));
        totalRequestCharge += item.getRequestCharge();
    }
    logger.info(String.format("Created %d items with total request " + "charge of %.2f", families.size(), totalRequestCharge));
}
Also used : CosmosItemRequestOptions(com.azure.cosmos.models.CosmosItemRequestOptions) Family(com.azure.cosmos.examples.common.Family) PartitionKey(com.azure.cosmos.models.PartitionKey)

Example 14 with Family

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

the class CosmosDiagnosticsQuickStart method queryDocuments.

private void queryDocuments() throws Exception {
    logger.info("Query documents in the container : {}", containerName);
    String sql = "SELECT * FROM c WHERE c.lastName = 'Witherspoon'";
    CosmosPagedIterable<Family> filteredFamilies = container.queryItems(sql, new CosmosQueryRequestOptions(), Family.class);
    // Add handler to capture diagnostics
    filteredFamilies = filteredFamilies.handle(familyFeedResponse -> {
        logger.info("Query Item diagnostics through handler : {}", familyFeedResponse.getCosmosDiagnostics());
    });
    // Or capture diagnostics through iterableByPage() APIs.
    filteredFamilies.iterableByPage().forEach(familyFeedResponse -> {
        logger.info("Query item diagnostics through iterableByPage : {}", familyFeedResponse.getCosmosDiagnostics());
    });
    logger.info("Done.");
}
Also used : CosmosQueryRequestOptions(com.azure.cosmos.models.CosmosQueryRequestOptions) CosmosContainerProperties(com.azure.cosmos.models.CosmosContainerProperties) Logger(org.slf4j.Logger) CosmosDatabaseRequestOptions(com.azure.cosmos.models.CosmosDatabaseRequestOptions) CosmosDatabase(com.azure.cosmos.CosmosDatabase) CosmosContainerResponse(com.azure.cosmos.models.CosmosContainerResponse) PartitionKey(com.azure.cosmos.models.PartitionKey) LoggerFactory(org.slf4j.LoggerFactory) CosmosQueryRequestOptions(com.azure.cosmos.models.CosmosQueryRequestOptions) UUID(java.util.UUID) CosmosItemResponse(com.azure.cosmos.models.CosmosItemResponse) CosmosClientBuilder(com.azure.cosmos.CosmosClientBuilder) Family(com.azure.cosmos.examples.common.Family) CosmosClient(com.azure.cosmos.CosmosClient) CosmosPagedIterable(com.azure.cosmos.util.CosmosPagedIterable) CosmosContainer(com.azure.cosmos.CosmosContainer) CosmosDatabaseResponse(com.azure.cosmos.models.CosmosDatabaseResponse) ThroughputProperties(com.azure.cosmos.models.ThroughputProperties) ConsistencyLevel(com.azure.cosmos.ConsistencyLevel) CosmosException(com.azure.cosmos.CosmosException) CosmosDiagnostics(com.azure.cosmos.CosmosDiagnostics) AccountSettings(com.azure.cosmos.examples.common.AccountSettings) CosmosItemRequestOptions(com.azure.cosmos.models.CosmosItemRequestOptions) Family(com.azure.cosmos.examples.common.Family)

Example 15 with Family

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

the class CosmosDiagnosticsQuickStart method readDocumentDoesntExist.

// Document read doesn't exist
private void readDocumentDoesntExist() throws Exception {
    logger.info("Read document by ID : bad-ID");
    // Read document by ID
    try {
        CosmosItemResponse<Family> familyCosmosItemResponse = container.readItem("bad-ID", new PartitionKey("bad-lastName"), Family.class);
    } catch (CosmosException cosmosException) {
        CosmosDiagnostics diagnostics = cosmosException.getDiagnostics();
        logger.info("Read item exception diagnostics : {}", diagnostics);
    }
    logger.info("Done.");
}
Also used : Family(com.azure.cosmos.examples.common.Family) PartitionKey(com.azure.cosmos.models.PartitionKey) CosmosException(com.azure.cosmos.CosmosException) CosmosDiagnostics(com.azure.cosmos.CosmosDiagnostics)

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