Shahzad Bhatti Welcome to my ramblings and rants!

October 14, 2009

Querying and Indexing CouchDB documents using Lucene

Filed under: Uncategorized — admin @ 9:32 pm

I have been playing with CouchDB lately and was looking for a way to index documents stored in the CouchDB. So, I started an open source project DocuSearch. It includes both POJO based and REST based services for indexing and searching that are hosted in Jetty server.

Getting Started

To get started download the source using:

 svn checkout http://docusearch.googlecode.com/svn/trunk/ docusearch-read-only  
 or
 git clone git://github.com/bhatti/DocuSearch.git
 

You will need to install Java 1.6, Maven 2.0+ and CouchDB before start using the services. On Mac, you can install CouchDB via:

 sudo port install couchdb
 

Then manually start the CouchDB using

 sudo /opt/local/bin/couchdb
 

You can verify if CouchDB is running using http://localhost:5984/_utils/index.html.

Building

Type “mvn” to build the project. Maven will download a bunch of files that may take a few minutes and will cache those locally and will then proceed to compile, test and build war file.

Populating Database

You are free to choose your favorite way to add or import data into CouchDB, though the DocuSearch includes some ETL programs to add comma or tab delimited data into CouchDB. For example, let say you want to find authorized e-file providers for IRS, so you download some data from IRS that has following format:

 business_name,street_address_1,street_address_2,city,state,zip,zip_4,contact_first_name,contact_middle_name,contact_last_name,phone,flag1,flag2,flag3,flag4
 

You can import it to the couchdb using

 mvn exec:java -Dexec.mainClass="com.plexobject.docusearch.etl.DocumentLoader" \
 -Dexec.args="efile_providers data/wa.txt none business_name,street_address_1,street_address_2,city,state,zip,zip_4,contact_first_name,contact_middle_name,contact_last_name,phone"
 

Which takes following arguments:

  • name-of-database, e.g. efile_providers
  • name of comma delimited file, e.g. data/wa.txt
  • id-column or none if database ids will automatically be generated
  • comma-delimited list of fields to be imported

Once the data is loaded, you can create Lucene index, but before that you will have to specify the index policy, which is just another CouchDB document. The index policy specifies fields to be indexed, whether they should be stored in index, score and boost values. These policy configurations are stored in the_config database and you can add the policy using:

 curl -X PUT http://127.0.0.1:5984/the_config/index_policy_for_efile_providers -d \
 '{"_id":"index_policy_for_efile_providers","dbname":"the_config","score":0,"boost":0,"fields":[{"name":"business_name", "storeInIndex":"true"},{"name":"street_address_1"},{"name":"city"},{"name":"zip"},{"name":"contact_first_name"},{"name":"contact_last_name"}]}'
 

It will return

 {"ok":true,"id":"index_policy_for_efile_providers","rev":"1-0fd2f5b2e2012f898df677c68daf4592"}
 

Note that you will need to pass the “_rev” parameter if you need to update the index policy. Later, you can retrieve the policy using:

 curl http://localhost:5984/the_config/index_policy_for_efile_providers
 

Now you are ready to build the index but let’s first start the Jetty with the REST based services via

 mvn jetty:run-war
 

Now hop on to browser and point to

 http://localhost:8080
 

Finally, you can use curl to build the index via:

 curl -vX POST http://localhost:8080/api/index/primary/efile_providers
 

Before you can query, you will have to specify query policy that is also stored in CouchDB and specifies list of fields that are searched, e.g.

 curl -X PUT http://127.0.0.1:5984/the_config/query_policy_for_efile_providers -d \ '{"_id":"query_policy_for_efile_providers","dynamo":"the_config","fields":[{"name":"efile_providers.business_name", "boost":2},{"name":"efile_providers.street_address_1"},{"name":"efile_providers.city"},{"name":"efile_providers.zip"},{"name":"efile_providers.contact_first_name"},{"name":"efile_providers.contact_last_name"}]}'
 

Which will return

 {"ok":true,"id":"query_policy_for_efile_providers","rev":"1-618703c1fd66996f23b89c4414dd0842"}
 

Again, you will need to pass “_rev” parameter when updating the query policy. Next you can search contents of the index via:

 curl "http://localhost:8080/api/search/efile_providers?keywords=mike"
 

