Store JSON documents in a Db2 database
JSON documents are stored in collections (or tables) in
the database. These documents are represented as a map of key value
pairs where the keys are strings. The values can be primitive Java™ objects like String, Integer,
Double, java.util.Date
, and also nested JSON documents
that are represented by other DBObject
instances.
JSON documents are represented by DBObject
instances
of the interface. A common implementation is by using BasicDBObject
object.
JSON arrays are represented by BasicDBList
class.
You can manually construct the objects, or you can use BasicDBObjectBuilder
class
for friendly syntax.
A collection is represented by DBCollection
class.
Before you can insert your documents, you must get a DBCollection
from
a DB
instance.
DBCollection empColl = db.getCollection("employees");
BasicDBObject obj = new BasicDBObject();
obj.put("name", "Joe");
obj.put("age", 50);
obj.put("salary", 60000);
empColl.insert(obj);
By default, insert operations wait for success confirmation from the database. If you want to
increase throughput at the expense of write safety, you can use WriteConcern.NONE
or WriteConcern.NORMAL
, in which case inserts are queued, batched, and inserted
with less frequent commits drastically increasing speed, but also increasing transaction log space
requirements on Db2 server side. The
Db2 server is
still providing atomicity, consistency, isolation, and durability (ACID). It is the API that is
relaxing the rules for speed.
DBCollection empColl = db.getCollection("employees");
for(int i=0; i<100; i++){
//Queues the object to be inserted
empColl.insert(dbObject[i], com.ibm.nosql.json.api.WriteConcern.NORMAL);
}
//Waits until all work sent from this thread on this db instance is processed
db.waitQueue();