Count

JavaSDK から CosmosDB で集計クエリーを利用するのにハマった点があったのでメモします。

クエリーにVALUE句を設定しないと以下のエラーになります。

java.lang.IllegalStateException: com.microsoft.azure.documentdb.DocumentClientException: Message: {"Errors":["Cross partition query only supports 'VALUE <AggreateFunc>' for aggregates."]} Caused by: com.microsoft.azure.documentdb.DocumentClientException: Message: {"Errors":["Cross partition query only supports 'VALUE <AggreateFunc>' for aggregates."]}

また、setEnableCrossPartitionQuery を true にしないと以下のエラーになります。

java.lang.IllegalStateException: com.microsoft.azure.documentdb.DocumentClientException: Cross partition query is required but disabled. Please set x-ms-documentdb-query-enablecrosspartition to true, specify x-ms-documentdb-partitionkey, or revise your query to avoid this exception. Caused by: com.microsoft.azure.documentdb.DocumentClientException: Cross partition query is required but disabled. Please set x-ms-documentdb-query-enablecrosspartition to true, specify x-ms-documentdb-partitionkey, or revise your query to avoid this exception.

以下、Javaのコードです。

// Azure Cosmos DB Libraries for Java // https://docs.microsoft.com/ja-jp/java/api/overview/azure/cosmosdb?view=azure-java-stable String host = "yourhost"; String container_id = "yourcontainer"; String database = "yourdatabase"; // Get key from Azure Web Console // read write key String key = "yourkey"; String endPoint = "https://" + host + ".documents.azure.com:443"; DocumentClient client = new DocumentClient(endPoint, key, // new ConnectionPolicy(), ConsistencyLevel.Session); String collectionLink = String.format("/dbs/%s/colls/%s", database, container_id); String q = String.format("SELECT VALUE count(1) FROM c"); // IF (without 'VALUE' in query)// java.lang.IllegalStateException: com.microsoft.azure.documentdb.DocumentClientException: Message: {"Errors":["Cross partition query only supports 'VALUE <AggreateFunc>' for aggregates."]}// Caused by: com.microsoft.azure.documentdb.DocumentClientException: Message: {"Errors":["Cross partition query only supports 'VALUE <AggreateFunc>' for aggregates."]} FeedOptions feedOptions = new FeedOptions(); feedOptions.setEnableCrossPartitionQuery(true); // IF (EnableCrossPartitionQuery = false)// java.lang.IllegalStateException: com.microsoft.azure.documentdb.DocumentClientException: Cross partition query is required but disabled. Please set x-ms-documentdb-query-enablecrosspartition to true, specify x-ms-documentdb-partitionkey, or revise your query to avoid this exception.// Caused by: com.microsoft.azure.documentdb.DocumentClientException: Cross partition query is required but disabled. Please set x-ms-documentdb-query-enablecrosspartition to true, specify x-ms-documentdb-partitionkey, or revise your query to avoid this exception. try { List<Object> results = client // .queryAggregateValues(collectionLink, q, feedOptions); System.err.println(results.get(0)); } catch (Exception e) { e.printStackTrace(); } finally { client.close(); }

以上です。