Which will return

 {"suggestions":[],"keywords":"mike","start":0,"limit":0,"totalHits":7,"docs":[{"_id":"0352d18145532a05714bfec2e1e649dd","dbname":"efile_providers","indexDate":"20091121","doc":"53","score":"0.0","owner":"*","efile_providers.business_name":"Mr Tax Man"},{"_id":"062d548eb394db3534782c5b6ded0529","dbname":"efile_providers","indexDate":"20091121","doc":"96","score":"0.0","owner":"*","efile_providers.business_name":"Liberty Tax Service"},{"_id":"1ddc6006a2315dd0b0119c0dbc22c1a7","dbname":"efile_providers","indexDate":"20091121","doc":"450","score":"0.0","owner":"*","efile_providers.business_name":"1040 PLUS INC"},{"_id":"3621cc7edde5f191bcc5f3a41160f61e","dbname":"efile_providers","indexDate":"20091121","doc":"793","score":"0.0","owner":"*","efile_providers.business_name":"MIKE A PASSECK CPA"},{"_id":"37a2a152ff120ac293ea67daac1a11aa","dbname":"efile_providers","indexDate":"20091121","doc":"811","score":"0.0","owner":"*","efile_providers.business_name":"Liberty Tax Service"},{"_id":"be0fd60800b9eed6d418601f8cba06f3","dbname":"efile_providers","indexDate":"20091121","doc":"2856","score":"0.0","owner":"*","efile_providers.business_name":"Liberty Tax Service"},{"_id":"dfa948236e87d0c6ba90c612cb166635","dbname":"efile_providers","indexDate":"20091121","doc":"3395","score":"0.0","owner":"*","efile_providers.business_name":"MIKE FOLEYS TAX SERVICE"}]}
 

This query functionality can also be tested through a simple html based interface by just pointing your browser to http://localhost:8080/, e.g.

The index stores id of the document that is indexed so you can also retrieve details of each link using

 http://localhost:8080/api/storage/efile_providers/0352d18145532a05714bfec2e1e649dd
 

This feature can be tested from HTML interface by clicking on details link, e.g.

You can also debug why certain results are showing up using following API

 http://localhost:8080/api/search/explain/efile_providers?keywords=mike
 

This feature can be tested from HTML interface by clicking on explain button, e.g.

Next, you can also find top terms used in the index using:

 http://localhost:8080/api/search/rank/efile_providers?limit=1000
 

Again, this feature can be tested from HTML interface by clicking on top terms button, e.g.

You can also find similar searches for a particular search using

 http://localhost:8080/api/search/similar/efile_providers?externalId=37a2a152ff120ac293ea67daac1a11aa&luceneId=811&detailedResults=true
 

