Getting Started – Basic DB Operations in RavenDB

I was recently was looking at NoSQL based databases for a personal project that I was working on. I did not want spend a lot of time designing the perfect database for an application which might or might not be used extensively. For this I checked out MongoDB and I had decided to go with it but while searching a database native to dotnet I saw RavenDB and felt it might be an appropriate fit for my simple application for the simple reason that RavenDB is fully written in dotnet. I downloaded the binaries for RavenDB and started playing with the db. The five main operations that we do on a database are

  • Adding records to the table.
  • Showing all records in the table.
  • Updating existing records in the table.
  • Deleting records in the table.
  • Searching for a specific record in the table.

  • Mind you I have just started playing with RavenDB and my examples are for the beginner. Those who consider themselves experts in this field of document oriented database’s or RavenDB, pardon my ignorance and let me know If I am wrong somewhere. So without any delay let’s jump into the examples

    A point to be noted here is that RavenDB can run as embedded database or external database. There are some minor TODO’s that we would need to do to configure that. For now I am going to assume that you want to run it as an external database.

    Before writing the RavenDB code, let us first create the appropriate classes for RavenDB’s consumption. Based on the example given on the site I have created a simple Product class.

    1
    2
    3
    4
    5
    6
    7
    
    public class Product
    {
          public string Id { get; set; }
          public string Name { get; set; }
          public decimal Cost { get; set; }
          public string Type { get; set; }
    }

    I have declared a simple products class with the following attributes

  • Id – Unique Identifier (Auto Generated by RavenDB)
  • Name – Product Name
  • Cost – Product Cost
  • Type – Product Type
  • It’s a simple class with getters and setters for assigning and retrieving values back and forth. Since we are done with the products class we will now look at how to store values in the products class which will be carried over to RavenDB.

    Inserting Records

    To insert records into Ravendb, the code is quite simple.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    
    var store = new Raven.Client.Document.DocumentStore { Url = "http://localhost:8080" };
    store.Initialize();
     
    Product prods;
     
    using (var session = store.OpenSession())
    {
         for (int i = 0; i < 10; i++)
         {
              prods = new Product();
              prods.Cost = i;
              prods.Type = i.ToString();
              prods.Name = "Product " + i;
              session.Store(prods);
         }
         session.SaveChanges();
    }

    And we are done, the above code will add 10 documents (records) to RavenDB. To elaborate on the code, Line no 1 specifies that we are going to use an External database and not an embedded one. We will create store for the same relevant purpose. We will now use the store globally in our code to save changes to the database. The second line “store.initialize” initializes the database and gets RavenDB ready for database transactions. In simpler terms the first line allows to connect to the database and the second line opens the connection to the database.

    In the next preceding lines we use the existing prods object to create a new instance of the Product class and assign some dummy values to be stored in the database. When we reach the 12th line the prods object is ready with the data and the session.store takes the prods object as input parameters and stores it in memory. The 16th line which states session.SaveChanges() carries over the new prods object details into the database. Remember unless and until you call the SaveChanges method, data will not be saved onto the database.

    Displaying all records in the database.

    We will now display all the records that we just stored in the database.

    1
    2
    3
    4
    5
    6
    
    var allproducts = session.Query<Product>().ToArray();
     
    foreach (var prod in allproducts)
    {
         Console.WriteLine(prod.Id + "  " + prod.Name);
    }

    The above code pretty much gets all the records we just stored and converts it into an array of products and lo behold we get all the product details. In the above code we just use the Query method in the session object to query all documents pertaining to the Product class and convert it to an array object and then we use the foreach construct to loop through the array of products. Simple isn’t it, wait till you see the rest of the operations.

    Updating a particular record

    The code to update the record is quite simple and here it is

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
    var prodToUpdate = session.Load<Product>("products/5129");
    if (prodToUpdate != null)
    {
           Console.WriteLine(prodToUpdate.Name);
           prodToUpdate.Name = "LED TV";
           session.SaveChanges();
           Console.WriteLine(prodToUpdate.Name);
    }
     
    In the above code we use the Load method and pass the product id to get a relevant product object for us to update. Once we get the object we use the setter method in the product class to update the name and guess what we call the SaveChanges method to save the changes to the database. Voila !! we are done updating a document in the database.

    Deleting a particular record

    The code to delete a particular is even simpler and very similar to updating the record.

    1
    2
    3
    4
    5
    6
    
    var prodToDelete = session.Load<Product>("products/5130");
    if (prodToDelete != null)
    {
         session.Delete<Product>(prodToDelete);
         session.SaveChanges();
    }

    In the above code we use the Load method in the session object and pass the product id. This method in turn searches the database and gets back the particular document if its available. Then we use the Delete method of Product type and pass the retrieved object and then call SaveChanges to ensure the delete is done permanently. Remember if you don’t call SaveChanges the deletion will not be effected. Alternatively if you would like to do a soft delete then you can include business logic to do the same.

    Searching for a specific record

    The code for searching a specific record is a little different and we will use the Query object to do the work.

    1
    2
    3
    4
    5
    6
    
    var prods = session.Query<Product>().Where(c=>c.Name == "Product 2");
     
    foreach (var prod in prods)
    {
         Console.WriteLine("Product Id and Name is: " + prod.Id + "," + prod.Name);
    }

    It is quite similar to the update or delete code we have. Instead of using Load method we use the Query method to search for a product named “Product 2″ and loop all the matching results. It is possible to get a single result also and it can be by modifying the line as seen below

    1
    
    var prod = session.Query<Product>().Where(c => c.Name == "Milk").SingleOrDefault();

    Simple wasn’t it !!!

    The biggest advantage of document based databases is the fact that its loosely typed. Some might disagree but to me working on a database where I can include and exclude a field of any type at any given time is very beneficial especially when I am doing prototyping.

    I hope you have enjoyed reading the article as much as I did writing it. Hope to hear some comments and please do let me know If I am wrong somewhere.

    2 thoughts on “Getting Started – Basic DB Operations in RavenDB”

    1. Woah, easy there – your SaveChanges call is inside the loop – you should really not be calling that for every operation :)

      You should call it *once* after you have made a batch of changes (In a typical OLTP world this is once per request/unit of work)

    2. Point noted and article updated :). I was under the impression that SaveChanges needed to be called immediately after loading the object. Thanks for clearing that up :).

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>