Join NoSQL movement with RavenDB – Part 1

NoSQL (aka Not Only SQL which Martin Fowler does not actually like the term) database is a database that does not totally adhere to relational concept. Another important characteristic is that some NoSQL implementation may not give full ACID guarantee. However, because of their distributed architecture in mind, most NoSQL database are very scalable in contrast to a classic relational database which can suffer from scalability issue. I won’t discuss RDBMS vs. NoSQL here as they are both invented to solve problems and I believe that what you choose should depend on your problem.

Although I have heard about NoSQL Database for a while, I haven’t had a chance to try it yet until I learned about one of the NoSQL database, RavenDB in the Nashville .NET Usergroup meeting last week.

RavenDB is a document-oriented database which is one of NoSQL implementations. The main concept of document-oriented database is that it stores document with a key (i.e., key/value). A document encapsulates data and can be encoded by using JSON (in RavenDB case), XML, Microsoft Word, etc. Every document has unique key (i.e., id) that represents that document. RavenDB has been written entirely in .NET, stores data as schema-free JSON (i.e., key/value) and provide a RESTful API for interaction with the database. Any client that supports HTTP/JSON communication should be able to use RavenDB. For .NET client, RavenDB provides LINQ support as well.

RavenDB can be run in as a console application, Windows service, IIS application, or embedded with client.

In this post, I will introduce RavenDB in embedded mode which is the easiest way to get started as I don’t need to set up and run the RavenDB server separately. With the help of NuGet, I can install everything in just one click.

After I create a console application, I go to NuGet package manager, and look for RavenDB Embedded. The embedded package will install both RavenDB Client, Database, and Embedded into the console project.

image

image

After I agree and accept all license terms, in the Solution Explorer, there will be a whole bunch of references added into the project.

image

Before I start using embedded RavenDB, I will need to specify where the database should be located by specify connection string.  This is not so different from how other databases such as SQL Server or Oracle connection string is setup. I create a new folder called Database in my project just to separate database from the code, but I can have RavenDB use any location to which my application has access.

image

<connectionStrings>
   <add name="RavenDB" connectionString="DataDir = .\Database" />
</connectionStrings>

In the code, I start by creating a DocumentStore instance which is thread-safe. However, DocumentStore is not cheap to create (similar to SessionFactory in NHibernate), the instance should be created once per database and application. Although the sample code is using ConntectionStringName, I can also use DataDictionary to specify the location directly in my code.

 using (var docStore = new EmbeddableDocumentStore { ConnectionStringName = "RavenDB" }.Initialize()) 

After I have a DocumentStore instance, then I can get a session from it (very similar to Session in NHibernate as well). The full sample code below just show how I can create a new document (i.e., Person instances), store them to RavenDB and query them later using LINQ.

class Program
    {
        static void Main(string[] args)
        {
            using (var docStore =  new EmbeddableDocumentStore 
                { 
                    ConnectionStringName = "RavenDB" 
                }
                .Initialize())
            {
                using (var session = docStore.OpenSession())
                {
                    // add new person
                    var p = new Person { LastName = "Fuchsia", FirstName = "Cyan" };
                    session.Store(p);
                    
                    // Id is generated by RavenDB
                    Console.WriteLine("{0} generated by RavenDB"
                        , session.Advanced.GetDocumentId(p));
                    session.SaveChanges();

                    #region Add more people
                    session.Store(new Person { LastName = "Hanselman"
                        , FirstName = "Scott" });
                    session.Store( new Person { LastName = "Rahien"
                        , FirstName = "Ayende" });
                    session.Store( new Person { LastName = "Sinofsky"
                        , FirstName = "Steven" });
                    session.Store( new Person { LastName = "The Gu"
                        , FirstName = "Scott" });
                    session.SaveChanges();                    
                    #endregion
                }

                using (var session = docStore.OpenSession())
                {
                    // retrieve people using LINQ
                    var people = from person in session.Query<Person>()
                                 select person;

                    Console.WriteLine("Total: {0}", people.Count());

                    foreach (var doc in people)
                    {
                        Console.WriteLine("{0} : {1}, {2}"
                            , doc.Id, doc.LastName, doc.FirstName);    
                    }                    
                }                
            }            
        }

        public class Person
        {
            public string Id { get; set; }
            public string LastName { get; set; }
            public string FirstName { get; set; }
        }
    }

Every document in RavenDB has to have a key, and RavenDB will generate a new key for the document if it has not been assigned already. Here is what happen when I run the code above.

image

I can go to the bin folder and see database that has been created. The folder is just a normal folder although the RavenDB icon is displayed.

image

image

In next RavenDB post, I will run RavenDB server in the console mode and show the RavenDB management studio which can be used to manage RavenDB server as well as see RavenDB in more detail. Enjoy coding!

Advertisements

One thought on “Join NoSQL movement with RavenDB – Part 1

  1. Pingback: Join NoSQL movement with RavenDB – Part 2 (Embedded, InMemory, and Management Studio) | Cyan By Fuchsia

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s