Monday 16 April 2012

RavenDb Quick Start

image

Introduction

Continuing the NoSQL trend in recent years RavenDb is a .NET LINQ enabled document storage engine with super fast text search capabilities thanks to Lucene.NET.  It also enables sharding out of the box which is a great feature for scalability.

It exposes a HTTP REST interface, which gives it far greater flexibility when scaling - no nasty firewalls getting in the way.

The most compelling reason from my point of view for using RavenDb over SQL Server is the ability to store a complete document (read .NET object model) without having to hit multiple tables.  SQL Server file IO can be crippling when dealing with large sets of data spread across huge tables. 

For example, if you had a customer with addresses, orders and payments in SQL you would have to access at least 4 tables (probably more) whereas in RavenDb the complete customer entity is stored as one document with one ID value.  One fast lookup and the data, which is stored internally within RavenDb as JSON, is rehydrated into the full .NET object.

Download

From the http://ravendb.net/download website you can download the latest build and/or source.

Or you can use Nuget directly from Visual Studio:

Client and Server package (recommended) http://nuget.org/packages/RavenDB
Embedded package http://nuget.org/packages/RavenDB-Embedded

 

Deployment

You have four main options for running RavenDb:

  • As a service under its own web server
  1. Download the build file from the website and extract the zip
  2. Go to the Server directory
  3. Execute the following command on the command line: Raven.Server.exe /install
    Note: Raven may ask you for administrator privileges while installing the service.  Configuration including port number is taken from Raven.Server.exe.config (defaults to port 8080).
  • Under IIS

http://ravendb.net/docs/server/deployment/as-iis-application

  • Embedded within your own application

http://ravendb.net/docs/server/deployment/embedded

  • Within a Command Prompt window, perhaps for development work with manual start up
    1. Download the build file from the website and extract the zip
    2. Run the Start.cmd batch file in the root directory.

Warning

IMPORTANT: To save any potential headaches, make sure you use the same build numbers for client and server!

RavenDB Management Studio

From the browser you can use the Management Studio, a great little tool written in Silverlight.  It enables you to write indexes (the map/reduce equivalent of queries in SQL), view/edit the JSON documents directly, run backups, import/export data or view the logs.

image

By default the Management Studio comes with a button you can press to load a sample Albums database.

The following examples are based on samples taken from the RavenDb source code.

Writing and Reading data from .NET

using System;
using Raven.Client.Document;

namespace Raven.Sample
{
class Program
{
static void Main(string[] args)
{
var documentStore1 = new DocumentStore
{ Url = "http://localhost:8080" }.Initialize();

using (var session1 = documentStore1.OpenSession())
{
session1.Store(new User { Id = "users/ayende", Name = "Ayende" });
session1.SaveChanges();
}

using (var session1 = documentStore1.OpenSession())
{
Console.WriteLine(session1.Load<User>("users/ayende").Name);
}

Console.WriteLine("Wrote and read one document to 8080");
}
}

public class User
{
public string Id { get; set; }
public string Name { get; set; }
}
}



Sharding Example from RavenDb Source

//-----------------------------------------------------------------------
// <copyright file="Program.cs" company="Hibernating Rhinos LTD">
// Copyright (c) Hibernating Rhinos LTD. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using Raven.Client.Document;
using Raven.Client.Shard;
using Raven.Client;

namespace Raven.Sample.ShardClient
{
class Program
{
static void Main()
{
var shards = new Dictionary<string, IDocumentStore>
{
{"Asia", new DocumentStore {Url = "http://localhost:8080"}},
{"Middle-East", new DocumentStore {Url = "http://localhost:8081"}},
{"America", new DocumentStore {Url = "http://localhost:8082"}},
};

var shardStrategy = new ShardStrategy(shards)
.ShardingOn<Company>(x => x.Region)
.ShardingOn<Invoice>(x => x.CompanyId);

using (var documentStore = new ShardedDocumentStore(shardStrategy).Initialize())
{
new InvoicesAmountByDate().Execute(documentStore);

using (var session = documentStore.OpenSession())
{
var asian = new Company { Name = "Company 1", Region = "Asia" };
session.Store(asian);
var middleEastern = new Company { Name = "Company 2", Region = "Middle-East" };
session.Store(middleEastern);
var american = new Company { Name = "Company 3", Region = "America" };
session.Store(american);

session.Store(new Invoice { CompanyId = american.Id, Amount = 3, IssuedAt = DateTime.Today.AddDays(-1) });
session.Store(new Invoice { CompanyId = asian.Id, Amount = 5, IssuedAt = DateTime.Today.AddDays(-1) });
session.Store(new Invoice { CompanyId = middleEastern.Id, Amount = 12, IssuedAt = DateTime.Today });
session.SaveChanges();
}


using (var session = documentStore.OpenSession())
{
var reduceResults = session.Query<InvoicesAmountByDate.ReduceResult, InvoicesAmountByDate>()
.ToList();

foreach (var reduceResult in reduceResults)
{
string dateStr = reduceResult.IssuedAt.ToString("MMM dd, yyyy", CultureInfo.InvariantCulture);
Console.WriteLine("{0}: {1}", dateStr, reduceResult.Amount);
}
Console.WriteLine();
}
}
}

}
}



Caching

using (session.Advanced.DocumentStore.AggressivelyCacheFor(TimeSpan.FromMinutes(5)))
{
session.Load<User>("users/1");
}

Authentication


RavenDB supports Windows and OAuth security models.  You can also add support for custom users within RavenDb by implementing IAuthenticateClient.


By default, Windows anonymous access is enabled for GET only access. This can be amended in the Raven.Server.exe.config file.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Raven/Port" value="*"/>
<add key="Raven/DataDir" value="~\Data"/>
<add key="Raven/AnonymousAccess" value="Get"/>
</appSettings>
<runtime>
<loadFromRemoteSources enabled="true"/>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<probing privatePath="Analyzers"/>
</assemblyBinding>
</runtime>
</configuration>


The full set of AnonymousAccess values are:  Get, All and None.

No comments:

Post a Comment