Skip to content
ghillairet edited this page Sep 10, 2012 · 2 revisions

CouchDB

Apache CouchDB is a document-oriented database that can be queried and indexed using JavaScript in a MapReduce fashion. CouchDB also offers incremental replication with bi-directional conflict detection and resolution.

EMFJs offers support for CouchDB through the implementation of a custom URIHandler. This page will show you how store, update and retrieve EMF Resources from CouchDB.

Install CouchDB

First of all download and install CouchDB.

Then start couchdb in a terminal: $ couchdb

Then go to http://127.0.0.1:5984/_utils/index.html, you can now access couchdb web client.

Storing Resources as Documents

This part suppose that you are familiar with the concepts of EMF Resource, ResourceSet and URI.

The access of EMF resources from CouchDB is done via the Resource API of EMF. To enable the CouchDB support for your EMF models, simply add the following line after you create a ResourceSet.

ResourceSet resourceSet = new ResourceSetImpl();
resourceSet.getURIConverter().getURIHandlers().add(0, new CouchDBHandler());

When you create a Resource, use the URI of the CouchDB server (e.g. http://127.0.0.1:5984/), as shown below. The first segment of the URI (here users) is the name of the database that will be used to store the JSON document corresponding to your EMF model.

Resource resource = resourceSet.createResource(URI.createURI("http://127.0.0.1:5984/users"));

You can now create an object and add it to your Resource.

User user = ModelFactory.eINSTANCE.createUser();
user.setUserId("1");
user.setName("John");
resource.getContents().add(user);

You can now save the Resource. The content will be translated into JSOn and save as a CouchDB document.

resource.save(null);

Resulting document:

{
   "_id": "fc4dc3af46a4d5a2a3798819260008ea",
   "_rev": "1-3a14223e845eb306b1b43763b967b141",
   "eClass": "http://www.eclipselabs.org/emfjson/junit#//User",
   "userId": "1",
   "name": "John"
}

Note that when you set only one fragment to the Resource URI, it will create a new document in the corresponding database. After calling save, the Resource URI is updated with the ID of the newly created document. For example:

resource.getURI() -> http://127.0.0.1:5984/users/ee16fdb915274370e9976fc1fd00ad6f

CouchDB

Updating a Document

The particularity of CouchDB is that it provides a built-in mechanism to handle revisions. If you make changes to the objects contained in a Resource, and re-save it, it will create a new revision of the CouchDB document.

Modify a property of an object:

user.setName("John Smith");

Save the modified resource:

resource.save(null);

You should now notice the presence of different revisions for the corresponding document in the CouchDB Web interface. CouchDB

Clone this wiki locally