Which will return

 {"externalId":"37a2a152ff120ac293ea67daac1a11aa","luceneId":811,"start":0,"limit":0,"totalHits":973,"docs":[{"zip":"98107","phone":"206\/782-2772","contact_first_name":"TOR","street_address_2":"","street_address_1":"5919 NW 15TH AVE","state":"WA","city":"SEATTLE","_rev":"1-6f14e2e9d2092e63173002cd95785963","business_name":"LIBERTY TAX SERVICE","_id":"00684037657ef8960ede2f155339420e","contact_middle_name":"","zip_4":"","dbname":"efile_providers","contact_last_name":"SLINNING"},{"zip":"98118","phone":"206\/850-0505","contact_first_name":"ANDREW","street_address_2":"","street_address_1":"5021 SOUTH BARTON","state":"WA","city":"SEATTLE","_rev":"1-f910f4736db188d05f24751a68070b86","business_name":"H&A TAX PREPARATION SVCS","_id":"00b6c05dd24c30c4740b7aa1257ef308","contact_middle_name":"H","zip_4":"5336","dbname":"efile_providers","contact_last_name":"HODGE"},{"zip":"98682","phone":"360\/891-6701","contact_first_name":"MARILYN","street_address_2":"","street_address_1":"5101 NE 121ST AVE #50","state":"WA","city":"VANCOUVER","_rev":"1-6ab3f77b03eee2c529f910c559236eb3","business_name":"AFFORDABLE BOOKKEEPING & TAX SERVIC","_id":"00e35b6bbfbfe68db8e962bc41ec6c99","contact_middle_name":"C","zip_4":"","dbname":"efile_providers","contact_last_name":"BOON"},{"zip":"98406","phone":"206\/322-2226","contact_first_name":"MAN","street_address_2":"","street_address_1":"602 6TH AVE","state":"WA","city":"TACOMA","_rev":"1-4efeefbdaadaf9dde2a49f7246f884b5","business_name":"INSTANT TAX PRO","_id":"00fe1df22fe5731e01515cada787efd2","contact_middle_name":"V","zip_4":"","dbname":"efile_providers","contact_last_name":"SAM"},{"zip":"98208","phone":"425\/338-0118","contact_first_name":"STEPHEN","street_address_2":"","street_address_1":"3615 100TH ST SE","state":"WA","city":"EVERETT","_rev":"1-381ea9171f405bf40f78597a91730588","business_name":"ADSUM TAX & BOOKKEEPING LLC","_id":"014548ee3e23e5d56d4521b76de8434a","contact_middle_name":"D","zip_4":"","dbname":"efile_providers","contact_last_name":"TANGEN"},{"zip":"99116","phone":"509\/633-3829","contact_first_name":"RICHARD","street_address_2":"","street_address_1":"102 STEVENS","state":"WA","city":"COULEE DAM","_rev":"1-1b767048def4829db756f04014733681","business_name":"MEYER TAX SERVICE","_id":"016a700252b54fc170ffc0f69c60ce93","contact_middle_name":"W","zip_4":"","dbname":"efile_providers","contact_last_name":"AVEY"},{"zip":"98391","phone":"253\/862-5573","contact_first_name":"Tim","street_address_2":"","street_address_1":"20616 SR 410 E","state":"WA","city":"Bonney Lake","_rev":"1-5b6ee0d167743b1679c8c3f84f16d78b","business_name":"Barrans Tax Service","_id":"017a48b555806eda9f7999b426b00d14","contact_middle_name":"","zip_4":"","dbname":"efile_providers","contact_last_name":"Barrans"},{"zip":"98503","phone":"360\/456-5084","contact_first_name":"THOMAS","street_address_2":"","street_address_1":"4440 PACIFIC AVE SE","state":"WA","city":"LACEY","_rev":"1-dcbfcb5c112e3ef1e109f7bbfd410e9a","business_name":"TAX CENTERS OF AMERICA","_id":"01a024fe186a0df2f313191a951dbb1c","contact_middle_name":"B","zip_4":"","dbname":"efile_providers","contact_last_name":"OTT"},{"zip":"WA","phone":"Stevenson","contact_first_name":"","street_address_2":"924 West S Circle","street_address_1":"LLC","state":"Washougal","city":"","_rev":"1-9a7678e5c46651998fb7c0c83c9018b1","business_name":"Columbia Tax","_id":"01aa9791195e915093ee207518e6bf34","contact_middle_name":"Gina","zip_4":"98671","dbname":"efile_providers","contact_last_name":"A"},{"zip":"98188","phone":"303\/888-1040","contact_first_name":"CARL","street_address_2":"","street_address_1":"17600 PACIFIC HWY S","state":"WA","city":"SEATTLE","_rev":"1-976ac1c5ba46f59a42b57786af76e9b2","business_name":"NEXT DAY TAX CASH","_id":"01b21a8653b83789b561040887be7a28","contact_middle_name":"","zip_4":"","dbname":"efile_providers","contact_last_name":"PALMER"},{"zip":"98032","phone":"253\/852-6182","contact_first_name":"TOM","street_address_2":"# A-148","street_address_1":"1819 CENTRAL AVE S","state":"WA","city":"KENT","_rev":"1-1d0a9dbc409944bfc4618f598541a97f","business_name":"TAX GALLERY\/ TOM COKE ASSOCIATES","_id":"02051caa9f2faa9ca8386792c9653ff6","contact_middle_name":"C","zip_4":"","dbname":"efile_providers","contact_last_name":"ARMON"},{"zip":"98686","phone":"702\/320-0727","contact_first_name":"ARMOGAST","street_address_2":"","street_address_1":"14605 NE 20TH AVE","state":"WA","city":"VANCOUVER","_rev":"1-adf4be610b7fa43794d4d7dd3f8dc7de","business_name":"SUPREME BOOKKEEPING & TAX LLC.","_id":"0220b0609b83dd5621a90d9f7fe342ca","contact_middle_name":"J","zip_4":"","dbname":"efile_providers","contact_last_name":"MWASHIGHADI"},{"zip":"98665","phone":"360\/896-9897","contact_first_name":"GERALD","street_address_2":"","street_address_1":"7700 HWY 99","state":"WA","city":"VANCOUVER","_rev":"1-78234fab75e3e44d79648dab756a7791","business_name":"JACKSON HEWITT TAX SERVICE","_id":"02c2c5983ca8b4a00173dca208cc86de","contact_middle_name":"D","zip_4":"","dbname":"efile_providers","contact_last_name":"BREUNIG"},{"zip":"98531","phone":"360\/556-4906","contact_first_name":"David","street_address_2":"SUITE A","street_address_1":"417 W. MAIN ST.","state":"WA","city":"CENTRALIA","_rev":"1-fcb886c533f0a223f835397a0d5cf773","business_name":"Liberty Tax Service","_id":"02c466c8097ee00a1ae2d27aafd808aa","contact_middle_name":"C","zip_4":"","dbname":"efile_providers","contact_last_name":"Dunsmore"},{"zip":"98626","phone":"909\/849-1174","contact_first_name":"CINDY","street_address_2":"","street_address_1":"2640 ROBERT CT","state":"WA","city":"Kelso","_rev":"1-5513b1057c7882a7657a79a3e888b21d","business_name":"THE TAX WARD","_id":"032a14eaca19a1548364609fd480a1b9","contact_middle_name":"J","zip_4":"","dbname":"efile_providers","contact_last_name":"WARD"},{"zip":"98036","phone":"425\/774-6633","contact_first_name":"Mike","street_address_2":"","street_address_1":"20015 HIGHWAY 99","state":"WA","city":"LYNNWOOD","_rev":"1-d7f17073757afa70e869e543099a7bf5","business_name":"Mr Tax Man","_id":"0352d18145532a05714bfec2e1e649dd","contact_middle_name":"C","zip_4":"6073","dbname":"efile_providers","contact_last_name":"McKinnon"},{"zip":"98284","phone":"360\/595-9138","contact_first_name":"LAURA","street_address_2":"","street_address_1":"765 SUMERSET WAY","state":"WA","city":"SEDRO WOOLLEY","_rev":"1-b2ebc210bbf481c2ed37751a45a2249e","business_name":"CAIN LAKE TAX SERVICE","_id":"03cc2bcb150f981519a8d93093a015ca","contact_middle_name":"L","zip_4":"","dbname":"efile_providers","contact_last_name":"COZZA"},{"zip":"99350","phone":"509\/786-1269","contact_first_name":"ERNEST","street_address_2":"","street_address_1":"1002 LILLIAN","state":"WA","city":"PROSSER","_rev":"1-cd626358950c19bd2519859fbd50bbce","business_name":"E & R TAX SERVICE","_id":"03f620e0ae8ac148af79cb7848c3bf41","contact_middle_name":"W","zip_4":"","dbname":"efile_providers","contact_last_name":"TROEMEL"},{"zip":"99301","phone":"509\/851-8808","contact_first_name":"Aaron","street_address_2":"SUITE E","street_address_1":"5024 NORTH ROAD 68","state":"WA","city":"PASCO","_rev":"1-e9c9843292f9233f46e07628105ee72c","business_name":"Liberty Tax Service of West Pasco","_id":"03fe45d715110d0aa2d3022bbe7325e7","contact_middle_name":"J","zip_4":"","dbname":"efile_providers","contact_last_name":"Welles"},{"zip":"98329","phone":"253\/884-3566","contact_first_name":"ROY","street_address_2":"","street_address_1":"13215 139TH AVE KPN","state":"WA","city":"GIG HARBOR","_rev":"1-70d070d37c72fb13b9162ba4523ab70f","business_name":"MYR-MAR ACCOUNTING SERVICE INC","_id":"040ab87550b5a4a200c97d2e6a6b96a7","contact_middle_name":"M","zip_4":"","dbname":"efile_providers","contact_last_name":"KEIZUR"}]}
 

