There are many different ways to query for data in Couchbase Server. You can do direct lookups for documents

based on their key, you can query views, or you can even write N1QL queries.

When it comes to obtaining data, doing a lookup based on a document key will always be faster than querying.

What happens when you have a handful of keys that you need to lookup? You could easily loop through these

keys using one of the SDKs, but that is a new network request per operation. Did you know you could batch

these keys into a single request?

I’ve seen this asked a few times, so I thought it would be useful to write about how to make it happen. Let’s

use the scenario that we have 1000 keys that we need to look up in a Node.js application. To do this, our

code might look like the following:

var Couchbase = require("couchbase"); var cluster = new Couchbase.Cluster("couchbase://localhost"); var bucket = cluster.openBucket("default", ""); bucket.getMulti(["234adsf", "bab7", "fe3f9921"], function(error, results) { if(error) { console.log(error + " failed to be retrieved"); } for(var key in results) { if(results.hasOwnProperty(key)) { if(results[key].error) { console.log("`" + key + "`: " + JSON.stringify(results[key])); } } } process.exit(0); }); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 var Couchbase = require ( "couchbase" ) ; var cluster = new Couchbase . Cluster ( "couchbase://localhost" ) ; var bucket = cluster . openBucket ( "default" , "" ) ; bucket . getMulti ( [ "234adsf" , "bab7" , "fe3f9921" ] , function ( error , results ) { if ( error ) { console . log ( error + " failed to be retrieved" ) ; } for ( var key in results ) { if ( results . hasOwnProperty ( key ) ) { if ( results [ key ] . error ) { console . log ( "`" + key + "`: " + JSON . stringify ( results [ key ] ) ) ; } } } process . exit ( 0 ) ; } ) ;

In the above example we are connecting to a locally running Couchbase instance and opening the default

bucket. The intention is to do a single request to get three different documents based on their key. This

is made possible via the getMulti method in Node.js. If the document keys don’t exist in

Couchbase or there are some other problems, errors will be returned in the results.

If you’re interested in the topic of performance, Kirk Kirkconnel wrote a blog post that explains the

differences. It can be found here. You

can also read about batching operations in the Couchbase documentation.