Sunday, 26 September 2010

NoSQL – One Simple CRUD Example

Here I’d will explain how simple, with the right .jars, is work with NoSQL, in my example will be used the CouchDB, that is pretty simple and easy to install and make it run. Basically just unzip it and run the .bat file.  For any other explanations about NoSQL databases please go to this llink, or to this other one.

.jar’s that you will might need

Couch4j
Json lib
ezmorph
httpClient and httpCore

Here we’ll create one very simple example with simple table and no relationships.

Field name

_id
_rev
EMPLOYEE_ID
FIRST_NAME
FAMILY_NAME
GROUP
FUNCTION

We don’t need to worry with the field types due that the document, is a JSON object so, just strings and you must perform the conversions later on. Here one simple JSON document as example:

{
 "_id":"1",
 "_rev":"1-10",
 "EMPLOYEE_ID":"0001",
 "FIRST_NAME":"MyFirstName",
 "FAMILY_NAME":"MyFamilyName",
 "GROUP ":"JAVA",
 "FUNCTION":"Developer"
 }




CouchDB reserve those fields starting with _ (underscore) to be used to itself, e. g. : _id , and the _id itself is a primary key.


As I’m using the CouchDB as localhost and the default port to access it is 5984, and to do any sort of access into CouchDB you must have one session created, in other words session is mandatory.


   1:  package au.com.nosql.main;
   2:   
   3:  import com.fourspaces.couchdb.Database;
   4:  import com.fourspaces.couchdb.Document;
   5:  import com.fourspaces.couchdb.Session;
   6:  import com.fourspaces.couchdb.ViewResults;
   7:  import java.util.List;
   8:   
   9:  public class NoSQLMain {
  10:   
  11:     public static void main(String[] args) {
  12:        boolean exist = false;
  13:        Database db = null;
  14:        
  15:        // Creating the session
  16:        Session mySession = new Session("localhost", 5984);
  17:        String dbname = "employeeTest";
  18:   
  19:   
  20:   
  21:        // Check if the database already exist, if not create
  22:        // Including one document into my new database
  23:        List<String> dbsNames = mySession.getDatabaseNames();
  24:        for (String dbName : dbsNames) {
  25:           if (dbName.trim().equalsIgnoreCase(dbname)) {
  26:              System.out.println("Already exist the database with name" + dbname);
  27:              exist = true;
  28:              break;
  29:           }
  30:        }
  31:   
  32:        if (!exist) {
  33:           mySession.createDatabase(dbname);
  34:        }
  35:   
  36:        db = mySession.getDatabase(dbname);
  37:   
  38:        // create one document and save it
  39:        Document doc = new Document();
  40:        doc.setId("1");
  41:        doc.put("EMPLOYEE_ID", "0001");
  42:        doc.put("FIRST_NAME", "MyFirstName");
  43:        doc.put("FAMILY_NAME", "MyFamilyName");
  44:        doc.put("GROUP", "JAVA");
  45:        doc.put("FUNCTION", "Developer");
  46:             
  47:        db.saveDocument(doc);
  48:        doc = null;
  49:   
  50:        // Retrive that list of DBs
  51:        List<String> listofdb = mySession.getDatabaseNames();
  52:        System.out.println("Number Total Of Databases: " + listofdb.size());
  53:   
  54:        // Displaying the current number of documents
  55:        int count = db.getDocumentCount();
  56:        System.out.println("Total Documents: " + count);
  57:   
  58:        // Retriving a single document
  59:        Document getOne = db.getDocument("1");
  60:        System.out.println("Document returned from database : " + getOne.toString());
  61:        getOne = null;
  62:   
  63:        // Delete the document from Database
  64:        getOne = db.getDocument("1");
  65:        db.deleteDocument(getOne);
  66:        count = db.getDocumentCount();
  67:        System.out.println("Total Documents after delete : " + count);
  68:        getOne = null;
  69:   
  70:   
  71:        // cleaning all docs if exist more than one
  72:        ViewResults viewResults = db.getAllDocuments();
  73:        List<Document> docs = viewResults.getResults();
  74:        for(Document doc1 : docs) {
  75:           System.out.println("Document to be deleted : " + doc1.toString());
  76:           db.deleteDocument(doc1);
  77:        }
  78:   
  79:   
  80:        // Delete the database
  81:        mySession.deleteDatabase(dbname);
  82:        listofdb = mySession.getDatabaseNames();
  83:        System.out.println("Number Total Of Databases after delete that created one : " + listofdb.size());
  84:   
  85:     }
  86:  }




 


There is one other way to persist one NoSQL DB is using HTTP:


HttpClient httpclient = new DefaultHttpClient();
 
HttpGet get = new HttpGet("http://localhost:5984/employeeTest/_all_docs?startkey=%221%22&limit=1");
 
HttpResponse response = httpclient.execute(get);



 


Or :

HttpGet get = new HttpGet(http://localhost:5984/employeeTest/_all_docs?startkey=%223%22&endkey=%226%22)





Where %22 is used for single cote ( ‘ ).


One last thing, have in mind that CouchDB is not a relational database, so it will just allow querying data based on "key" only, so we cannot retrieve data based on field values from such databases.


This is just a simple example using CouchDB and with one very simple table structure, though for more complex things, as the DB is not relational you will need search using keys and then populate it to create what you might need.

No comments:

Post a Comment