This feature can be tested from HTML interface by clicking on similar link, e.g.

Conclusion

DocuSearch makes it easy to query documents on CouchDB, however I have also started adding support for Berkley DB if you choose to use it. I found CouchDB wastes a lot of space and is a bit slow so that may be alternative option for some. I also plan to add ngrams and stem based analyzers to create better search experience. I also welcome you to join the project. You can add yourself to http://code.google.com/p/docusearch/ or http://github.com/bhatti/DocuSearch/ project(s) and start contributing.

September 21, 2009

Installing Ubuntu Remix and Troubleshooting Network connections

Filed under: Computing — admin @ 10:00 am

I recently ordered ASUS Eeee PC 1005HA netbook that actually got lost in mail and had to reorder. Anyway, I finally received it this weekend and it comes with Windows XP that I decided to replace with Ubuntu. Though, there is a special distribution of Ubuntu called Remix or UNR, but support of netbooks on Ubuntu is still work in progress so it took longer than I expected. Here are the steps I went through to install and setup UNR on my ASUS netbook:

Download Ubuntu Remix

This was easy, I downloaded UNR from http://www.ubuntu.com/GetUbuntu/download-netbook and saved img file on my local netbook (which was running XP at that time).

Download USB Imager

Then, I downloaded USB Disk Imager for windows.

Creating UNR Image

After downloading imager, I opened the application, inserted my USB drive and copied the image, so far so good.

Changing BIOS to boot from USB

The ASUS reboots automatically from hard disk so I had to change the BIOS settings. I shutdown
the machine completely, then started while holding F2. It brought up BIOS settings and I changed the Boot sequence to boot from USB and then saved the settings with F10.

Installing UNR

After rebooting, the UNR loaded from the USB. First, I played without installing and figured out quickly that network isn’t working. I decided to install the UNR despite these issues. I allocated half of disk space about 70G to Linux and left Windows partition alone in case I fail. I then allocated swap space and then proceeded to install, which was fairly standard. After installation, I rebooted the machine and the GRUB loader showed me both Windows and UNR options.

Troubleshooting Network

Now, the fun started. Neither my wired nor wireless network was working. I found a number of forums with similar problems. I tried

 iwconfig
 iwlist scan
 lsmod
 

to see what’s installed and available but didn’t see the drivers. Also, “dmesg” wasn’t helpful and

  sudo /etc/init.d/networking restart
 

didn’t help either. I then typed

 lspci
 

Which showed

 02:00.0 Network controller: Atheros Communications Inc. AR9285 Wireless Network Adapter (PCI-Express) (rev 01)
 

I then switched to my Mac and I then looked for driver of AR9285. I found a good resource http://partner.atheros.com/Drivers.aspx and downloaded Linux driver and then copied to another USB drive.
I built the driver with

 tar -xzf 
 cd src
 make 
 sudo make install
 sudo insmod atl1e.ko
 

After rebooting, it fixed the wired network and I could then use the wired network to continue troubleshooting. I tried following instructions from http://wireless.kernel.org/en/users/Download, which suggested

 sudo apt-get install linux-backports-modules-jaunty
 

But it didn’t work for me. I then tried

 apt-get install linux-backports-modules-$(uname -r)
 

And that didn’t work. Finally, I decided to upgrade to Karmic Koala by issuing this command:

 sudo do-release-upgrade -d
 

It took a while to download all packages, it then removed a bunch of obsolete packages and after reboot complained about a bunch of old configurations that are not compatible anymore. Nevertheless, my wireless started working, yeah. Next, I am going to install Regdb, CRDA, and IW to track any other wireless issues.

