Data Structures
Edit this article in GitHub
Version 2.4

Data Structures

You can use complex data structures such as dictionaries and lists in Couchbase. These data structures may be manipulated with basic operations without retrieving and storing the entire document.

Data structures in Couchbase are similar in concept to data structures in JavaScript:
  • Map is like a JavaScript Object, and is a key-value structure, where a value is accessed by using a key string.
  • List is like a JavaScript array and is a sequential data structure. Values can be placed in the beginning or end of a list, and can be accessed using numeric indexes.
  • Set is a wrapper over a list which provides the ability to handle unique values.

These data structures are stored as JSON documents in Couchbase, and can therefore be accessed using N1QL, Full Text Search, and normal key-value operations. Data structures can also be manipulated using the traditional sub-document and full-document KV APIs.

Using the data structures API may help your application in two ways:
  • Simplicity: Data structures provide high level operations by which you can deal with documents as if they were container data structures. Adding an item to a dictionary is expressed as mapAdd, rather than retrieving the entire document, modifying it locally, and then saving it back to the server.
  • Efficiency: Data structure operations do not transfer the entire document across the network. Only the relevant data is exchanged between client and server, allowing for less network overhead and lower latency.

Creating a Data Structure

Data structures can be created implicitly by adding a create: true to the options of the operation. For example, to add an item to a map, specify the document ID of the map itself (i.e. the ID which uniquely identifies the map in the server), the key within the map, and the value to store under the key:
bucket.mapAdd('map_id', 'name', 'Mark Nunberg', {create: true}, function(err, result) {});
Likewise, to create a list, specify the document ID and the value to add:
bucket.listPush('list_id', 'hello', {create: true}, function(err, result) {});
Note that the {create: true} will not overwrite an existing document with the same name if it already exists. It is therefore always safe to use, unless your application creates data structures independently.

Data structures can be explicitly created and reset using full-document methods, and initialized with its JSON equivalent. To create a new empty list or set, use bucket.upsert('list_id', []). To create an empty map, use bucket.upsert('map_id', {}).

Accessing Data Structures

Data structures can be accessed using their appropriate methods. You need to supply a callback that receives an error and a result object. The actual returned value is can be accessed using the result.value property.
bucket.listGet('list_id', 0, function(err, result) {
    console.log('%s', result.value);
});
// Prints 'hello'
bucket.mapGet('map_id', 'name', function(err, result) {
    console.log('%s', result.value);
});
// Prints 'Mark Nunberg'
Here is a list of common operations:
Table 1. Data Structure Operations
   
mapRemove Remove a key from a map.
bucket.mapRemove('map_id', 'some_key', function(err, result){});
mapGet Get an item from a map.
bucket.mapGet('map_id', 'some_key', function(err, result) {
    console.log(result.value);
});
listPush Add an item to the end of a list.
bucket.listPush('list_id', 'some_value', function(err, result(){});
listShift Add an item to the beginning of a list.
bucket.listShift('list_id', 'some_value', function(err, result(){});
listGet Get an item from a list by its index.
bucket.listGet('list_id', 1, function(err, result) {
    console.log(result.value);
});
setAdd Add an item to a set, if the item does not yet exist in the set.
bucket.setAdd('list_id', 'some_value', function(err, result) {});
Note that a set is just a list. You can retrieve the entire set by simply using a full-document get operation:
bucket.get('list_id', function(err, result) {
    result.value; // <- this is the set
});
Note: Currently, using the node.js SDK you can only store primitive values in sets, such as strings, ints, and booleans.
setRemove Remove an item from a set, if it exists. An exception is not thrown if the item does not exist. You can determine if an item existed or not by the return value. If the item did not exist beforehand, None is returned.
bucket.setRemove('list_id', 'some_value', function(err, result){});
mapSize, listSize, setSize These methods get the length of the data structure. For maps, this is the number of key-value pairs inside the map. For lists, and sets, this is the number of elements in the structure.
bucket.listSize('list_id', function(err, result) {
    console.log(result.value);
});

Note that there are only two basic types: map and list. Types such as set are merely derivatives of list.

Data Structures and Key-Value APIs

Data structures can be accessed using key-value APIs as well. In fact, the data structure API is actually a client-side wrapper around the key-value and sub-document API. Most of the data structure APIs wrap the sub-document API directly. Therefore, for example, the map_set can be implemented as follows:
function mapSet(bucket, docid, key, value, callback) {
    bucket.mutateIn(docid).upsert(key, value).execute(function(err, frag) {
        if (err) {
            callback(err);
        }
        callback(null, {value: frag.contentByIndex(0)});
    });
}
Some data structure operations are compound operations. This means that they do not correspond to a single server-side operation. For example, setRemove does not exist on the server. In order to implement setRemove, it would require an implementation like so:
function setRemove(bucket, docid, value, callback) {
    bucket.get(docid, function(err, result) {
        if (err) {
            callback(err);
        } else {
            // Find the index
            value_index = err.result.indexOf(value);
            if (value_index != -1) {
                bucket.mutateIn(docid, {cas: result.cas}).remove('[' + value_index + ']').execute(function(err, res) {
                    callback(err, res);
                });
            }
        }
    });
}
In the example above, the entire document is fetched and the index of the value is retrieved. If the value exists, the index of the value is removed at the server side.
Note: Because the data structure API is just a wrapper around the various key-value APIs, you are free to switch between them in your application code.