簡體   English   中英

如何使用 azure-cosmos sdk 在 JAVA java 中將 cosmos 響應作為 JSON 數組獲取

[英]How to get cosmos response as a JSON Array in JAVA java using azure-cosmos sdk

我可以在 azure cosmos-db explore 中運行查詢,如下圖所示,並將響應視為 json 數組在此處輸入圖像描述

我想使用帶有 azure-cosmos SDK 的 Java 做同樣的事情

下面是我的功能

public JSONArray getCosmosResponseFromSyncClient(String databaseName, String 
containerName, String sqlQuery) {
try {
cosmosClient = new 
CosmosClientBuilder().endpoint(cosmosURI).key(cosmosPrimaryKey).buildClient();
CosmosDatabase database = cosmosClient.getDatabase(databaseName);
CosmosContainer container = database.getContainer(containerName);

int preferredPageSize = 10;
CosmosQueryRequestOptions queryOptions = new CosmosQueryRequestOptions();
queryOptions.setQueryMetricsEnabled(true);
CosmosPagedIterable < JSONArray > responsePagedIterable = container.queryItems(sqlQuery, 
queryOptions, JSONArray.class);

return cosmosQueryResponseObjectAsAJSONArray;
}finally {
cosmosClient.close();
}
}

假設org.json.JSONArray用於 JSONArray,您可以使用Cosmos DB V4 SDK中的 Async API。 cosmosAsyncClient 確實應該在您的方法之外構建,並由調用該方法的所有線程重新使用。 請參閱此處的示例以正確創建異步客戶端並從多種方法中使用。

cosmosAsyncClient = new CosmosClientBuilder().endpoint(cosmosURI).key(cosmosPrimaryKey).buildAsyncClient();
CosmosAsyncDatabase database = cosmosAsyncClient.getDatabase(databaseName);
CosmosAsyncContainer container = database.getContainer(containerName);

您的方法應如下所示:

public JSONArray getCosmosResponseFromAsyncClient(String sqlQuery) {
    int preferredPageSize = 10;
    CosmosQueryRequestOptions queryOptions = new CosmosQueryRequestOptions();
    queryOptions.setQueryMetricsEnabled(true);
    CosmosPagedFlux<JsonNode> pagedFlux = container.queryItems(sqlQuery, queryOptions,
            JsonNode.class);
    List<JsonNode> cosmosQueryResponseObjectAsAJSONArray = pagedFlux.byPage(preferredPageSize)
            .flatMap(pagedFluxResponse -> {
                return Flux.just(pagedFluxResponse
                        .getResults()
                        .stream()
                        .collect(Collectors.toList()));
            }).onErrorResume((exception) -> {
                logger.error(
                        "Exception. e: {}",
                        exception.getLocalizedMessage(),
                        exception);
                return Mono.empty();
            }).blockLast();
    return new JSONArray(cosmosQueryResponseObjectAsAJSONArray.toString());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM