自己投資の一つとしてチャレンジしている Programming の Java の独習状況を Blog で公開しています。今回は Azure Cosmos DB API for MongoDB への接続および、Document の Read, Write について紹介します。
————————————
▼1. Azure Cosmos DB API for MongoDB 利用のメリット
————————————
Azure Cosmos DB は NoSQL Database で Relational Database とは異なり、スキーマやテーブルをあらかじめ定義する必要はなく、データを分散しクエリ実行時パフォーマンスが得られるように Shared key を決め collection id を作成するだけで利用できます。MongoDB を利用するメリットとしては BSON が利用できる点が挙げられます。JSON よりも多い Data type、例えば Date や Raw Binary などが利用できます。
————————————
▼2. 事前準備
————————————
2-1. 以下のサイトから無料で利用できる Azure Cosmos DB を用意します。Azure を利用するために必要な Subscription を用意する必要もありません。
https://azure.microsoft.com/ja-jp/try/cosmosdb/
2-2. IntelliJ IDEA のインストール
詳細はこちらの blog を参照ください。
2-3. Maven auto-import を IntelliJ IDEA で有効にします(ubuntu で IntelliJ IDEA をインストールしています)。
詳細はこちらの blog を参照ください。
2-4. Pom.xml に以下のように必要なライブラリーを指定します。その後、上記 2-3 設定により、ライブラリーが自動でダウンロードされます。
<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.4.2</version>
</dependency>
</dependencies>————————————
▼3. Cosmos DB への接続および Document の書き込みと読み取り
————————————
3-1. 以下のコードで Azure Cosmos DB に接続します。
connectionString には接続文字列を入れ、dbName および collName にそれぞれ利用する DB 名と Collection 名を入れます。
(例)
import com.mongodb.MongoClientOptions;
import com.mongodb.client.model.Filters;
import com.mongodb.MongoException;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
public class ConnCosmosDBMongoDBv1 {
String connectionString ="mongodb://xxxx.documents.azure.com:10255/?ssl=true";
String dbName = "dbname";
String collName = "collectionname";
MongoClient client;
public void InitMongoClient()
{
MongoClientOptions.Builder optionBuilder = new MongoClientOptions.Builder();
// Set values to prevent timeouts
optionBuilder.socketTimeout(10000);
optionBuilder.maxConnectionIdleTime(60000);
optionBuilder.heartbeatConnectTimeout(5000);
MongoClientURI mongoClientURI = new MongoClientURI(this.connectionString, optionBuilder);
this.client = new MongoClient(mongoClientURI);
}
public void ReadDocuments() {
System.out.println("Reading documents.");
try {
MongoCollection<Document> coll = this.client.getDatabase(this.dbName).getCollection(this.collName);
// Add the document
Document document = new Document("LName","French");
document.append("Sku","F00");
document.append("Name","Middle");
document.append("Price","200");
coll.insertOne(document);
// Read the document
Document queryResult = coll.find(Filters.eq("LName","French")).first();
if (queryResult != null) {
System.out.println("===");
System.out.println(queryResult.toJson());
}
} catch (MongoException me) {
System.out.println("Exception:" + me);
}
}
public void RunCode() {
System.out.println("Start the application.");
InitMongoClient();
ReadDocuments();
System.out.println("Completed the application");
}
public static void main(String[] args) {
ConnCosmosDBMongoDBv1 appMongo = new ConnCosmosDBMongoDBv1();
appMongo.RunCode();
}
}3-2. 実行結果は以下となります。
(例)
Start the application.
Jan 29, 2022 4:57:39 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[xxxx.documents.azure.com:10255], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
Reading documents.
Jan 29, 2022 4:57:39 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: No server chosen by WritableServerSelector from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, serverDescriptions=[ServerDescription{address=xxxx.documents.azure.com:10255, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out
Jan 29, 2022 4:57:40 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:1, serverValue:111111111}] to xxxx.documents.azure.com:10255
Jan 29, 2022 4:57:41 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Monitor thread successfully connected to server with description ServerDescription{address=xxxx.documents.azure.com:10255, type=REPLICA_SET_PRIMARY, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 2, 0]}, minWireVersion=0, maxWireVersion=2, maxDocumentSize=16777216, roundTripTimeNanos=110864552, setName='globaldb', canonicalAddress=xxxxxx.documents.azure.com:10255, hosts=[xxxxxx.documents.azure.com:10255], passives=[], arbiters=[], primary='xxxxxx.documents.azure.com:10255', tagSet=TagSet{[Tag{name='region', value='West US'}]}, electionId=null, setVersion=1, lastWriteDate=null, lastUpdateTimeNanos=1111111}
Jan 29, 2022 4:57:42 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:2, serverValue:-111111}] to xxxx.documents.azure.com:10255
===
{ "_id" : { "$oid" : "6xxxxxxx" }, "LName" : "French", "Sku" : "F00", "Name" : "Middle", "Price" : "200" }
Completed the application
Process finished with exit code 0————————————
▼4. 参考情報
————————————
(1) Azure Cosmos DB を無料で試す https://docs.microsoft.com/ja-jp/azure/cosmos-db/optimize-dev-test#try-azure-cosmos-db-for-free
(2) Quickstart: Build a web app using the Azure Cosmos DB API for Mongo DB and Java SDK | Microsoft Docs
(3) azure-cosmos-db-mongodb-java-getting-started/Program.java at master · Azure-Samples/azure-cosmos-db-mongodb-java-getting-started · GitHub
(4) azure-cosmos-db-mongodb-java-geo-readpreference/App.java at master · Azure-Samples/azure-cosmos-db-mongodb-java-geo-readpreference · GitHub
以上です。参考になりましたら幸いです。