java - 如何使用 azure-cosmos sdk 在 JAVA java 中获取 JSON 数组形式的 cosmos 响应

标签 java azure azure-cosmosdb azure-cosmosdb-sqlapi

我可以在 azure cosmos-db explore 中运行查询,如下图所示,并将响应视为 json 数组 enter image description here

我想使用 Java 和 azure-cosmos SDK 来执行相同的操作

下面是我的函数

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 实际上应该在方法之外构建,并由调用该方法的所有线程重用。查看示例here用于正确创建异步客户端并通过多种方法进行消费。

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());
}

关于java - 如何使用 azure-cosmos sdk 在 JAVA java 中获取 JSON 数组形式的 cosmos 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68349289/

相关文章:

azure - documentDb 的奇怪结果

java - Autowiring 包中的所有组件,无需实现接口(interface)

azure - 如何将 az 网络公共(public) IP 列表输出导出到 csv?

azure - contentOffset 从哪里来?

azure - 在 Azure DocumentDB 的选择查询中获取重复记录

azure - sdk v3 中的 Azure Cosmos DB 中的请求超时

java - 如果 avro 模式与数据一起存储,为什么 java avro api 需要我提供模式文件?

Java:压缩 JPEG 图像

java - WeakHashMap 和强引用值

visual-studio - 在本地运行 Azure Functions