CouchDB – The Open Source NoSQL Database


CouchDB is a great example of forward-thinking technology that’s worth a look even if you’re not currently in need of a database solution. This article introduces you to CouchDB, showing you how to get started using this fascinating solution and even integrate it into your PHP website.

In a recent Developer.com article I introduced MongoDB, a NoSQL database which is experiencing widespread adoption within enterprises such as github and The New York Times. If you’re new to the technology, NoSQL is a generic term for a database which relies upon a key-value storage solution rather than a formally defined schema, with the goal of providing developers with increased flexibility, availability, and scalability not easily obtained with traditional relational databases.

Although among the most popular, MongoDB is just one of many open source NoSQL solutions in widespread use today. Another popular solution is CouchDB, which like MongoDB is such a great example of forward-thinking technology that it’s worth a look even if you’re not currently in need of a database solution! In this article I’ll introduce you to CouchDB, showing you how to get started using this fascinating solution and even integrate it into your PHP website.

Introducing CouchDB

Django developer Jacob Kaplan-Moss summed up CouchDB better than any other definition I’ve encountered so far, stating, “Django may be built for the Web, but CouchDB is built of the Web. I’ve never seen software that so completely embraces the philosophies behind HTTP.”

Kaplan defines CouchDB as being “built of the Web” because of its reliance upon native Web technologies such as JSON, HTTP, REST, and even server-side JavaScript. Written in fault-tolerant Erlang, and with a great deal of emphasis placed on scalability and replication, the CouchDB team has clearly taken great pains to create a database capable of meeting the modern-day requirements of Web developers.

You’ll interact with CouchDB data using HTTP’s request verbs, including DELETE, GET, POST, and PUT, using these requests to send and receive JSON-formatted data. This means it’s possible to use all of today’s mainstream programming languages in conjunction with CouchDB, including Java, PHP, Python, Perl, and Ruby. Later in this article I’ll show you just how easy it is to plug CouchDB into your PHP-driven website.

Installing CouchDB

CouchDB is supported on all of the major platforms. If you’re running a *nix-based system, then chances are quite good that you can install CouchDB via your distribution’s package manager. For instance, on Ubuntu installing CouchDB was as easy as using apt-get:

%>sudo apt-get install couchdb

If you’re running Windows, download the beta installer. Learn more about the Windows installation process on the CouchDB wiki.

You can find a comprehensive list of installation instructions on the CouchDB wiki.

Interacting with CouchDB

Once installed and configured, CouchDB will listen for requests on port 5984. Yet unlike a database such as MySQL (which incidentally runs on port 3306), remember that CouchDB is HTTP-driven, meaning you can contact the CouchDB server by opening a browser and pointing it to http://localhost:5984/ (presuming you installed CouchDB locally). Within the browser window you should see the following response:

{"couchdb":"Welcome","version":"0.10.0"}

You might recognize this response format as a simple JSON string which contains two key-value pairs. Having successfully contacted the server, let’s next create a database. To do this, you’ll use a PUT request. Because it’s not possible to send a PUT request from the browser address bar, we’ll use cURL. cURL is a command-line tool (and library) useful for transferring data using a variety of protocols. If you’re running any *nix-based system, it’s likely already installed. Windows users can download a version from here.

Once you’ve confirmed that cURL is installed, open up a terminal and execute the following command:

%>curl -X PUT http://localhost:5984/markets {"ok":true}

Yes that’s right, anybody who can access this URL can create a new database, as well as perform other administrative tasks. CouchDB does however support the ability to create administrator accounts and restrict access to administrative tasks. You can learn more about this topic here.

As indicated by the response, a database named markets was successfully created. We’ll use this database to store information about local food markets. Next let’s add a location (formatted for readability):

%>curl -X POST http://localhost:5984/markets --header 'Content-Type:
application/json' --data '{"title": "Westside Market", "address": "Corner of West 25th and Lorain", "city":
"Cleveland", "telephone": "(216) 664-3387"}' {"ok":true,"id":"6496a284bdf44af5e5399e26ce6b44ae","rev":"1
b14ca58947e2358f62774bf0cdeb27f0"}