I still left option to dual boot on my netbook but I am definitely going to live in UNR for most part.

September 2, 2009

Introduction to CouchDB

Filed under: Computing — admin @ 6:51 pm

I have been following growth and popularity of CouchDB for a while and even attended an excellent talk by J Chris Anderson of http://couch.io. However, only recently I am getting chance to actually use it. I am building an internal Search Engine based on Lucene, but I am storing documents in CouchDB. Though, CouchDB is pretty easy to setup, but its documentation is sporadic. Here are basic steps to get it running:

Installation and Launch

I installed CouchDB on my MacPro notebook using:

 sudo port install couchdb
 

CouchDB is available for Linux distributions and you can use yum or apt to install it, though official binaries are not available for Windows. You can also setup to load it at startup on Mac usng:

 sudo launchctl load -w /opt/local/Library/LaunchDaemons/org.apache.couchdb.plist
 

Once you installed it, you can start the couchdb server using:

 sudo /opt/local/bin/couchdb
 

Alternatively, you can skip installation & launch and instead use hosting solution from http://hosting.couch.io using “booom-couch” password for private beta.

Verify Installation

Once couchdb is started you can point your browser to http://127.0.0.1:5984/ or type in:

 curl http://127.0.0.1:5984/
 

As CouchDB uses JSON format for communication, it would show something like:

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

Alternatively, you can use curl to communication with couchd server:

 curl http://127.0.0.1:5984/
 

Creating a database

CouchDB is REST based service, and you can review all APIs at http://wiki.apache.org/couchdb/HTTP_Document_API. CouchDB uses PUT operation to create a database, e.g.

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

It will return

 {"ok":true}
 

Based on REST principles, PUT is used when adding a new data where the resource is specified by the client. However, if you call this API again with the same arguments, it will return in error, e.g.:

 {"error":"file_exists","reason":"The database could not be created, the file already exists."}
 

Adding documents

Each document is a JSON object that consists of name value pairs. Also, each document is specified a unique identifier or uuid. You can generate uuid in your application or get it from the CouchDB server. For example, to generate 10 UUIDs, call

 curl -X GET http://127.0.0.1:5984/_uuids?count=10
 

and it will return something like:

 {"uuids":["152019530472f7b0b364367bc2ec571d","cba55d13244afe7b924265760deccced","41a8d0d7093ac11827b3147565a08a80","281dc15503fffee17c9da332748e9288","90613ae77c78c8bd81849b728d648055","23c320522473bdd47071d56b72667172","bb8b72a9dc391e95ffd5e155d8bf7011","87b8da3e3cf0c16110e030a711dc26b3","cfdf87adc2cf4593a92e4edf38f2f557","dc80745c5cb478de48230e48efaf5ede"]}
 

You can then add a document using:

 curl -X PUT http://127.0.0.1:5984/guestbook/152019530472f7b0b364367bc2ec571d -d '{"name":"Sally", "message":"hi there"}'
 

It will return verification message:

 {"ok":true,"id":"152019530472f7b0b364367bc2ec571d","rev":"1-3525253587"}
 

Note, it generated a version of the document. Alternatively, you can use POST request to add document using server-generated UUID, e.g.

 curl -X POST http://127.0.0.1:5984/guestbook -d '{"name":"John", "message":"hi there"}'
 

That returns UUID and version of newly created object, e.g.

 {"ok":true,"id":"b4bb85ab50271f3d12d25feb219cb66e","rev":"1-657551114"}
 

Also, you can add binaries such as images to the CouchDB as well, e.g.

 curl -vX PUT http://127.0.0.1:5984/guestbook/6e1295ed6c29495e54cc05947f18c8af/image.jpg?rev=2-2739352689 -d@image.jpg -H "Content-Type: image/jpg"
 

Reading documents

CouchDB uses GET operation to read the document and you pass the id of the document, e.g.

 curl -X GET http://127.0.0.1:5984/guestbook/152019530472f7b0b364367bc2ec571d
 

which returns

 {"_id":"152019530472f7b0b364367bc2ec571d","_rev":"1-3525253587","name":"Sally","message":"hi there"}
 

Updating documents

CouchDB uses optimistic locking to update documents so this version number must be passed when we update document. Also, CouchDB is append-only database so it will create a new version of the document upon updated. For example, if you type same command again you would see:

 {"error":"conflict","reason":"Document update conflict."}
 

In order to update the document, the version must be specified, e.g.

 curl -X PUT http://127.0.0.1:5984/guestbook/152019530472f7b0b364367bc2ec571d -d '{"_rev":"1-3525253587", "name":"Sally", "message":"hi there", "date":"September 5, 2009"}'
 

This will in turn, create a new version and will return:

 {"ok":true,"id":"152019530472f7b0b364367bc2ec571d","rev":"2-1805813096"}
 

Deleting document/database

You can delete a document using DELETE operation, e.g.

 curl -X DELETE http://127.0.0.1:5984/guestbook/b4bb85ab50271f3d12d25feb219cb66e -d '{"rev":"1-657551114"}'
 

Similarly, you can delete a database using:

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

Querying Documents

