Sean Forman
Sean Forman

Reputation: 400

RavenDB Any Query on Child Objects returns incorrect results

I have a RavenDB Query that searches for active users on a document.

The normal query looks like this:

var documents = session.Query<Document>().Where(d => d.Users.Any(u => u.Id == UserId && u.Active == true)).ToList();

The Automatically generated query looks like this:

from doc in docs.Documents
select new {
    Users_Active = (
        from docUsersItem in ((IEnumerable<dynamic>)doc.Users).DefaultIfEmpty()
        select docUsersItem.Active).ToArray(),
    Users_Id = (
        from docUsersItem in ((IEnumerable<dynamic>)doc.Users).DefaultIfEmpty()
        select docUsersItem.Id).ToArray()
}

However, this causes the query to return document which have the correct user, but that user is inactive, as long there is another active user on the document.

I suspect this is because the fields are indexed resulting as:

AssignedUsers_Id: [1, 2]
AssignedUsers_Active:[false, true]

And the query will match the Id in the array, and true in the Active array, even though they are at different indices in their respective arrays.

What changes do I need to make to the index to get this to return only documents that have the UserId correct AND is Active?

To avoid this in the future with automatic indexes, is there any way I can rewrite my LINQ query so it will index and perform correctly?

Upvotes: 0

Views: 99

Answers (1)

Ayende Rahien
Ayende Rahien

Reputation: 22956

This is by design behavior with auto indexes. You can avoid this behavior by defining your own index, which will emit an index entry per user on the document.

The reason this is the default behavior for auto indexes is that in the vast majority of cases, it wouldn't matter to the user, but it has an extremely high potential cost on the server side, so we want the user to make an explicit decision about it.

Upvotes: 1

Related Questions