Java -Retrieve data on Azure Cosmos DB (SQL API) No.15

In this blog, how to retrieve data on Azure Cosmos DB is shown.

▼1. Retrieve Data on Azure Cosmos DB (SQL API) 

Using steam() and iterableByPage() in CosmosPagedIterable<T> class of com.azure.cosmos.util library, We can retrieve data on Cosmos DB.


▼2. Prerequisites

2-1. Free trial Cosmos DB account is available without subscription.

https://azure.microsoft.com/ja-jp/try/cosmosdb/

2-2. Enabling Maven auto-import in IntelliJ IDEA on Ubuntu

Enable auto-import on IntelliJ IDEA No.13

2-3. Creating sample data

Java – Create Database on Azure Cosmos DB (SQL API) Database No.14


▼3. Java code to retrieve data on Cosmos DB (SQL API)

3-1. Creating Java code to find item

Update the following parameters according to the setting on your environment

  • end_point: your Cosmos DB account name
  • master_key: your Account key
  • databaseName: your database name
  • containerName: your container name
import com.azure.cosmos.*;
import com.azure.cosmos.models.CosmosQueryRequestOptions;
import com.azure.cosmos.util.CosmosPagedIterable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.stream.Collectors;

public class ReadCosmosDBv4 {
    protected static final Logger log = LoggerFactory.getLogger(ReadCosmosDBv4.class);

    public static class Family{
        public String id;
        public String lastName;
        public boolean isRegistered;
        public String getId(){
            return id;
        }
        public String getLastName(){
            return lastName;
        }
        public Family(){
        }
    }

    public static void main(String... args) {
        String databaseName = "testdb";
        String end_point = "https://xxxx.documents.azure.com:443";
        String master_key = "xxxx";
        String containerName = "colltest";

        try (CosmosClient cosmosClient = new CosmosClientBuilder().endpoint(end_point).key(master_key).gatewayMode(GatewayConnectionConfig.getDefaultConfig()).consistencyLevel(ConsistencyLevel.SESSION).connectionSharingAcrossClientsEnabled(true).contentResponseOnWriteEnabled(true).userAgentSuffix("My-Application-clienttest").preferredRegions(Collections.singletonList("West US")).buildClient()){
            log.info("The connection to Cosmos DB succeeded.");
            log.info("Set Databse");
            CosmosDatabase database = cosmosClient.getDatabase(databaseName);
            log.info("Set Container");
            CosmosContainer container = database.getContainer(containerName);
            log.info("Set some common query options");
            CosmosQueryRequestOptions queryOptions = new CosmosQueryRequestOptions();
            CosmosPagedIterable<Family> familiesPagedIterable = container.queryItems("select * from c",queryOptions,Family.class);
            log.info("Read data");
            // familiesPagedIterable.stream().forEach(family -> log.info("Record: {},{}",family.getId(),family.getLastName()));
            familiesPagedIterable.stream().forEach(family -> System.out.println("Record: " + family.getId() + " "  + family.getLastName()));
            System.out.println("===========================");            familiesPagedIterable.iterableByPage(10).forEach(cosmosItemPropertiesFeedResponse ->            {System.out.println("Got results " + cosmosItemPropertiesFeedResponse.getResults().size() + " items(s)"
                    + " | Item Ids " + cosmosItemPropertiesFeedResponse.getResults().stream().map(Family::getId).collect(Collectors.toList())
                    + " | request charge of " + cosmosItemPropertiesFeedResponse.getRequestCharge()
                    + " | request ActivityId " + cosmosItemPropertiesFeedResponse.getActivityId());
            System.out.println("===========================");
            });
        }catch(CosmosException e){
            e.printStackTrace();
            System.err.println(String.format("Read Item failed with %s",e));
        }
    }
}

3-2. The result of executing the query

[main] INFO com.azure.cosmos.implementation.RxDocumentClientImpl - Initializing DocumentClient with serviceEndpoint [https://xxxx.documents.azure.com:443], connectionPolicy [ConnectionPolicy{requestTimeout=PT5S, connectionMode=GATEWAY, maxConnectionPoolSize=1000, idleConnectionTimeout=PT1M, userAgentSuffix='My-Application-clienttest', throttlingRetryOptions=RetryOptions{maxRetryAttemptsOnThrottledRequests=9, maxRetryWaitTime=PT30S}, endpointDiscoveryEnabled=true, preferredRegions=[West US], multipleWriteRegionsEnabled=true, proxyType=null, inetSocketProxyAddress=null, readRequestsFallbackEnabled=true, connectTimeout=null, idleEndpointTimeout=null, maxConnectionsPerEndpoint=0, maxRequestsPerConnection=0}], consistencyLevel [Session], directModeProtocol [Tcp]
[main] INFO com.azure.cosmos.implementation.http.SharedGatewayHttpClient - creating a new shared HttpClient
[parallel-1] INFO com.azure.cosmos.implementation.RxDocumentClientImpl - Getting database account endpoint from https://xxxx.documents.azure.com:443
[main] INFO ReadCosmosDBv4 - The connection to Cosmos DB succeeded.
[main] INFO ReadCosmosDBv4 - Set Databse
[main] INFO ReadCosmosDBv4 - Set Container
[main] INFO ReadCosmosDBv4 - Set some common query options
[main] INFO ReadCosmosDBv4 - Set query metrics enabled to get metrics around query executions
[main] INFO ReadCosmosDBv4 - Read data
[reactor-http-epoll-2] INFO com.azure.cosmos.implementation.SessionContainer - Registering a new collection resourceId [xxxx] in SessionTokens
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by com.fasterxml.jackson.module.afterburner.util.MyClassLoader (file:xxxx) to method java.lang.ClassLoader.findLoadedClass(java.lang.String)
WARNING: Please consider reporting this to the maintainers of com.fasterxml.jackson.module.afterburner.util.MyClassLoader
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
Record: 1 Travase
Record: 2 Sara
Record: 3 Ken
===========================
Got results 3 items(s) | Item Ids [1, 2, 3] | request charge of 2.31 | request ActivityId xxxx
===========================
[main] INFO com.azure.cosmos.implementation.RxDocumentClientImpl - Shutting down ...
[main] INFO com.azure.cosmos.implementation.RxDocumentClientImpl - Closing Global Endpoint Manager ...
[main] INFO com.azure.cosmos.implementation.RxDocumentClientImpl - Closing StoreClientFactory ...
[main] INFO com.azure.cosmos.implementation.RxDocumentClientImpl - Shutting down reactorHttpClient ...
[main] INFO com.azure.cosmos.implementation.http.SharedGatewayHttpClient - closing one reference to the shared HttpClient, the number of remaining references is 0
[main] INFO com.azure.cosmos.implementation.http.SharedGatewayHttpClient - All references to shared HttpClient are closed. Closing the underlying HttpClient
[main] INFO com.azure.cosmos.implementation.RxDocumentClientImpl - Shutting down completed.

▼4. Reference


That’s all. Have a nice day ahead !!!

Leave a Reply

Your email address will not be published. Required fields are marked *