CouchDB uses Javascript based map and reduce functions to query and view documents, where map function takes a document object and returns (emits) attributes from the document. Here is simplest map function that returns entire document:

 function(doc) {
       emit(null, doc);
 }
 

Here is another example, that returns names of people who posted to guestbook:

 function(doc) {
     if (doc.Type == "guestbook") {
         emit(null, {name: doc.name});
     }
 }
 

Reduce function is similar to aggregation functions in most relatinal databases, for example to count all names you could define map function as

 function (doc) {
     if (doc.Type == "guestbook") {
         emit(doc.name, 1);
     }
 }
 

and reduce function as

 function (name, counts) {
     int sum=0;
     for (var i=0; i<counts.length; i++) {
         sum+=counts[i];
     }
     return sum;
 }
 

All Databases

You can list names of the database using:

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

You can also get all documents for a particular database (guestbook):

 curl -X GET http://127.0.0.1:5984/guestbook/_all_docs
 

CouchDB also comes with a web based Futon application to create, update, and list databases and documents, simply go to http://127.0.0.1:5984/_utils/ and you will all databases in the system.
You can also control replication from that UI, which is pretty handy. Also, you can poll database changes using:

 curl -X GET 'http://127.0.0.1:5984/guestbook/_changes?feed=longpoll&since=2'
 

Also, you can get statistics using:

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

And Config via:

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

Replication

CouchDB is written in Erlang and uses many of internal features of Erlang such as replication of databases (that use Mnesia). In order to replicate, just create a database on another server, e.g.

 curl -X PUT http://127.0.0.1:5984/guestbook-replica
 

Then replicate using:

 curl -X POST http://127.0.0.1:5984/_replicate -H 'Content-Type: application/json' -d '{"source":"guestbook", "target":"http://127.0.0.1:5984/guestbook-replica"}'
 

Security

You can add user/password based basic authentication by editing /opt/local/etc/couchdb/local.ini file. You will then need to pass user/password when accessing CouchDB server, e.g.

 
 curl -basic -u 'user:pass' -X PUT http://127.0.0.1:5984/guestbook
 

Summary

I just started using CouchDB and I am still learning more advanced features and its capabilities in enterprise level environment. Though, it looks very promising, but I am keeping Berkely DB in the back pocket in case I run into severe issues.

August 15, 2009

Releasing Wazil.com

Filed under: Computing — admin @ 11:30 am

I just finished a brand new website Wazil.com and companion facebook app for posting yellow pages and classifieds. I am working on starting a local communities for this website that will show local search results based on your location. Please give it a try and post me your comments and suggestions.

August 6, 2009

How Twitters D.O.S brought my blog site to halt

Filed under: Computing — admin @ 12:17 pm

I noticed my blog was taking a long time to load and then realized that twitter’s denail of service attack effected my weblog. My blog shows latest tweets using javascript and as browsers generally block loading the contents when executing javascript, thus my blog was not showing the contents. I noticed that I was violating one of the commandments of Steve Souders, i.e., put your javascripts at the bottom. After moving the javascript calls to the bottom, my blog started loading happily though without the tweets for now. Also, Steve’s new book shows tons of ways to load javascript asynchronously but I haven’t added that to my blog yet.

July 28, 2009

Cut the scope and make your life easy

Filed under: Project Management — admin @ 10:45 am

I have been developing software for over twenty years and in every project you have to grapple with iron triangle of schedule/cost/functionality or sometime referred to as cost/quality/schedule or cost/resources/schedule. In my experience, curtailing the scope produces better results than adding more resources or extending deadline. In addition, slashing the scope also produces other side effects such as reducing the complexity of the software, easier learning curve for users, less training/support cost and better communication among team members.

You can reduce the scope by focusing on essential features using Pareto principle (80-20 rule) and companies like like Apple or 37Signals produce great products that are not only more useful but are much simpler to use. However, this is not easy as project manager or product owner have to say NO. Too often, I see project managers say YES to anything to please upper management and users. In the end, the team is overwhelmed and under stress. Also, a big pile of features where all features are of same importance (priority) is biggest reason for death-march projects.

Working with a small number of features reduces complexity such as essential complexity, cyclomatic complexity or accidental complexity because your codebase is smaller. Though, you still have to apply good software engineering principles such as domain driven design, unit testing, refactoring, etc, but maintenance becomes easier with smaller codebase. When you have a small codebase you have fewer bugs as they are no bugs for zero code. Fewer bugs means less support cost when some user complains of a bug or when system crashes in the middle of the night.

With a small set of features, the user interface becomes simpler, which in turn provides better usability to the users. Often, I have seen users get confuse when they have to work with a complex software that has a lot of features. This often is remedied by providing training or adding support that adds a lot more overhead to the projects. Again, better user interface does not come free automatically with a small set of features, but the usability problem becomes easier with fewer features.

