package com.microsoft.azure.documentdb.sample;
import java.util.Date;
import java.util.Iterator;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.microsoft.azure.documentdb.ConnectionMode;
import com.microsoft.azure.documentdb.ConnectionPolicy;
import com.microsoft.azure.documentdb.ConsistencyLevel;
import com.microsoft.azure.documentdb.Document;
import com.microsoft.azure.documentdb.DocumentClient;
import com.microsoft.azure.documentdb.FeedOptions;
import com.microsoft.azure.documentdb.FeedResponse;
import com.microsoft.azure.documentdb.ResourceResponse;
public class HelloCosmodDB002UpdateDocument {
public static void main(String[] args) throws Exception {
// 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 database_id = "{your_database}";
String collection_id = "{your_collection}";
// Get key from Azure Web Console
// read write key
String key = "{your_key}";
String endPoint = "https://" + host + ".documents.azure.com:443";
ConnectionPolicy policy = new ConnectionPolicy();
policy.setConnectionMode(ConnectionMode.DirectHttps);
try (DocumentClient client = new DocumentClient(endPoint, key, ConnectionPolicy.GetDefault(),
ConsistencyLevel.Session)) {
// Name? ID?
String collectionLink = String.format("/dbs/%s/colls/%s", database_id, collection_id);
JsonObject json;
FeedOptions options = new FeedOptions();
options.setEnableCrossPartitionQuery(true);
FeedResponse<Document> res = client.queryDocuments(collectionLink, "SELECT * FROM c WHERE c.id=\"1000\"",
options, "{your_pkey}");
Iterator<Document> itr = res.getQueryIterator();
if (itr.hasNext()) {
Document doc = itr.next();
Gson gson = new Gson();
json = gson.fromJson(doc.toJson(), JsonObject.class);
} else {
json = new JsonObject();
json.addProperty("id", "1000");
}
json.addProperty("text2", "This is test for update.");
json.addProperty("lastupdate", System.currentTimeMillis());
Document d = new Document(json.toString());
ResourceResponse<Document> response = client.upsertDocument(collectionLink, d, null, false);
client.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Recommended Posts