### Example contents of azure.cosmos.directTcp.defaultOptions.json Source: https://github.com/azure/azure-cosmosdb-java/blob/master/README.md Example JSON configuration for Direct TCP options. All values are optional; invalid values are ignored. This file is loaded from the classpath resource named azure.cosmos.directTcp.defaultOptions.json. ```json { "bufferPageSize": 8192, "connectionTimeout": "PT1M", "idleChannelTimeout": "PT0S", "idleEndpointTimeout": "PT1M10S", "maxBufferCapacity": 8388608, "maxChannelsPerEndpoint": 10, "maxRequestsPerChannel": 30, "receiveHangDetectionTime": "PT1M5S", "requestExpiryInterval": "PT5S", "requestTimeout": "PT1M", "requestTimerResolution": "PT0.5S", "sendHangDetectionTime": "PT10S", "shutdownTimeout": "PT15S" } ``` -------------------------------- ### Sample report output Source: https://github.com/azure/azure-cosmosdb-java/blob/master/benchmark/README.md Example output from the benchmark tool showing successful and unsuccessful operation counts, rates, and latency percentiles. ```text 2/13/19 9:32:39 PM ============================================================= -- Meters ---------------------------------------------------------------------- #Successful Operations count = 89934 mean rate = 1798.56 events/second 1-minute rate = 1718.45 events/second 5-minute rate = 1630.17 events/second 15-minute rate = 1610.01 events/second #Unsuccessful Operations count = 0 mean rate = 0.00 events/second 1-minute rate = 0.00 events/second 5-minute rate = 0.00 events/second 15-minute rate = 0.00 events/second -- Timers ---------------------------------------------------------------------- Latency count = 89938 mean rate = 1798.64 calls/second 1-minute rate = 1718.65 calls/second 5-minute rate = 1630.37 calls/second 15-minute rate = 1610.21 calls/second min = 3.97 milliseconds max = 22.81 milliseconds mean = 5.37 milliseconds stddev = 0.96 milliseconds median = 5.26 milliseconds 75% <= 5.70 milliseconds 95% <= 6.40 milliseconds 98% <= 6.93 milliseconds 99% <= 7.51 milliseconds 99.9% <= 17.37 milliseconds ``` -------------------------------- ### Install OpenSSL and APR on Ubuntu Source: https://github.com/azure/azure-cosmosdb-java/blob/master/README.md Installs OpenSSL and APR libraries required for netty's native SSL support on Ubuntu. Without these, netty falls back to Java's default SSL implementation. ```bash sudo apt-get install openssl sudo apt-get install libapr1 ``` -------------------------------- ### Inspect query metrics Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/response-types.md Enable query metrics with FeedOptions.setPopulateQueryMetrics(true). The example queries documents and prints each partition range ID with its total query execution time from the metrics map. ```java FeedOptions options = new FeedOptions(); options.setPopulateQueryMetrics(true); FeedResponse page = client.queryDocuments(collectionLink, "SELECT * FROM c", options) .toBlocking().single(); page.getQueryMetrics().forEach((partitionRangeId, metrics) -> System.out.println(partitionRangeId + " → " + metrics.getTotalQueryExecutionTime())); ``` -------------------------------- ### Set Direct TCP options via system property azure.cosmos.directTcp.defaultOptionsFile Source: https://github.com/azure/azure-cosmosdb-java/blob/master/README.md Command-line example for loading Direct TCP options from a JSON file specified by the system property azure.cosmos.directTcp.defaultOptionsFile. The file path is provided as an argument. ```bash java -Dazure.cosmos.directTcp.defaultOptionsFile=/path/to/default/options/file -jar Direct 10 0 Query ``` -------------------------------- ### Set Direct TCP options via system property azure.cosmos.directTcp.defaultOptions Source: https://github.com/azure/azure-cosmosdb-java/blob/master/README.md Command-line example for passing Direct TCP options as a JSON string using the system property azure.cosmos.directTcp.defaultOptions. The JSON must be escaped for the shell. Values in error are ignored. ```bash java -Dazure.cosmos.directTcp.defaultOptions={\"idleEndpointTimeout\":\"PT24H\"} -jar target/cosmosdb-sdk-testing-1.0-jar-with-dependencies.jar Direct 10 0 Read ``` -------------------------------- ### Attach a media stream to a document Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/client-server-side.md Creates an attachment with content type 'image/png', updates it with a media stream from a file, and reads it back. The example shows how to use MediaOptions and handle the media content stream. ```java Attachment att = new Attachment(); att.setId("profile-photo"); att.setContentType("image/png"); ResourceResponse created = client .createAttachment(docLink, att, null) .toBlocking().single(); MediaOptions media = new MediaOptions(); media.setContentType("image/png"); media.setSlug("profile-photo.png"); try (InputStream in = new FileInputStream("/tmp/photo.png")) { client.updateMedia(created.getResource().getSelfLink(), in, media).toBlocking().single(); } MediaResponse readBack = client.readMedia(created.getResource().getSelfLink()).toBlocking().single(); // readBack.getMedia() — content stream ``` -------------------------------- ### Read response metadata with quota info Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/response-types.md Use RequestOptions.setPopulateQuotaInfo(true) to enable quota information in the response. The example reads a document and prints request charge, activity ID, and document usage/quota. The resource is then obtained via getResource(). ```java RequestOptions options = new RequestOptions(); options.setPopulateQuotaInfo(true); ResourceResponse rsp = client.readDocument(docLink, options).toBlocking().single(); System.out.println("charge=" + rsp.getRequestCharge() + " activityId=" + rsp.getActivityId() + " documentBytes=" + rsp.getDocumentUsage() + "/" + rsp.getDocumentQuota()); Document doc = rsp.getResource(); ``` -------------------------------- ### Reading an account's consistency policy Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/connection-policy.md Retrieves the DatabaseAccount, gets its ConsistencyPolicy, and prints the default consistency level, staleness prefix, and staleness interval in seconds. ```java DatabaseAccount account = client.getDatabaseAccount().toBlocking().single(); ConsistencyPolicy cp = account.getConsistencyPolicy(); System.out.println(cp.getDefaultConsistencyLevel() + " stalenessPrefix=" + cp.getMaxStalenessPrefix() + " stalenessInterval(s)=" + cp.getMaxStalenessIntervalInSeconds()); ``` -------------------------------- ### Change feed from a point in time with ChangeFeedOptions Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/request-feed-options.md Sets up ChangeFeedOptions to read the change feed starting from 24 hours ago in UTC, with a max item count of 100, and subscribes to the change feed query. ```java import java.time.ZoneId; import java.time.ZonedDateTime; ChangeFeedOptions cf = new ChangeFeedOptions(); cf.setStartDateTime(ZonedDateTime.now(ZoneId.of("UTC")).minusHours(24)); cf.setMaxItemCount(100); client.queryDocumentChangeFeed(collectionLink, cf).subscribe(...); ``` -------------------------------- ### Read an account Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/resource-models.md Reads the database account and prints the maximum media storage usage, default consistency level, and readable locations with their endpoints. Uses toBlocking().single() to get the account synchronously. ```java DatabaseAccount account = client.getDatabaseAccount().toBlocking().single(); System.out.println(account.getMaxMediaStorageUsageInMB()); System.out.println(account.getConsistencyPolicy().getDefaultConsistencyLevel()); for (DatabaseAccountLocation loc : account.getReadableLocations()) { System.out.println(loc.getName() + " → " + loc.getEndpoint()); } ``` -------------------------------- ### ChangeFeedOptions Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/request-feed-options.md Configuration options for change feed requests, including partition key range, start from beginning, and start date/time. ```APIDOC ## ChangeFeedOptions ### Description Configuration options for change feed requests, allowing specification of partition key range, start from beginning, and start date/time. ### Constructors - `ChangeFeedOptions()` - Default constructor. - `ChangeFeedOptions(ChangeFeedOptions options)` - Copy constructor. ### Properties #### partitionKeyRangeId - **Type**: String - **Default**: — - **Description**: Poll only this partition-key range. - **Getter**: `getPartitionKeyRangeId()` - **Setter**: `setPartitionKeyRangeId(String)` #### startFromBeginning - **Type**: boolean - **Default**: `false` - **Description**: Start the feed from collection creation. - **Getter**: `isStartFromBeginning()` - **Setter**: `setStartFromBeginning(boolean)` #### startDateTime - **Type**: `java.time.ZonedDateTime` - **Default**: — - **Description**: Start the feed from a point in time; serialized as `If-Modified-Since` (RFC-1123). Takes precedence over `startFromBeginning`, ignored when `requestContinuation` is set. - **Getter**: `getStartDateTime()` - **Setter**: `setStartDateTime(ZonedDateTime)` ### Inherited Properties (from FeedOptionsBase) - `maxItemCount` - `requestContinuation` - `partitionKey` - `populateQueryMetrics` ``` -------------------------------- ### Build the benchmarking tool Source: https://github.com/azure/azure-cosmosdb-java/blob/master/benchmark/README.md Clones the repository and builds the project with Maven, skipping tests. The resulting package is generated in the target directory. ```bash git clone https://github.com/Azure/azure-cosmosdb-java.git cd azure-cosmosdb-java mvn clean package -DskipTests ``` -------------------------------- ### Build with Maven Source: https://github.com/azure/azure-cosmosdb-java/blob/master/README.md Builds the project from the command line using Maven, skipping tests. ```bash maven clean package -DskipTests ``` -------------------------------- ### Retrieve stored procedure script log Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/response-types.md Enable script logging with RequestOptions.setScriptLoggingEnabled(true) before executing a stored procedure. The example prints the decoded script log using URLDecoder.decode(). ```java RequestOptions opts = new RequestOptions(); opts.setScriptLoggingEnabled(true); StoredProcedureResponse rsp = client.executeStoredProcedure(sprocLink, opts, new Object[]{1}) .toBlocking().single(); System.out.println(URLDecoder.decode(rsp.getScriptLog(), "UTF-8")); ``` -------------------------------- ### ChangeFeedOptions class definition Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/request-feed-options.md Defines the ChangeFeedOptions class with constructors and methods for configuring change feed queries. Includes a copy constructor and methods for partition key range, start-from-beginning, and start date/time. ```java public final class ChangeFeedOptions extends FeedOptionsBase { public ChangeFeedOptions() {} public ChangeFeedOptions(ChangeFeedOptions options) {} // copy constructor ``` -------------------------------- ### Create database and collection with custom indexing and TTL Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/client-database-collection.md Creates a database and a collection with a default TTL of 3600 seconds and a custom indexing policy (Range on String, Hash on Number). Uses AsyncDocumentClient with toBlocking().single() to make synchronous calls. Prints the collection self-link and closes the client. ```java AsyncDocumentClient client = new AsyncDocumentClient.Builder() .withServiceEndpoint(HOST).withMasterKeyOrResourceToken(KEY).build(); Database db = new Database(); db.setId("my-db"); ResourceResponse dbRsp = client.createDatabase(db, null) .toBlocking().single(); DocumentCollection coll = new DocumentCollection(); coll.setId("items"); coll.setDefaultTimeToLive(3600); // seconds; null removes the property coll.setIndexingPolicy(new IndexingPolicy(new Index[] { Index.Range(DataType.String), // default overrides Index.Hash(DataType.Number) })); ResourceResponse collRsp = client .createCollection("dbs/my-db", coll, null) .toBlocking().single(); String collectionLink = collRsp.getResource().getSelfLink(); System.out.println(collectionLink); // dbs//colls/ client.close(); ``` -------------------------------- ### Change feed polling loop Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/client-document-operations.md Polls the change feed in a loop using continuation tokens. Starts from the beginning, sets max item count to 100, and sleeps 1 second when no results are returned. ```java ChangeFeedOptions cf = new ChangeFeedOptions(); cf.setStartFromBeginning(true); cf.setMaxItemCount(100); String continuation = null; for (;;) { cf.setRequestContinuation(continuation); FeedResponse page = client.queryDocumentChangeFeed(collectionLink, cf) .toBlocking().single(); page.getResults().forEach(d -> System.out.println("changed: " + d.getId())); continuation = page.getResponseContinuation(); if (page.getResults().isEmpty()) { Thread.sleep(1000); // poll interval (application choice) } } ``` -------------------------------- ### Cross-partition query tuning with FeedOptions Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/request-feed-options.md Configures FeedOptions for cross-partition queries, setting parallelism, buffered item count, max item count, and query metrics. Then executes a query and prints the per-partition query metrics. ```java FeedOptions options = new FeedOptions(); options.setEnableCrossPartitionQuery(true); options.setMaxDegreeOfParallelism(4); options.setMaxBufferedItemCount(1000); options.setMaxItemCount(500); options.setPopulateQueryMetrics(true); FeedResponse page = client.queryDocuments(collectionLink, "SELECT * FROM c", options) .toBlocking().single(); System.out.println(page.getQueryMetrics()); // per-partition query metrics ``` -------------------------------- ### Create user and permission, then use resource token in scoped client Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/client-users-permissions-offers.md Creates a user 'alice', a read-only permission on a collection, and uses the returned resource token to build a scoped AsyncDocumentClient. The permission's resource partition key is set to 'Seattle'. The scoped client only has access to the governed resource. ```java User user = new User(); user.setId("alice"); ResourceResponse userRsp = client.createUser("dbs/my-db", user, null).toBlocking().single(); Permission permission = new Permission(); permission.setId("alice-read-docs"); permission.setResourceLink("dbs/my-db/colls/items"); // governed resource permission.setPermissionMode(PermissionMode.Read); permission.setResourcePartitionKey(new PartitionKey("Seattle")); ResourceResponse permissionRsp = client .createPermission(userRsp.getResource().getSelfLink(), permission, null) .toBlocking().single(); String resourceToken = permissionRsp.getResource().getToken(); // A second, scoped client using only the resource token: AsyncDocumentClient scoped = new AsyncDocumentClient.Builder() .withServiceEndpoint(HOST) .withMasterKeyOrResourceToken(resourceToken) .build(); ``` -------------------------------- ### Create a hashed collection keyed on /city Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/partitioning.md Sets up a DocumentCollection with a hash partition key definition on the '/city' path, using PartitionKeyDefinitionVersion.V2 for case-insensitive hashing, and creates the collection via client.createCollection. ```java DocumentCollection coll = new DocumentCollection(); coll.setId("byCity"); PartitionKeyDefinition pkd = new PartitionKeyDefinition(); pkd.setKind(PartitionKind.Hash); pkd.setVersion(PartitionKeyDefinitionVersion.V2); // case-insensitive hashing pkd.setPaths(Collections.singletonList("/city")); coll.setPartitionKey(pkd); ResourceResponse rsp = client .createCollection("dbs/my-db", coll, null) .toBlocking().single(); System.out.println(rsp.getResource().getPartitionKey().getPaths()); ``` -------------------------------- ### Get database account and close client Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/async-document-client.md Lifecycle methods: getDatabaseAccount() returns an Observable emitting the DatabaseAccount resource once after subscription; close() closes the client's session container and releases transport resources. ```java Observable getDatabaseAccount(); // Line 1525 void close(); // Line 1530 ``` -------------------------------- ### Enumerate partition key ranges for manual fan-out Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/partitioning.md Paginates through all PartitionKeyRange objects using readPartitionKeyRanges with a continuation token, printing each range's ID and min/max bounds. Useful for manual fan-out across partitions. ```java FeedOptions feedOptions = new FeedOptions(); feedOptions.setMaxItemCount(100); String continuation = null; do { feedOptions.setRequestContinuation(continuation); FeedResponse page = client .readPartitionKeyRanges(collectionLink, feedOptions) .toBlocking().single(); for (PartitionKeyRange r : page.getResults()) { System.out.println(r.getId() + " [" + r.getMinInclusive() + ", " + r.getMaxExclusive() + ")"); } continuation = page.getResponseContinuation(); } while (continuation != null); ``` -------------------------------- ### StoredProcedure class definition Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/server-side-models.md Defines the StoredProcedure resource model with constructors and methods for getting and setting the JavaScript body. The body is executed by the service. The sproc id is inherited from Resource and is unique within the collection. ```java public class StoredProcedure extends Resource { public StoredProcedure() {} public StoredProcedure(String jsonString) {} public String getBody() {} public void setBody(String body) {} } ``` -------------------------------- ### Paginate queryDatabases with continuation token Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/client-database-collection.md Pagination loop for queryDatabases using FeedOptions with maxItemCount and requestContinuation. Continues until getResponseContinuation returns null. Prints each database id and request charge. ```java FeedOptions options = new FeedOptions(); options.setMaxItemCount(2); String continuation = null; do { options.setRequestContinuation(continuation); FeedResponse page = client.queryDatabases("SELECT * FROM c", options) .toBlocking().single(); for (Database d : page.getResults()) { System.out.println("db: " + d.getId() + ", charge: " + d.getRequestCharge()); } continuation = page.getResponseContinuation(); // null when no more pages } while (continuation != null); ``` -------------------------------- ### Collection configuration with indexing and partition key Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/resource-models.md Configures a DocumentCollection with a default time-to-live, an indexing policy that includes all paths, and a hash partition key on the '/city' path. Uses PartitionKeyDefinition with PartitionKind.Hash. ```java DocumentCollection coll = new DocumentCollection(); coll.setId("items"); coll.setDefaultTimeToLive(86400); IndexingPolicy ip = new IndexingPolicy(); IncludedPath p = new IncludedPath(); p.setPath("/"); ip.setIncludedPaths(Collections.singleton(p)); // index everything coll.setIndexingPolicy(ip); PartitionKeyDefinition pkd = new PartitionKeyDefinition(); pkd.setPaths(Collections.singletonList("/city")); pkd.setKind(PartitionKind.Hash); coll.setPartitionKey(pkd); ``` -------------------------------- ### Create and read a document asynchronously Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/client-document-operations.md Creates a document and reads it back using the async subscription style. Demonstrates nested subscriptions and error handling for both operations. ```java AsyncDocumentClient client = new AsyncDocumentClient.Builder() .withServiceEndpoint(HOST).withMasterKeyOrResourceToken(KEY).build(); Document doc = new Document("{ 'id': 'doc1', 'counter': 1 }".replace('\'', '"')); client.createDocument(collectionLink, doc, null, false) .single() .subscribe( rsp -> { System.out.println("created: " + rsp.getResource().getId() + " charge=" + rsp.getRequestCharge()); client.readDocument(rsp.getResource().getSelfLink(), null) .single() .subscribe( readRsp -> System.out.println("read: " + readRsp.getResource().getString("counter")), err -> System.err.println("read failed: " + err.getMessage())); }, error -> System.err.println("create failed: " + error.getMessage())); ``` -------------------------------- ### Run tests with Maven Source: https://github.com/azure/azure-cosmosdb-java/blob/master/README.md Runs tests from the command line, requiring Azure Cosmos DB endpoint credentials passed as system properties. ```bash mvn test -DACCOUNT_HOST="https://REPLACE_ME_WITH_YOURS.documents.azure.com:443/" -DACCOUNT_KEY="REPLACE_ME_WITH_YOURS" ``` -------------------------------- ### BridgeInternal bridge factory API Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/response-types.md Public but intended for SDK-internal bridging, not for application construction of responses. Provides static methods to convert RxDocumentServiceResponse objects into typed responses, set and get fields on DocumentClientException, and query database account and connection policy settings. ```java public class BridgeInternal { public static Error createError(ObjectNode objectNode) public static Document documentFromObject(Object document, ObjectMapper mapper) public static ResourceResponse toResourceResponse(RxDocumentServiceResponse response, Class cls) public static MediaResponse toMediaResponse(RxDocumentServiceResponse response, boolean willBuffer) public static FeedResponse toFeedResponsePage(RxDocumentServiceResponse response, boolean useEtagAsContinuation, Class cls) public static FeedResponse toChaneFeedResponsePage(RxDocumentServiceResponse response, Class cls) public static StoredProcedureResponse toStoredProcedureResponse(RxDocumentServiceResponse response) public static DatabaseAccount toDatabaseAccount(RxDocumentServiceResponse response) public static Map getFeedHeaders(FeedOptionsBase options) public static boolean noChanges(FeedResponse page) public static boolean noChanges(RxDocumentServiceResponse rsp) public static FeedResponse createFeedResponse(List results, Map headers) public static FeedResponse createFeedResponseWithQueryMetrics(List results, Map headers, ConcurrentMap queryMetricsMap) public static E setResourceAddress(E e, String resourceAddress) public static long getLSN(E e) public static String getPartitionKeyRangeId(E e) public static String getResourceAddress(E e) public static E setLSN(E e, long lsn) public static E setPartitionKeyRangeId(E e, String partitionKeyRangeId) public static boolean isEnableMultipleWriteLocations(DatabaseAccount account) public static boolean getUseMultipleWriteLocations(ConnectionPolicy policy) public static void setUseMultipleWriteLocations(ConnectionPolicy policy, boolean value) public static Uri getRequestUri(DocumentClientException documentClientException) public static void setRequestHeaders(DocumentClientException documentClientException, Map requestHeaders) public static void setSubStatusCode(DocumentClientException documentClientException, int subStatusCode) public static Map getRequestHeaders(DocumentClientException documentClientException) public static Map getQueryEngineConfiuration(DatabaseAccount databaseAccount) public static ReplicationPolicy getReplicationPolicy(DatabaseAccount databaseAccount) public static ReplicationPolicy getSystemReplicationPolicy(DatabaseAccount databaseAccount) } ``` -------------------------------- ### System property for options file path Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/configuration.md Sets the default options for the RNTBD transport client using a system property that points to a JSON file. The property is named 'azure.cosmos.directTcp.defaultOptionsFile'. ```bash -Dazure.cosmos.directTcp.defaultOptionsFile=/path/to/default/options/file ``` -------------------------------- ### Convert Observable to ListenableFuture using ListenableFutureObservable Source: https://github.com/azure/azure-cosmosdb-java/blob/master/README.md Java example converting an RxJava Observable to a Guava ListenableFuture using ListenableFutureObservable.to(). Requires the RxJava Guava library. The resulting future can be used to block on the result. Note: for CPU-intensive work, consider changing the scheduler to avoid stealing Netty event loop threads. ```java // You can convert an Observable to a ListenableFuture. // ListenableFuture (part of google guava library) is a popular extension // of Java's Future which allows registering listener callbacks: // https://github.com/google/guava/wiki/ListenableFutureExplained import rx.observable.ListenableFutureObservable; Observable> createDocObservable = asyncClient.createDocument( collectionLink, document, null, false); // NOTE: if you are going to do CPU intensive work // on the result thread consider changing the scheduler see Use Proper Scheduler // (Avoid Stealing Eventloop IO Netty threads) section ListenableFuture> listenableFuture = ListenableFutureObservable.to(createDocObservable); ResourceResponse rrd = listenableFuture.get(); ``` -------------------------------- ### PartitionKeyDefinition class definition Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/partitioning.md Defines the partition key definition for a collection. Use `setKind` with `PartitionKind.Hash`, `setVersion` with `V1` or `V2` (V2 required for case- and accent-insensitive hash partition keys on string paths), and `setPaths` with partition key paths like `["/city"]` or `["/deviceId", "/date"]`. Set it on the collection via `DocumentCollection.setPartitionKey` before `createCollection`; the partition key is immutable afterwards. ```java public final class PartitionKeyDefinition extends JsonSerializable { public PartitionKeyDefinition() {} public PartitionKeyDefinition(String jsonString) {} public PartitionKind getKind() {} public void setKind(PartitionKind kind) {} public PartitionKeyDefinitionVersion getVersion() {} public void setVersion(PartitionKeyDefinitionVersion version) {} public List getPaths() {} public void setPaths(List paths) {} } ``` -------------------------------- ### Create a Document with AsyncDocumentClient Source: https://github.com/azure/azure-cosmosdb-java/blob/master/README.md Use this snippet to create a document in Azure Cosmos DB using the async client. It sets the connection policy to Direct mode, builds the client with the service endpoint, master key, and eventual consistency, then creates a document and subscribes to the observable to print the request charge or an error. ```java import com.microsoft.azure.cosmosdb.rx.*; import com.microsoft.azure.cosmosdb.*; ConnectionPolicy policy = new ConnectionPolicy(); policy.setConnectionMode(ConnectionMode.Direct); AsyncDocumentClient asyncClient = new AsyncDocumentClient.Builder() .withServiceEndpoint(HOST) .withMasterKeyOrResourceToken(MASTER_KEY) .withConnectionPolicy(policy) .withConsistencyLevel(ConsistencyLevel.Eventual) .build(); Document doc = new Document(String.format("{ 'id': 'doc%d', 'counter': '%d'}", 1, 1)); Observable> createDocumentObservable = asyncClient.createDocument(collectionLink, doc, null, false); createDocumentObservable .single() // we know there will be one response .subscribe( documentResourceResponse -> { System.out.println(documentResourceResponse.getRequestCharge()); }, error -> { System.err.println("an error happened: " + error.getMessage()); }); ``` -------------------------------- ### Monitor Direct TCP metrics (duplicate) Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/async-document-client.md Duplicate of the monitor method shown with a comment indicating direct TCP metrics. Requires the optional io.micrometer:micrometer-core dependency. ```java public static void monitor(MeterRegistry registry) // direct TCP metrics ``` -------------------------------- ### Builder.withConfigs Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/async-document-client.md Sets internal configuration tunables. If not set, a new Configs instance is used. ```APIDOC ## Builder.withConfigs ### Description Sets internal configuration tunables. If not set, a new Configs instance is used. ### Method withConfigs ### Signature public Builder withConfigs(Configs configs) ### Parameters - **configs** (Configs) - Optional - Internal configuration tunables. ### Returns Builder - The builder instance for fluent chaining. ``` -------------------------------- ### createDatabase(Database database, RequestOptions options) Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/client-database-collection.md Creates a new database in the Cosmos DB account. Emits a ResourceResponse containing the created database. ```APIDOC ## createDatabase(Database database, RequestOptions options) ### Description Creates a new database in the Cosmos DB account. Emits a ResourceResponse containing the created database. ### Method createDatabase ### Signature Observable> createDatabase(Database database, RequestOptions options) ### Parameters - **database** (Database) - Required - The database to create (its `id` property). - **options** (RequestOptions) - Optional - Request options: consistency level, session token, access condition, triggers, partition key. ### Return Type Observable> ### Behavior Emits a single ResourceResponse containing the created database. ### Errors Emits DocumentClientException on error channel (e.g., 409 on duplicate id). ``` -------------------------------- ### Create and execute stored procedure with parameters Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/server-side-models.md Creates a stored procedure named 'triple' that multiplies its input by 3, then executes it with the argument 21 and prints the response, which is 63. ```java StoredProcedure sp = new StoredProcedure(); sp.setId("triple"); sp.setBody("function (a) { getContext().getResponse().setBody(a * 3); }"); StoredProcedure created = client.createStoredProcedure(collectionLink, sp, null) .toBlocking().single().getResource(); StoredProcedureResponse rsp = client .executeStoredProcedure(created.getSelfLink(), new Object[]{ 21 }) .toBlocking().single(); System.out.println(rsp.getResponseAsString()); // 63 ``` -------------------------------- ### FeedOptions Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/request-feed-options.md Concrete class extending FeedOptionsBase, adding options for partition key range, session token, scan, traces, cross-partition queries, parallelism, buffering, continuation limit, and empty pages. ```APIDOC ## FeedOptions ### Description Concrete class extending FeedOptionsBase, adding options for partition key range, session token, scan, traces, cross-partition queries, parallelism, buffering, continuation limit, and empty pages. ### Constructors - `public FeedOptions()` - `public FeedOptions(FeedOptions options)` — copy constructor ### Properties #### partition key range id - **Getter**: `getPartitionKeyRangeIdInternal()` - **Setter**: `setPartitionKeyRangeIdInternal(String)` - **Type**: String - **Default**: — - **Description**: target a specific partition key range (advanced) #### session token - **Getter**: `getSessionToken()` - **Setter**: `setSessionToken(String)` - **Type**: String - **Default**: — - **Description**: sticky session token for reads #### scan - **Getter**: `getEnableScanInQuery()` - **Setter**: `setEnableScanInQuery(Boolean)` - **Type**: Boolean - **Default**: — - **Description**: allow full scans (`x-ms-documentdb-query-enable-scan`) #### traces - **Getter**: `getEmitVerboseTracesInQuery()` - **Setter**: `setEmitVerboseTracesInQuery(Boolean)` - **Type**: Boolean - **Default**: — - **Description**: verbose query traces (`x-ms-documentdb-query-emit-traces`) #### cross-partition - **Getter**: `getEnableCrossPartitionQuery()` - **Setter**: `setEnableCrossPartitionQuery(Boolean)` - **Type**: Boolean - **Default**: — - **Description**: allow cross-partition queries #### parallelism - **Getter**: `getMaxDegreeOfParallelism()` - **Setter**: `setMaxDegreeOfParallelism(int)` - **Type**: int - **Default**: — - **Description**: parallel fan-out for cross-partition queries #### buffering - **Getter**: `getMaxBufferedItemCount()` - **Setter**: `setMaxBufferedItemCount(int)` - **Type**: int - **Default**: — - **Description**: max buffered items while merging partitions #### continuation limit - **Getter**: `getResponseContinuationTokenLimitInKb()` - **Setter**: `setResponseContinuationTokenLimitInKb(int)` - **Type**: int - **Default**: — - **Description**: cap on continuation token size #### empty pages - **Getter**: `getAllowEmptyPages()` - **Setter**: `setAllowEmptyPages(boolean)` - **Type**: boolean - **Default**: — - **Description**: emit empty feed pages (change-feed polling) ``` -------------------------------- ### Clone the repository Source: https://github.com/azure/azure-cosmosdb-java/blob/master/README.md Clones the Azure Cosmos DB Java SDK repository and changes into the project directory. ```bash git clone https://github.com/Azure/azure-cosmosdb-java.git cd azure-cosmosdb-java ``` -------------------------------- ### Configure and use a pre-trigger Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/server-side-models.md Creates a pre-trigger named 'audit' that sets an 'audited' field to true on documents, then creates a document with that trigger included, demonstrating how to attach a trigger to a document creation operation. ```java Trigger trigger = new Trigger(); trigger.setId("audit"); trigger.setTriggerType(TriggerType.Pre); trigger.setTriggerOperation(TriggerOperation.All); trigger.setBody("function () { var c = getContext(); var doc = c.getRequest().getBody(); doc['audited'] = true; c.getRequest().setBody(doc); }"); client.createTrigger(collectionLink, trigger, null).toBlocking().single(); RequestOptions createOpts = new RequestOptions(); createOpts.setPreTriggerInclude(Collections.singletonList("audit")); client.createDocument(collectionLink, new Document("{'id':'x'}"), createOpts, false).toBlocking().single(); ``` -------------------------------- ### Builder.withMasterKey Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/async-document-client.md Sets the master key or resource token for authentication. Deprecated; use withMasterKeyOrResourceToken instead. ```APIDOC ## Builder.withMasterKey ### Description Sets the master key or resource token for authentication. Deprecated; use withMasterKeyOrResourceToken instead. ### Method withMasterKey ### Signature public Builder withMasterKey(String masterKeyOrResourceToken) ### Parameters - **masterKeyOrResourceToken** (String) - Required - The master key or resource token. ### Returns Builder - The builder instance for fluent chaining. ``` -------------------------------- ### queryOffers Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/client-users-permissions-offers.md Queries offers using a SQL query. Supports both a raw query string and a SqlQuerySpec. ```APIDOC ## queryOffers ### Description Queries offers using a SQL query. Supports both a raw query string and a SqlQuerySpec. ### Method queryOffers ### Endpoint Observable> queryOffers(String query, FeedOptions options) Observable> queryOffers(SqlQuerySpec querySpec, FeedOptions options) ### Parameters #### Query Parameters - **query** (String) - Required (if using string overload) - SQL query string, e.g., `"SELECT * FROM offers"`. - **querySpec** (SqlQuerySpec) - Required (if using SqlQuerySpec overload) - SQL query specification. - **options** (FeedOptions) - Optional - Paging options for the feed. ### Request Example ```java Observable> response = offer.queryOffers("SELECT * FROM offers", options); ``` ### Response #### Success Response - **FeedResponse** - A feed of offers matching the query. #### Response Example ```java FeedResponse response = ...; // contains a page of offers ``` ``` -------------------------------- ### Builder.withPermissionFeed Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/async-document-client.md Sets a list of permissions for token-based authentication. One of masterKey, permissionFeed, or tokenResolver must be provided. ```APIDOC ## Builder.withPermissionFeed ### Description Sets a list of permissions for token-based authentication. One of masterKey, permissionFeed, or tokenResolver must be provided. ### Method withPermissionFeed ### Signature public Builder withPermissionFeed(List permissionFeed) ### Parameters - **permissionFeed** (List) - Required - List of permissions containing resource tokens. ### Returns Builder - The builder instance for fluent chaining. ``` -------------------------------- ### Basic construction and blocking read Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/async-document-client.md Constructs an AsyncDocumentClient with a direct connection policy and session consistency, then performs a blocking read of the database account. Requires HOST and MASTER_KEY variables. The client must be closed after use. ```java import com.microsoft.azure.cosmosdb.*; import com.microsoft.azure.cosmosdb.rx.*; ConnectionPolicy policy = new ConnectionPolicy(); policy.setConnectionMode(ConnectionMode.Direct); AsyncDocumentClient client = new AsyncDocumentClient.Builder() .withServiceEndpoint(HOST) // e.g. "https://my.documents.azure.com:443/" .withMasterKeyOrResourceToken(MASTER_KEY) .withConnectionPolicy(policy) .withConsistencyLevel(ConsistencyLevel.Session) .build(); // read the account (blocking style) DatabaseAccount account = client.getDatabaseAccount().toBlocking().single(); System.out.println(account.getConsistencyPolicy()); client.close(); ``` -------------------------------- ### Run WriteLatency workload Source: https://github.com/azure/azure-cosmosdb-java/blob/master/benchmark/README.md Runs the benchmark jar with the WriteLatency operation, specifying endpoint, key, database, collection, consistency, concurrency, and operation count. Uses Direct connection mode. ```bash java -jar benchmark/target/azure-cosmosdb-benchmark-2.4.1-SNAPSHOT-jar-with-dependencies.jar \ -serviceEndpoint $endpoint -masterKey $masterkey \ -databaseId $dbname -collectionId $colname \ -consistencyLevel Eventual -concurrency 10 -numberOfOperations 1000000 \ -operation WriteLatency -connectionMode Direct ``` -------------------------------- ### Builder.withConsistencyLevel Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/async-document-client.md Sets the desired consistency level for the client. If not set, the service default is used. ```APIDOC ## Builder.withConsistencyLevel ### Description Sets the desired consistency level for the client. If not set, the service default is used. ### Method withConsistencyLevel ### Signature public Builder withConsistencyLevel(ConsistencyLevel desiredConsistencyLevel) ### Parameters - **desiredConsistencyLevel** (ConsistencyLevel) - Optional - The desired consistency level. ### Returns Builder - The builder instance for fluent chaining. ``` -------------------------------- ### List offers and replace throughput Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/client-users-permissions-offers.md Subscribes to readOffers, prints each offer's resource ID, type, and throughput, and replaces the offer for a specific collection (identified by 'my-collection-rid') with a new throughput of 1200. Errors are printed to stderr. ```java client.readOffers(null).subscribe( page -> page.getResults().forEach(o -> { System.out.println("offer=" + o.getOfferResourceId() + " type=" + o.getOfferType() + " throughput=" + o.getThroughput()); if (o.getOfferResourceId().equals("my-collection-rid")) { o.setThroughput(1200); client.replaceOffer(o).toBlocking().single(); } }), error -> System.err.println("offers query failed: " + error.getMessage())); ``` -------------------------------- ### Offers API method signatures Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/client-users-permissions-offers.md These are the method signatures for the Offers API, showing how to replace, read, and query offers. The methods return Observable instances for asynchronous operations. ```java Observable> replaceOffer(Offer offer); // :1465 Observable> readOffer(String offerLink); // :1477 Observable> readOffers(FeedOptions options); // :1489 Observable> queryOffers(String query, FeedOptions options); // :1501 Observable> queryOffers(SqlQuerySpec querySpec, FeedOptions options); // :1513 ``` -------------------------------- ### Create and execute stored procedure with error handling Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/client-server-side.md Creates a stored procedure named 'multiply' that multiplies two numbers, then executes it with a partition key 'Seattle'. Catches DocumentClientException and prints the status code and error message on failure. ```java StoredProcedure sp = new StoredProcedure( "{ 'id': 'multiply', 'body': 'function (a, b) { getContext().getResponse().setBody(a * b); }' }" .replace('\'', '\"')); StoredProcedure created = client .createStoredProcedure(collectionLink, sp, null) .toBlocking().single().getResource(); RequestOptions opts = new RequestOptions(); opts.setPartitionKey(new PartitionKey("Seattle")); try { StoredProcedureResponse rsp = client .executeStoredProcedure(created.getSelfLink(), opts, new Object[]{ 6, 7 }) .toBlocking().single(); System.out.println("result: " + rsp.getResponseAsString() + ", charge=" + rsp.getRequestCharge()); } catch (DocumentClientException e) { System.err.println("sproc failed: status=" + e.getStatusCode() + " msg=" + e.getError().getMessage()); } ``` -------------------------------- ### Construction with a TokenResolver (no master key) Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/async-document-client.md Builds an AsyncDocumentClient using a TokenResolver instead of a master key. The resolver receives the request verb, resource ID or full name, and resource type, and must return a token from myTokenService. ```java AsyncDocumentClient client = new AsyncDocumentClient.Builder() .withServiceEndpoint(HOST) .withTokenResolver((requestVerb, resourceIdOrFullName, resourceType, properties) -> myTokenService.tokenFor(requestVerb, resourceIdOrFullName, resourceType)) .build(); ``` -------------------------------- ### Import AsyncDocumentClient and common resources Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/overview.md Typical imports for consumers of the SDK, bringing in the main async client interface and the common resource/model classes. ```java import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; import com.microsoft.azure.cosmosdb.*; ``` -------------------------------- ### Document construction and field access Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/resource-models.md Shows how to create a Document from a JSON string (single quotes accepted) and access arbitrary fields using inherited methods like getString. ```java new Document("{ 'id': 'doc1', 'counter': 2 }") ``` ```java document.getString("counter") ``` -------------------------------- ### createUser Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/client-users-permissions-offers.md Creates a new user in the specified database. ```APIDOC ## createUser ### Description Creates a new user in the specified database. ### Method Observable> ### Signature Observable> createUser(String databaseLink, User user, RequestOptions options) ### Parameters - **databaseLink** (String) - Required - The link to the database. - **user** (User) - Required - The user to create. - **options** (RequestOptions) - Required - The request options. ### Returns Observable> - A single user resource response. ``` -------------------------------- ### Builder.withMasterKeyOrResourceToken Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/async-document-client.md Sets the master key or resource token for authentication. This is the preferred method over withMasterKey. ```APIDOC ## Builder.withMasterKeyOrResourceToken ### Description Sets the master key or resource token for authentication. This is the preferred method over withMasterKey. ### Method withMasterKeyOrResourceToken ### Signature public Builder withMasterKeyOrResourceToken(String masterKeyOrResourceToken) ### Parameters - **masterKeyOrResourceToken** (String) - Required - The master key or resource token. ### Returns Builder - The builder instance for fluent chaining. ``` -------------------------------- ### Builder.build Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/async-document-client.md Builds an AsyncDocumentClient instance. Throws IllegalArgumentException if service endpoint is missing or if no authentication method is provided. ```APIDOC ## Builder.build ### Description Builds an AsyncDocumentClient instance. Throws IllegalArgumentException if service endpoint is missing or if no authentication method is provided. ### Method build ### Signature public AsyncDocumentClient build() ### Returns AsyncDocumentClient - The constructed client instance. ### Exceptions - IllegalArgumentException - If service endpoint is missing or if none of masterKey, resourceToken, permissionFeed, or tokenResolver is present. ``` -------------------------------- ### Micrometer metrics monitoring Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/async-document-client.md Enables Micrometer metrics monitoring for the client by registering a SimpleMeterRegistry. After calling AsyncDocumentClient.monitor(registry), timers such as "azure.cosmos.directTcp.requests" become available in the registry. ```java import io.micrometer.core.instrument.simple.SimpleMeterRegistry; SimpleMeterRegistry registry = new SimpleMeterRegistry(); AsyncDocumentClient.monitor(registry); // registry.timer("azure.cosmos.directTcp.requests", ...) etc. become available ``` -------------------------------- ### Read Direct TCP options from resource file azure.cosmos.directTcp.defaultOptions.json Source: https://github.com/azure/azure-cosmosdb-java/blob/master/README.md Java code snippet showing how the SDK reads the resource file azure.cosmos.directTcp.defaultOptions.json from the classpath using RntbdTransportClient's class loader. This is the third priority for loading default Direct TCP options. ```java RntbdTransportClient.class.getClassLoader().getResourceAsStream("azure.cosmos.directTcp.defaultOptions.json") ``` -------------------------------- ### Paginate with FeedResponse.getResponseContinuation() Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/response-types.md Pagination loop using FeedOptions.setMaxItemCount(50) and FeedResponse.getResponseContinuation(). The loop continues until the continuation token is null, printing each document ID. The continuation token is passed back via setRequestContinuation(). ```java FeedOptions feedOptions = new FeedOptions(); feedOptions.setMaxItemCount(50); String continuation = null; do { FeedResponse page = client .queryDocuments(collectionLink, "SELECT * FROM c", feedOptions) .toBlocking().single(); page.getResults().forEach(d -> System.out.println(d.getId())); continuation = page.getResponseContinuation(); feedOptions.setRequestContinuation(continuation); } while (continuation != null); ``` -------------------------------- ### ConnectionPolicy() Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/connection-policy.md Creates a new ConnectionPolicy instance with default settings. Use this for per-client tuning instead of the shared default. ```APIDOC ## ConnectionPolicy() ### Description Creates a new ConnectionPolicy instance with default settings. Use this for per-client tuning instead of the shared default. ### Method Constructor ### Signature java public ConnectionPolicy() ### Parameters None. ### Returns A new ConnectionPolicy instance with default values. ### Remarks Defaults are documented in the table above. For example, request timeout is 60000 ms, connection mode is Gateway, and retry options are a new RetryOptions(). ``` -------------------------------- ### Error when the partition key is missing or mismatched Source: https://github.com/azure/azure-cosmosdb-java/blob/master/_autodocs/api-reference/partitioning.md Catches DocumentClientException when creating a document without a partition key, checking for BADREQUEST status and PARTITION_KEY_MISMATCH substatus to print an error message. ```java try { client.createDocument(collectionLink, new Document("{ 'id': 'x' }"), null, false) .toBlocking().single(); } catch (DocumentClientException e) { if (e.getStatusCode() == HttpConstants.StatusCodes.BADREQUEST && e.getSubStatusCode() == HttpConstants.SubStatusCodes.PARTITION_KEY_MISMATCH) { System.err.println("specify the partition key via RequestOptions/FeedOptions"); } } ```