Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RavenDB - why, when querying docs by Id, .Load<> returns value and Query<> does not?

Tags:

ravendb

Here is a simple class:

public class Person
{
    public int Id {get; set;}
    public string Name {get; set;}
}

When I save this in RavenDB it gets some Id assinged, say it's 1, then this

var person = session.Load<Person>("Person/1")

returns person I specified but this

var person = session.Query<Person>().First(p => p.Id == 1)

errors out and says that 'sequence contains no elements'. I don't uderstand why.

like image 324
user981375 Avatar asked Aug 08 '12 15:08

user981375


1 Answers

Loading documents by their ID is an ACID operation. In other words, the moment you save the document, it is available for retrieval.

On the other hand, querying documents follows the no-sql concept of "eventual consistency". You are querying an index, and that index may or may not have had time to fully build.

In your example, the index is still stale. If you waited long enough, your query would return properly. Alternatively, you can tell Raven to wait by using the WaitForNonStaleResults customization, but this can have dangerous side effects - especially on a busy index. You can read more about stale index queries here: http://ravendb.net/docs/client-api/querying/stale-indexes

In general, if you know the Id of the document, you should always use .Load(). Reserve using .Query() for things that actually would require index lookup. In your case, a reasonable query might be:

var person = session.Query<Person>().Where(p => p.Name == "Joe").FirstOrDefault();
like image 66
Matt Johnson-Pint Avatar answered Nov 06 '22 07:11

Matt Johnson-Pint