Finally, small number of features and small code means your team size will remain small so communication among team members becomes easier. I like to work with team with size of 5 plus/minus 2, as number of communication links increase exponentially when you add more members. Also, with smaller teams that are colocated, you have better
Osmotic communication that Alistair Cockburn talks about. At Amazon, we have “2-Pizza” teams, i.e., teams are small enough to have team lunch with just two pizzas. Another factor when building teams is whether they are cross functional (vertical) or focus on single expertise such as systems, database, UI, etc. I prefer working with cross functional teams that focus on a single service or an application as communication and priorities within a single team is much easier to manage than between different teams.

In nutshell, reducing scope not only helps you deliver the software in time and delight your users but prepares you better to maintain and support the software. The complexity is number one killer for the software and results in buggy and bloated software. You should watch out when someone says “Wouldn’t it be cool if it did X?” kind of feature requests and often I see developers see this as a challenge or an opportunity to learn or apply new technology. However, each new feature takes a toll on your existing features, software maintenance and your team.

July 26, 2009

Day 5 at #oscon 2009

Filed under: Computing — admin @ 11:00 am

July 24, 2009 that was Day 5 of OSCON 2009 for me started with yet another talk by Gunnar Hellekson on using open source for building government projects. This was followed by very entertaining talk by Erik Meijer on “Fundamentalist Functional Programming”. He talked about side-effect free programming and how most functional languages are not pure. He briefly described Monads features of Haskell and how LINQ is influenced by them. Finally, there were keynotes by Karl Schroeder and Mark Surman, which were not very inspiring.

There were not a lot of sessions on last day of the OSCON, I decided to attend The HTML 5 Experiments to learn a bit on new HTML5 tags. Bruce Lawson showed how he implemented his blog using some of HTML5 tags such as header, footer, section, article, time, etc. He also mentioned canvas feature that was interesting but was difficult for people that require assistance technology. Finally, video tags won’t be available anytime soon due to a lot of proprietary decoders.

I then skipped next session and headed to Tech Museum, which is must see if you are visiting San Jose. I then headed to the airport and flew back to Seattle in the evening. Overall, I enjoyed OSCON 2009, I wished there were more talks on functional programming and was disappointed when haskell talk was cancelled. Also, I wish more talks were a bit more hands on like talks on CoucheDB that showed examples of how to use the system instead of just listing out features.

Day 4 at #oscon 2009

Filed under: Computing — admin @ 9:29 am

Thursday, July 23 2009, which was Day 4 for me at OSCON 2009, started with keynote by Kirrily Robert, where she she deplored acceptance of women in open source projects. This was followed by lame keynote by Tony Hey from Microsoft, where the presenter showed bits of open source contributions by Microsoft. Finally, Simon Wardley talked about cloud computing that was pretty entertaining. I then proceeded to attend talk on JRuby on Google App Engine, which didn’t quite kept up to its name and a lot of talk focused on persistence. I attended talk on Eucalyptus, which is an open source project for building private EC2 based cloud. This was sort of marketing talk, but I got a couple of things out such as how Amazon throttles network traffic within a datacenter to 500mb/sec and between zones to 200mb/sec.

I then attended A Survey of Concurrency Constructs, which presented common constructs for concurrency such as locks, transactional shared memory, message passing, dataflow, futures, i-structures, etc. I liked dataflow due to its deterministic nature, but is difficult to implement. I-structures is also interesting, but is non-deterministic and requires ports that make it similar to actors. I also like Linda as it can simulate dataflow, actors and CSP. Finally, message-passing and actors model are poplar these days due to their implementation in Erlang and Scala languages. Ted mentioned how most of the solutions are 20-30 years old, you can read history of most of these solutions from his slides. This was bleak talk as none of the options presented satisfactory option, though his bias was towards JVM based technology and he was impressed with Jonas Boner’s work on AKKA.

Next, I attended talk on Clojure: Functional Concurrency for the JVM, which described functional nature of Clojure and brief overview of its features and syntax. I found calling Java code from Clojure a little verbose especially when you are using method chaining, e.g.

                 factory.newSaxParser().parse(src, handler)
 becomes
                 (.. factory new SaxParser (parse src handler))
 

Another interesting features of Clojure are its implementation of persistent datastorage and lazy evaluation. Finally, Clojure supports transactional memory for building concurrent applications but there is a little emperical data on its performance and usability. In fact, Ted Sueng mentioned porting some of open source applications to use transactional memory resulted in deadlocks so I am waiting for a little more evidence.

Next, I attended talk on Cassandra: Open Source Bigtable + Dynamo, which is another DHT similar to
Dynomite, Redis, Tokyo Tyrant, Voldemort, HBase, etc. Cassendra is an implementation of DHT based on Amazon Dynamo paper and supports consistent hashing, gossip, failure detection, cluster state, partitioning and replication. I liked the fact that there is no single master as in BigTable so it is easier to scale and uses bloomfilter to keep index of keys. You can read more on its features from the slides.

Last session I attended was “Design Patterns” in Dynamic Languages, where Neal Ford showed how GOF design patterns were created to overcome deficiencies of C++ and he described how dynamic languages like Ruby and Groovy make it trivial to use these patterns without all the ceremony. Neal showed how method_missing can be used to implement builder pattern (though, I prefer not to use method_missing). He showed how each method on array is easier than iterator, how closures can be used to implement command and strategy patterns. Neal then showed, how internel DSLs can be used to implement interpreter pattern. Other examples included decorator and adapter patterns that used invokeMethod feature of Groovy to delegate invocation. Finally, he showed using null object pattern for consistent interface and aridifier to keep your code DRY. You can read more from his slides.

