it’s long time that I left this topic alone, last time I promised we will discuss about the way document database let you get your data back to life, here we are.
Indexing
As we already said, I hope :-), the only way to search/query data in a document database is to use an index, let see what happens using a really trivial example:
static void Main( string[] args )
{
    var uri = new Uri( "http://localhost:8181" );

    var store = new DocumentStore()
    {
        DefaultDatabase = "Spike",
        Url = uri.ToString(),
        Credentials = CredentialCache.DefaultCredentials.GetCredential( uri, "Basic" )
    }.Initialize();
    using ( var session = store.OpenSession() )
    {
        session.Store( new Person() { FirstName = "Mauro", LastName = "Servienti" } );
        session.Store( new Person() { FirstName = "Guido", LastName = "Rossi" } );
        session.Store( new Person() { FirstName = "Giorgio", LastName = "Verdi" } );
        session.Store( new Person() { FirstName = "Samuele", LastName = "Bianchi" } );

        session.SaveChanges();
    }
}


The first thing we need is to load some test data, and then we can try to search for some of them:
using ( var session = store.OpenSession() )
{
    var query = session.Query<Person>().Where( p => p.FirstName.StartsWith( "G" ) );
    var persons = query.ToList();
}

The interesting stuff is that if we execute the above query we get back the expected 2 persons (Giorgio and Guido): how can it be? haven’t we said that we need an index to query for data? we have created nothing.
The most amazing feature (in my humble opinion)
If we fire up the RavenDB Studio and go to the Indexes tab we notice the following:
image
RavenDB has created a brand new index (a temporary index) for us automatically as soon as the query engine has noticed that there is no index that is capable to satisfy the query we issued.
But…what is the shape of the index?
image
RavenDB has just created what is called a “Map Index” whose role is to map fields that can be searched so to let the Lucene search engine have something to work on.
What happens if we issue a new query that involves different fields? Once again we get back the expected results, but:
image
We have now 2 indexes…let’s try one thing, manually delete the first index and re-execute the first query, what happens? No index is created, the query engine realizes that the existing index can be used to satisfy the incoming query, so far so good. The new question now is: is a good practice to let RavenDB auto-magically create indexes? in my opinion the answer is no.
The basic idea is that since we know how we are going to use our data we can create indexes upfront and use the amazing auto-index creation feature only at development time when for example in order to understand which is the best way to create an index that satisfies a specific query.
Next time we’ll see options we have out-of-the-box to create and manage indexes.
.m