Tuesday, 26 February 2013

Introduction to Simple DB

According to Wikipedia Amazon simple db is a distributed database written in Earlang used extensively as a web service. As the name suggests simple db has a very easy to understand and use architecture where a domain is a database, having a size of 10GB allowing 256 attribute per item. An item is like a table which holds attributes restricted to 1024 bytes in size.
     We can simply add, delete, query a sdb. First we need to connect to the sdb, we use the python interface to connect to amazon web services.

import boto

sdb = boto.connect_sdb(awsaccesskey, awssecretkey)

Now after getting connection to sdb, you can start either by creating a new domain or connecting to an existing domain.

domain = sdb.create_domain('my_domain_name') #create a new domain
domain = sdb.get_domain('my_domain_name') #connect to existing domain

If the domain doesn't exist, then get_domain returns error.

Now to create item inside domain we have,

item = domain.new_item('item_name')

Item is the key which is unique, associated with each key-value pair. To save the items to sdb use item.save(). Entries gets saved as unicode. Now simply running a for loop displays the items in the domain and you get to see the entries in the item. To update an existing value in the sdb. We use
 sdb.put_attribute(domain_name, item_name, values, replace=True)       

This writes to the domain, if the item already exists then it simply overwrites the existing value.

You can also query for a  particular value, using the select query. 

sdb.select('SELECT * from domain_name where value = value', None, True, None)

SDB is widely used in web services, for storing key- value pairs. It also gives you to save data any way you like.