July 25, 2009

Day 3 at #oscon 2009

Filed under: Computing — admin @ 9:44 pm

On the third day (Wednesday, July 22, 2009, the real conference started. The day began with the a couple of keynotes. First, Tim O’reilly talked about Government 2.0, data.gov and other open source organizations that are building applications for the newly opened data. This turned out to be theme of a number of keynote speakers and there was a lot of interest in sunlight labs, http://opensourceforamerica.org/, http://www.gov2summit.com/. Then Dirk Hohndel talked about netbooks and some of innovations from Intel to improve boot time. He deplored state of graphics on Linux that have changed a little in last twenty years. Finally, Mike Lopp, author of Rands in Repose blog talked about how well intentional evil people can ruin companies using Borland as an example.

I started the sessions with Testing iPhone apps with Ruby and Cucumber, which should have been called Testing iPhone GUI apps with Ruby and Cucumber. It was half decent, but the framework had a lot of dependencies that we didn’t go into. I would like to give it a try as testing on Objective-C sucks. I then attended Introduction to Animation and OpenGL on the Android SDK, which seemed too fast and the presenter rambled on miscleneous APIs of OpenGL that I could not follow.

On the second half, I started talk on Automating System Builds and Maintenance with Cobbler and Puppet. This was somewhat useful and I learned a bit to use Cobbler for creating system images and using Puppet for configuration. This was followed by Best practices for ‘scripting’ with Python 3. This was a good talk that described some good principles for writing scripts (as opposed to Python applications). These principles included using optparse for parsing arguments, layers of I/O to help testing (StringIO), using generators for performance and finally using templates for packaging as setup is hard to configure from scratch. I then attended Using Hadoop for Big Data Analysis, which was sort of marketing talk from Cloudera CEO and prsented a few projects that are using Hadoop such as log processing at rackspace, monitoring electircal grid and large hadron collider. Finally, I attended Distributed Applications with CouchDB, which was really good talk on CouchDB by J Chris Anderson from couch.io. It described architecture of CouchDB and features of CouchDB. Chris also gave password for private beta to http://hosting.couch.io, which was “booom-couch”. You can read detailed examples from his slides.

July 23, 2009

Day 2 at #oscon 2009

Filed under: Computing — admin @ 2:34 pm

On the second day of OSCon 2009, I started with PhoneGap tutorial. The PhoneGap is an ambitious project that provides Javascript based unified APIs to develop mobile applications for a variety of mobile platforms such as iPhone, Blackberry, Android, Windows Mobile, Nokia, Palm, etc (most of those are not yet support, but 1.0 is expected in a few months that will have support most of them). It competes with a number of other open source projects such as Joyent Smart platform, Big five, Corona, Nimblekit, Appcellerator, Rhodes, etc. The PhoneGap uses HTML, CSS and Javascript for development and relies on Webkit and HTML5 technologies and standards. Many of mobile platforms such as iphone, android, palmpre support Webkit, though Blackberry and Windows Mobile are exceptions. The PhoneGap uses a number of features of HTML5 such as caching, CSS transformation, fonts, local storage, etc. The PhoneGap uses XUI, which is a subset of jQuery as some of the platforms such as iPhone provide limited caching (25K) for Javascript. It uses selectors and CSS for animations. The session introduced Dashcode tool that comes with XCode to build web applications and then converting those web applications into native applications using PhoneGap. The presenation for this session is available from http://presentations.sintaxi.com/oscon/

For the second half I decided to attend “Scalable Internet Architectures” — more than 10 million consumers/day. It was interesting talk that discussed building scalable architectures from hardware and networking perspective. It empahsized awareness on end-to-end architecture including javascript, application, database, network and machines and stressed importance of including people from operations in the architecture of the system. The presenter suggested use of CDN for static contents and using peer-based HA instead of load balancers as it eliminates load balancers as point of contention or failures. The speaker also suggested use of reverse proxy cache such as Varnish or Squid. He also suggested setting up multiple DNS servers for each data center and registering local servers with local DNS so that they take advantage of shortest path routes and talk to local servers. Other suggestions included use of caching, avoiding 302 redirects, separtion of OLTP and OLAP databases, use of DHT. The speaker also pointed to a number of networking techniques such isolating network for different services to prevent starvation of bandwidth when one of the service is surging the network with high dataload by using mac based filtering.
The speaker mentioned a number of usability techniques to offload expensive operation or hinting users when something is going on in the background. He mentioned use of queuing technology for offload processing. Finally, the speaker talked about a number of lesson learned from scaling and some of big WTF moments from his consulting work. Overall, this talk summarized a lot of existing knowledge for building scalable applications (such as from Steve Souders work) with a couple of new networking techniques to tackle slashdot or denial of service attack. The slides from this talk are available at http://www.slideshare.net/postwait/scalable-internet-architecture.

« Newer PostsOlder Posts »

Powered by WordPress