Exception in thread "main" java.lang.UnsupportedOperationException: PartitionKey value must be supplied for this operation.

現象

Cosmos DB にて Java SDK を使ってドキュメントの削除をしようとすると以下の例外が発生する。

Exception in thread "main" java.lang.UnsupportedOperationException: PartitionKey value must be supplied for this operation.

at com.microsoft.azure.documentdb.DocumentClient.addPartitionKeyInformation(DocumentClient.java:3353)

at com.microsoft.azure.documentdb.DocumentClient.deleteDocument(DocumentClient.java:1047)

原因

RequestOptions にPartitionKeyを指定していないため。

PartitionKeyとは?

The Partition Key is used to automatically partition data among multiple servers for scalability. Choose a JSON property name that has a wide range of values and is likely to have evenly distributed access patterns.

パーティション キーは、スケーラビリティのために複数のサーバー間でデータを自動的にパーティション分割するために使用されます。幅広い値を持ち、アクセス パターンが均等に分散している可能性が高い JSON プロパティ名を選択します。

PartitionKeyを指定する方法

PartitionKeyを確認する

管理コンソールから「Data Explorer」「コンテナ名」「Scale&Settings」を選択するとPartition Keyを確認できる。(パーティションを作成する際に必須で指定する必要がある)

RequestOptions でPartitionKeyの値を指定する

String documentLink = doc.getSelfLink();

RequestOptions options = new RequestOptions();

String partitionKey = ((org.json.JSONObject) doc.get("item")).getString("doc_id");

System.err.println("partitionKey: " + partitionKey);

options.setPartitionKey(new PartitionKey(partitionKey));

client.deleteDocument(documentLink, options);

所感

DocumentのIDを指定しているのにパーティションも指定しないといけないのは腑に落ちないが、どうやらこういう仕組みらしい。