In this example we added a new market, including its name, address, city, and telephone. But what if a particular farmer’s market didn’t specify a contact? The beauty of document-based databases is that you simply omit it:

%>curl -X POST http://localhost:5984/markets --header 'Content-Type:
application/json' --data '{"title": "Short North Farmer%22s Market", "address": "59 Spruce Street", "city": "Columbus"}'
{"ok":true,"id":"9fd60e85033f0cce782e3a967a86285d","rev":"1-d1b4c0f0e9ceddfb6d5dc018eb14da51"}

In both examples notice how an identifier was returned. You can use these identifiers to uniquely retrieve each row (formatted for readability):

%>curl -X GET http://localhost:5984/markets/6496a284bdf44af5e5399e26ce6b44ae 
{"_id":"6496a284bdf44af5e5399e26ce6b44ae", "_rev":"1-b14ca58947e2358f62774bf0cdeb27f0",
"title":"Westside Market", "address":"Corner of West 25th and Lorain", "city":"Cleveland", "telephone":"(216) 664-3387"}

Incidentally, CouchDB is bundled with a simple Web-based interface called Futon which you can use to peruse and manage your databases. To access this interface, navigate to http://localhost:5984/_utils/ from within your browser.

While using cURL and Futon is fine for getting acquainted with CouchDB, you’ll likely soon want to begin interacting with the database using a programming language such as PHP. I’ll show you how to do this in the next section.

Talking to CouchDB with PHP

Although PHP doesn’t yet offer a native CouchDB extension, several third-party libraries are available, including PHPillow (as in couch pillow, get it?). To use PHPillow you’ll need to be running PHP 5.2+. Presuming you meet this requirement, head over to the PHPillow download page to retrieve the latest version. Download and uncompress the code and place the directory somewhere within PHP’s include path.

Next create a class which we’ll use to represent the markets. This class should extend PHPillow’s abstract phpillowDocument class:

class marketDocument extends phpillowDocument { protected static $type = "market";
protected $requiredProperties = array ( 'title', 'address', 'city' ); public function __construct()
{ $this->properties = array ( 'title' => new phpillowStringValidator(), 'address' => new phpillowStringValidator(), 'city' =>
new phpillowStringValidator() ); parent::__construct(); } protected function generateId() { return $this->stringToId( $this->storage->title );
} protected function getType() { return self::$type; } }

This example defines several required class structures you’ll need to create when using PHPillow. The $type attribute is used by PHPillow to uniquely identify the class. The $requiredProperties array defines the three pieces of data which must accompany each document. The class constructor uses PHPillow’s native validators to ensure that the document data meets certain guidelines. The generateId() method is used to generate a unique ID based on some unique piece of data within each document, in this case the market name.

With the class in place, you can use it to add a new market:

phpillowConnection::createInstance('localhost', 5984); 
phpillowConnection::setDatabase('markets'); $market = new marketDocument(); $market->title
= "Andersonville Market"; $market->address = "Berwyn between Clark and Ashland"; $market->city = "Chicago";
try { $market->save(); } catch (Exception $e) { die($e); } echo $market->_id;

Executing this example will save the new market, and return its unique ID:

market-andersonville_market

Notice how the type is used as a prefix to the unique title. You can use this unique ID to retrieve the document:

$market = new marketDocument(); $market->fetchById('market-andersonville_market'); echo $market->address;

Executing this snippet produces the address:

Berwyn between Clark and Ashland

Conclusion

CouchDB is another best-of-breed solution in the cutting-edge NoSQL database market. Sporting a modern architecture, backing by the Apache Software Foundation, and active support within all of the popular programming language communities, CouchDB is well worth a look if you’re interested in migrating to a document-oriented database solution. Are you using CouchDB or another NoSQL solution? Tell us about it in the comments!

About the Author

Jason Gilmore is founder of the publishing and consulting firm WJGilmore.com. He is the author of several popular books “Easy PHP Websites with the Zend Framework”, “Easy PayPal with PHP”, and “Beginning PHP and MySQL, Third Edition”. Follow him on Twitter at @wjgilmore.

Get the Free Newsletter!

Subscribe to Cloud Insider for top news, trends & analysis

Latest Articles