How to use CouchDB as Cache Database in your app (2/3)

Basic usage and Rails configuration

Go to part 1: What is CouchDB.
Go to part 3: Redirect to CouchDB records and making backups

Getting Started and basic usage

After installing and checking that our CouchDB installation is up and running we are going to explain the basic usage of the http query requests and how to configure a Rails application to use CouchDB database.

To start querying our database we need a command line http client. On this tutorial we will use curl. To be sure that the curl command is installed on our system we must type the following command in our terminal:

curl --version

and the response should be something like:

curl 7.47.0 (x86_64-pc-linux-gnu) libcurl/7.47.0 GnuTLS/3.4.10 zlib/1.2.8 libidn/1.32 librtmp/2.3
Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtmp rtsp smb smbs smtp smtps telnet tftp
Features: AsynchDNS IDN IPv6 Largefile GSS-API Kerberos SPNEGO NTLM NTLM_WB SSL libz TLS-SRP UnixSockets

The use of curl is out of the scope of this post. For a complete documentation you could visit Curl Documentation Page.

First let’s get a list of all existing databases:

curl -X GET http://127.0.0.1:5984/_all_dbs

The response should look like:

["_replicator","_users"]

These are the default databases created by the CouchDB installation process. Let’s create our first database:

curl -X PUT http://127.0.0.1:5984/demo_database

CouchDB will reply with:

{"ok":true}

Retrieving the list of databases again shows some useful results this time:

curl -X GET http://127.0.0.1:5984/_all_dbs
["demo_database"]

Let’s create a second database:

curl -X PUT http://127.0.0.1:5984/demo_database_to_delete

If we get the list of all databases again we will get something like this:

curl -X GET http://127.0.0.1:5984/_all_dbs
["demo_database", "demo_database_to_delete"]

To round things off, let’s delete the second database:

curl -X DELETE http://127.0.0.1:5984/demo_database_to_delete

CouchDB will reply with:

{"ok":true}

The list of databases is now the same as it was before:

curl -X GET http://127.0.0.1:5984/_all_dbs
["demo_database"]

Let’s create a new document in our demo_database with the following command:

curl -X PUT http://127.0.0.1:5984/demo_database/6e1295ed6c29495e54cc05947f18c8af -d '{"title":"There is Nothing Left to Lose","artist":"Foo Fighters"}'

and CouchDB should respond something similar to this:

{"ok":true,"id":"6e1295ed6c29495e54cc05947f18c8af","rev":"1-2902191555"}

where the first part is an acknowledgment that the document was saved.

Although the curl command seems difficult is simple when you break it down in sections. First, -X PUT tells curl to make a HTTP PUT request followed by the URL that specifies your CouchDB IP address and port. The resource part of the URL /demo_database/6e1295ed6c29495e54cc05947f18c8af specifies the location of a document inside our demo_database. The strange combination of numbers and characters is an UUID that identifies this document in an unique way in your database. Finally, the -d flag tells curl to use the following string as the body for the PUT request. The string is a simple JSON structure including title and artist attributes with their respective values.

Let’s check if CouchDB really saved our document:

curl -X GET http://127.0.0.1:5984/demo_database/6e1295ed6c29495e54cc05947f18c8af

CouchDB replies:

{"_id":"6e1295ed6c29495e54cc05947f18c8af","_rev":"1-2902191555","title":"There is Nothing Left to Lose","artist":"Foo Fighters"}

As you can see there is a pattern on this queries. Everything in CouchDB has an address, an URI, and you use the different HTTP methods to operate on these URIs.

This are simple examples of the http queries that you can use on CouchDB. If you want to get a detailed list of all possible queries you can check the CouchDB API documentation. If your prefer to use a web interface to interact with your CouchDB database I recommend you use Fauxton that is installed by default on your server.


Configuring Rails to use CouchDB

Know let’s configure our Rails application to use a CouchDB database. First we need to install the appropriate gem. On this example will be using Couchrest Model.

Install

If you wish to install the gem globally on your system type the following in your commandline:

sudo gem install couchrest_model

In case you are using Bundler add the following line to your project’s Gemfile:

gem couchrest_model and type bundle install on your terminal.

Configuration

To properly configured the connection with your database add config/couchdb.yml file to your Rails root directory and setup your CouchDB database in a Rails-like way:

development:
protocol: 'http'
host: localhost
port: 5984
prefix: demo
suffix: database
username: user
password: password

Note that the name of the database is either just the prefix and suffix combined or the prefix plus any text you specify using use_database method in your models with the suffix on the end.

The example config above for example would use a database called demo_database. Here’s an example using the use_database call:

class Project < CouchRest::Model::Base
use_database 'sample'
end
# The database object would be provided as:
Project.database #=> "https://test:user@sample.cloudant.com:443/project_sample_test"

Generators

Before using Couchrest Model we need to tell Rails to configure the newly installed gem with the settings we just provided:

$ rails generate couchrest_model:config

Know we can generate a model and start using Couchrest:

rails generate model album --orm=couchrest_model

General usage

Let’s define a model by creating app/models/album.rb:

require 'couchrest_model'

class Album < CouchRest::Model::Base

property :title, String
property :artist, String
property :year, Integer, :default => 1900

timestamps!

design do
view :by_title
view :by_artist_and_year
end

end

First we are requiring couchrest_model so it is possible to define our class model with inheritance from CouchRest::Model::Base.

After that we are defining the properties of the model with the corresponding data type for each one. With timestamps! we are telling the model to create autogenerated fields for created_at and updated_at.

Finally we are indicating that the model will have two views in CouchDB to query documents by title and by artist and year.

Let’s see some examples:

@album = Album.new(:title => 'Master of Puppets', :artist => 'Metallica', :year => 1986)

@album.new? # true
@album.save

@album['title'] # "Master of Puppets"


# Fetching by views, loading all results into memory
albums = Album.by_title.all
album.first.title # "Master of Puppets"

# Streaming views, for efficient memory usage
Album.by_name.all do |cat|
puts album.title
end
# Fetching views that fulfill multiple conditions
album = Album.by_artist_and_year.key(['Metallica', 1986]).first
album.title #"Master of Puppets"
# Be careful with this
album.destroy # Delete the album from the CouchDB database

As you can see the use of Couchrest Model gem is pretty straight forward. To know more please visit the Github page or the Official Documentation page.


Conclussion

In this post we saw the basic usage of curl to make http queries to a CouchDB database. We installed the Couchrest Model gem on our Rails project so we can define models and query them using Ruby language in our controllers. On the next part we will see an example of how we redirect the user request to get from our CouchDB Cache Database instead of our main database. Also we will discuss how to backup our databases using bash scripts or replication.

Author: Eng. Alberto Aragón Alvarez

Like what you read? Give Altura Soluciones a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.