Retooling
April 13, 2018Asynchronous Programming with JavaScript Part 1: Introduction & Overview
June 13, 2018Do you ever find yourself making Couchbase calls inside of a loop to get your documents, and you ask yourself if there is a better way? One handy method in the Couchbase SDK, version 4.5 or greater, is getMulti, a variant of the get method that allows you to perform bulk retrieval operations.
There are many ways to get data from Couchbase. You can write and query a view, run a N1QL query, or lookup a document via its key. There are benefits to each but looking up a document directly by key is the fastest way to retrieve data. In some cases, you may have multiple keys that you need to lookup, and getMulti can be used to retrieve all of the documents at once. This can significantly improve efficiency of your application, as well as decrease the workload that needs to be done by Couchbase.
Using getMulti is quite simple. Instead of performing a get call, where you pass in a single key to get a document, you pass in an array of keys for the documents you need. It’s as simple as that! Here is an example:
const couchbase = require('couchbase');
const cluster = new couchbase.Cluster('Administrator','admin');
const bucketName = 'default';
const buckets = {};
//default bucket
buckets.default = cluster.openBucket(bucketName, (err) => {
if(err) {
throw err;
}
});
buckets.default.operationTimeout = 10000;
buckets.default.bucketName = bucketName;
class CouchbaseService {
constructor (bucket) {
this.couchbaseBucket = buckets[bucket];
}
insertDesignDocument(viewName, ddocName, ddoc) {
return new Promise((resolve, reject) => {
try {
const bManager = this.couchbaseBucket.manager('Administrator', 'admin');
const views = {};
views[ddocName] = {
map: `${ddoc}`
};
const dataStruct = {
views
};
bManager.insertDesignDocument(viewName, dataStruct, (insertError) => {
if(insertError){
bManager.upsertDesignDocument(viewName, dataStruct, (updateError) => {
if(updateError) {
return resolve(null);
} else {
return resolve(null);
}
});
} else {
return resolve(null);
}
});
} catch(e) {
return reject(e);
}
});
}
}
module.exports = CouchbaseService;
The data is then returned as a structure with the key and value. This ends up being ideal since you can map the key array to replace the key with value.
There are many useful methods in the Couchbase SDK, and the getMulti method is one that substantially improves the efficiency of data-heavy applications. It can help to optimize your application greatly!