Wednesday, February 1, 2012

Getting Started with OrientDB

OrientDB is a NoSQL document database (http://code.google.com/p/orient/). Here I'm gonna show you how to get started with OrientDB.
apply plugin: 'java'
apply plugin: 'eclipse'

repositories {
    mavenCentral()
    maven { url 'http://www.orientechnologies.com/listing/m2' }
}

dependencies {
    compile 'com.orientechnologies:orient-commons:1.0rc7'
    compile 'com.orientechnologies:orientdb-core:1.0rc7'
}
The sample code below shows some basic create, retrieve, update, delete operations
package test;

import java.io.IOException;
import java.io.Serializable;
import java.util.List;

import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.db.object.ODatabaseObjectTx;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.serialization.OBase64Utils;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;

public class Main {
    static class Message implements Serializable {
        private static final long serialVersionUID = 1L;
        private String msg;
        
        public Message(String msg) {
            this.msg = msg;
        }
        
        public String getMessage() {
            return msg;
        }
    }
    
    public static void main(String[] args) throws Exception {
        ODatabaseDocumentTx db = new ODatabaseDocumentTx("local:testdb");
        if (!db.exists()) {
            db.create();
            
            // creating a schema is optional, but can be useful
            OClass personClass = db.getMetadata().getSchema().createClass("person");
            personClass.createProperty("id", OType.INTEGER);
            personClass.createProperty("name", OType.STRING);
            personClass.createProperty("msg", OType.STRING);
            db.getMetadata().getSchema().save(); // don't forget to save it
            
            // creating some records
            for (int i = 0; i < 10; i++) {
                ODocument doc = new ODocument(db, "person");
                doc.field("id", i + 1);
                doc.field("name", "foo" + i);
                Message msg = new Message("Hello" + i);
                doc.field("msg", OBase64Utils.encodeObject(msg));
                doc.save();
            }
        }
        else {
            // default username/password
            db.open("admin", "admin");
        }
        
        try {
            // query all records
            for (ODocument doc : db.browseClass("person")) {
                printPersonRecord(doc);
            }

            // query some records
            List<ODocument> results = db.query(new OSQLSynchQuery<ODocument>(
                "select * from person where name like 'foo%' order by id desc"));
            for (ODocument doc : results) {
                printPersonRecord(doc);
            }

            // create a new record
            ODocument doc = new ODocument(db, "person");
            doc.field("id", "11");
            doc.field("name", "foo11");
            Message msg = new Message("Hello" + 11);
            doc.field("msg", OBase64Utils.encodeObject(msg));
            doc.save();
            // verify it
            printPersonRecord(doc);
            // update it
            doc.field("name", "bar");
            doc.save();
            // verify it again
            printPersonRecord(doc);
            // delete it
            doc.delete();
            // count the number of records
            System.out.println(db.countClass("person"));
        }
        finally {
            db.close();
        }
    }
    
    private static void printPersonRecord(ODocument doc) 
        throws ClassNotFoundException, IOException {
        Message msg = (Message) OBase64Utils.decodeToObject(
            doc.field("msg").toString());
        System.out.println("id=" + doc.field("id") + ";" + 
            "name=" + doc.field("name") + ";" +
            "message=" + msg.getMessage());
    }
}
Creating a schema is useful to indicate the type of a field. If we omitted the creation of the schema, the query "order by id desc" would be sorted based on string rather than integer since by default all the fields are considered as a string in OrientDB.

OrientDB has a pretty useful utility to serialize/deserialize Java object and encode/decode it using base64 as shown in the example above.

If we look at the content of the testdb, there are two files created ls person.och and person.0.ocl for the "person" class. There is a limit of the number of classes/clusters that OrientDB can have. The default max number of classes/clusters is 32,768 (thanks Luca Garulli for the correction!).

1 comment:

  1. Nice post. Just a minor update: the maximum number of classes/clusters is 32,768 not 500.

    ReplyDelete