Conflict Resolution

When replicating, you will inevitably run into document update conflicts. This can happen when a document with the same ID has been updated independently on two or more CouchDB nodes. To handle document update conflicts, you will need to create a view to find conflicts. Here is the Map function that will let us find conflicts:

function(doc) {
   if (doc._conflicts) {
       for (var i in doc._conflicts) {
           emit(doc._conflicts[i]);
       }
   }
}

Let’s save this to a design document:

curl -X PUT http://localhost:5984/catalog-a/_design/default -d \
'{
   "_id": "_design/default",
   "language": "javascript",
   "views": {
       "conflicts": {
           "map":
"function(doc) {
   if (doc._conflicts) {
       for (var i in doc._conflicts) {
           emit(doc._conflicts[i]);
       }
   }
}"       }
   }
}'

The response:

{
   "ok":true,
   "id":"_design/default",
   "rev":"1-05df67108309b2783233f27ffff31c59"
}

Now let’s create a conflict. First, create the following document within the catalog-a database:

curl -X PUT http://localhost:5984/catalog-a/978-0-596-80579-1 \
-H "Content-Type: application/json" \
-d '{
   "title":"Building iPhone Apps with HTML, CSS, and JavaScript",
}'

The response:

{
   "ok":true,
   "id":"978-0-596-80579-1",
   "rev":"1-8e68b2b2f14a81190889dab9d04481d2"
}

Next, create the same document within the catalog-b database, but with a slightly different title (the comma is missing after “CSS”):

curl -X PUT http://localhost:5984/catalog-b/978-0-596-80579-1 \ -H "Content-Type: application/json" \ -d '{ "title":"Building iPhone Apps with HTML, CSS and JavaScript", ...

Get Scaling CouchDB now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.