Batching

Batching refers to accumulating multiple JSON documents and then sending them together to the JSON store instead of sending each one separately. The Db2® JSON API provides a programmatic way to run batching. The major advantage of batching is better performance.

The following types of batching are supported:
Homogeneous batching
Occurs when the JSON documents in the batch are part of the same collection and the same operation is applied to all documents.
Heterogeneous batching
Occurs when the JSON documents in the batch are part of different collections or different operations are applied to the documents.

To mark the start of a batch, use the startBatch() method. To trigger the insert, update, remove, or save operations for the documents, use the endBatch() method. If an operation in the batch fails, processing continues with the next operation in the batch.

Example 1: In the following example, homogeneous batching is used to insert three documents in one collection:
DBCollection batch = db.getCollection("batch");

BasicDBObject dbObj1 = new BasicDBObject("name", "Joe1");
dbObj1.put("_id", 1);

BasicDBObject dbObj2 = new BasicDBObject("name", "Joe2");
dbObj2.put("_id", 2);

BasicDBObject dbObj3 = new BasicDBObject("name", "Joe3");
dbObj3.put("_id", 3);

db.startBatch();

batch.insert(dbObj1);
batch.insert(dbObj2);
batch.insert(dbObj3);

db.endBatch(); 
Example 2: In the following example, heterogeneous batching is used to insert three documents in collection batch1 and two documents in collection batch2:
// Get collection batch1
DBCollection batch1 = db.getCollection("batch1");

// Create three documents to insert in collection batch1
BasicDBObject dbObj1 = new BasicDBObject("name", "Joe1");
dbObj1.put("_id", 1);

BasicDBObject dbObj2 = new BasicDBObject("name", "Joe2");
dbObj2.put("_id", 2);

BasicDBObject dbObj3 = new BasicDBObject("name", "Joe3");
dbObj3.put("_id", 3);

// Get collection batch2
DBCollection batch2 = _db.getCollection("batch2"); 

// Create two documents to insert in collection batch2
BasicDBObject dbObj4 = new BasicDBObject("name", "Joe4");
dbObj4.put("_id", 4);

BasicDBObject dbObj5 = new BasicDBObject("name", "Joe5");
dbObj5.put("_id", 5);

db.startBatch();

// Insert three documents into collection batch1

batch1.insert(dbObj1);
batch1.insert(dbObj2);
batch1.insert(dbObj3);

// Insert two documents into collection batch2

batch2.insert(dbObj4);
batch2.insert(dbObj5);

db.endBatch();