Introduction to CouchDB

Photo by RODNAE Productions: https://www.pexels.com/photo/rotary-phone-on-red-couch-9086927/

Recently I was working with CouchDB and wanted to learn the fundamentals so I thought of writing
a blog post about an introduction to CouchDB to share with you all. This post will cover

- A brief introduction.
- Features.
- Getting started.

Introduction


Apache CouchDB is an Open source NoSQL database initially released in 2005, It was implemented using
ErlangLike many other NoSQL databases, it uses JSON to store data and you can transform your data
using javascript.

Features and technical overview


Couch has some cool features which beat the other NoSQL competitors.  

HTTP API


  • Couch provides RESTful API to access your databases from anywhere and CRUD operations to add, edit, delete and read your data which makes CouchDB flexible. With the emergence of microservices architecture, developers find it easy to use the REST API support in the database itself. 

Document Storage


  • Documents are the primary unit of data in CouchDB and consist of any number of fields and attachments Support multiple data types and there is no set limit to text size or element count.
  • The document update model is lockless and optimistic if multiple clients update the same document, the client will receive a conflict error on save. To resolve the conflicting error, the client needs to pull the latest document version and edit and update it to apply the change.
  • Couch guarantees that there will never be partially saved or edited documents.

ACID properties


  • Couch support all the ACID (atomic, consistent, isolated, durable) properties.
  • CouchDB uses MVCC (Multi-Version Concurrency Control) to manage access to databases concurrently. 

Compaction


  • Out-of-the-box support for compaction, On schedule or when the database file exceeds the wasted space it ran a compaction process and cloned the active data to a new file, and disregards the old file. This happens while keeping the database online all the time. This makes CouchDB an efficient data store.

Replication



Offline Support


  • CouchDB can collect your local data and synchronize data to the cloud once your device is online, your devices could be mobile devices or browsers. 

CouchDB Views



Hands-On


Let's try to get hands-on to get familiarized with the basics of CouchDB. To Install couch DB, you may follow the instructions per your operating system and preference. 


I followed the easiest way which is using docker-compose to install the CouchDB to just play around.
You can follow this approach if you like. Use the below docker-compose file.

To start the CouchDB go to the docker-compose file location and run

docker-compose up -d

Now your CouchDB is running on port 5984, you can log in to the UI from http://localhost:5984/_utils
Once you navigate to the URL you will direct to a login screen, there use the credentials we registered in our docker-compose file. Once logged in you can verify your couch installation by navigating to Verify tab and in the side panel then clicking the Verify Installation button.


Setting Up


  • For testing purposes, we only need a single node, so go to the Setup tab and click on the Configure a Single Node button.


Creating a database and adding documents.


  • Navigate to the Databases tab and let's create a database using the create database button. 
  • Once you create a database you can add documents. 


  • You can edit, and delete or clone the document you created. Create some documents for yourself to familiarize yourself with the flow.

Creating views


  • You have the create view option in the + sign in both All Documents and Design Documents buttons. Click it and create a new view. As you can remember we can customize our data presentation using view. 
  • Data is manipulated using a javascript map and reduce functions, reduce is optional. For this, I have extracted the name, email, and mobile_no from our documents.


  • Once you save the View, you will get a key-value pair, where the key is the doc id, since we used doc._id as the first parameter in the emit function and the manipulated data as the value. You can view this in the metadata section and in the JSON view in the specific view.


I hope that we have covered some basics to get started with, now let's look at the REST APIs.


Using REST APIs


  • As we discussed CouchDB has exposed REST APIs to deal with CouchDB, let's look at some basic operations we can do.
  • For most of the APIs, you need to pass the server admin credentials in the URL, you can create a server admin from the Your Account tab in the UI.
  • You may use a tool of choice to execute the requests like curls or postman.
  • This will be the sample format of a request

         curl --location --request GET 'http://username:password@localhost:5984/_all_dbs'

Eg: Get all databases

         curl --location --request GET 'http://admin:root@localhost:5984/'_all_dbs

 CRUD Operations 


1. Create a document

Request:

curl -i --location --request PUT 'http://admin:root@localhost:5984/employee/b0019232e3f54713a4fc9cb488d3890f' \
--header 'Content-Type: application/json' \
--data-raw '{
"name":"Saul Goodman",
"email":"saul@walterwhite.com",
"mobile_no":"+5051485464",
"address":{
"street":"Montgomery Blvd NE",
"city":"Albuquerque",
"zipCode":87101
}
}'

Response:

{"ok":true,"id":"b0019232e3f54713a4fc9cb488d3890f","rev":"1-ee0ea147642f199bea595725cd8b521b"}

2. Get Documents

Request, Here the last parameter is the id that we used to create the document.

curl http://admin:root@localhost:5984/employee/b0019232e3f54713a4fc9cb488d3890f

Response:

{
"_id":"b0019232e3f54713a4fc9cb488d3890f",
"_rev":"1-ee0ea147642f199bea595725cd8b521b",
"name":"Saul Goodman",
"email":"saul@walterwhite.com",
"mobile_no":"+5051485464",
"address":{
"street":"Montgomery Blvd NE",
"city":"Albuquerque",
"zipCode":87101
}
}

To fetch all the documents, a better way is to use a view, for example 

curl http://admin:root@localhost:5984/employee/_design/personalView/_view/pdetailsName\?include_docs\=true

Response

This will return all the docs as per the view you created.

3. Update a document.

To update the document you need to send the _rev with the payload which we can retrieve from the GET request, let's update the document which we created earlier. I'm only going to update the mobile_no and please note that my _rev has changed because I did some edits.

Request:

curl -i --location --request PUT 'http://admin:root@localhost:5984/employee/b0019232e3f54713a4fc9cb488d3890f' \
--header 'Content-Type: application/json' \
--data-raw '{
"_rev": "6-49edc757dea50729c42c00ad18a11605",
"name":"Saul Goodman",
"email":"saul@walterwhite.com",
"mobile_no":"+505148666",
"address":{
"street":"Montgomery Blvd NE",
"city":"Albuquerque",
"zipCode":87101
}
}'

Response:

{"ok":true,"id":"b0019232e3f54713a4fc9cb488d3890f","rev":"7-d8e027ac38e5b52aed5aabf7d8029453"}

4. Delete a document.

You just need to send the _rev as the last request parameter.

Request:

curl -i --location --request DELETE 'http://admin:root@localhost:5984/employee/b0019232e3f54713a4fc9cb488d3890f/?rev=7-d8e027ac38e5b52aed5aabf7d8029453'

Response:

{"ok":true,"id":"b0019232e3f54713a4fc9cb488d3890f","rev":"8-6ea7ed02e1c91473853c295616f01c79"}

If you used docker-compose, to stop the container when you are done just run
docker-compose stop in the terminal where the docker-compose file is located.

That's pretty much it that I wanted to share with you all. I believe this will help you to start exploring CouchDB. I suggest you read through the CouchDB documentation, you will learn many more things other than couch-related stuff. I will write a post explaining how we can use CouchDB via code. Hope you learn something from it. Now it's time to relax ðŸ˜Ž

References:


Comments