Java Azure Cosmos DB (SQL API) データの参照方法 No.15

自己投資としてチャレンジしている内容を Blog で公開しています。

今回は Java で Azure Cosmos DB (SQL API) で データを参照 する方法について紹介します。
(In English Java -Retrieve data on Azure Cosmos DB (SQL API) No.15)

▼1. Azure Cosmos DB (SQL API) でデータを参照する

Azure Cosmos DB (SQL API) でも JSON に対して SQL クエリが実行できます。
今回は com.azure.cosmos.util の CosmosPagedIterable<T> のクラスを利用して stream() や iterableByPage() を使ってデータを参照する Java のコードを紹介します。


▼2. 事前準備

2-1. トライアルの Cosmos DB アカウントの作成

以下のサイトから無料で利用できる Azure Cosmos DB を用意します。Azure を利用するために必要な Subscription を用意する必要もありません。
https://azure.microsoft.com/ja-jp/try/cosmosdb/

2-2. Maven auto-import を IntelliJ IDEA で有効

ubuntu で IntelliJ IDEA をインストールしています。詳細はこちらの blog を参照ください。

IntelliJ IDEA の利用 auto-import を有効にする方法 No.13

2-3. データを作成

詳細はこちらの blog を参照ください。

Java Azure Cosmos DB (SQL API) Database の作成方法 No.14


▼3. Cosmos DB (SQL API) に既に存在するデータを参照するコードを作成

3-1. Java コードの作成

Azure Cosmos DB に接続しデータを参照します。
end_point  の xxx と、master_key の xxx は、それぞれ利用する Cosmos DB のアカウント名とキーに書き換えます。

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://YourCosmosDBAccountName.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. 実行結果

[main] INFO com.azure.cosmos.implementation.RxDocumentClientImpl - Initializing DocumentClient with serviceEndpoint [https://YourCosmosDBAccountName.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://YourCosmosDBAccountName.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. 参考情報

以上です。参考になりましたら幸いです。


コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です