skjagini
skjagini

Reputation: 3217

Firestore WhereIn Query with FieldPath.DocumentId is throwing exception

Trying to fetch few documents from a Collection based on a list of DocumentIDs and not able to get the following working using WhereIn and FieldPath. Nuget version Google.Cloud.Firestore v1.1.0

public async Task<IEnumerable<T>> GetByDocumentIdWhereIn(IEnumerable<string> documentIds)
{
    CollectionReference ref= FirestoreDb.Collection(_collectionName);
    Query query = ref.WhereIn(FieldPath.DocumentId, documentIds);
    QuerySnapshot querySnapshot = await query.GetSnapshotAsync();
    ...
}

And I am getting the following error when executed with couple of documentIds.

RpcException: Status(StatusCode=InvalidArgument, Detail="__key__ filter value must be a Key")
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Grpc.Core.Internal.ClientResponseStream+<MoveNext>d__5.MoveNext() in ClientResponseStream.cs
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Linq.AsyncEnumerable+<ForEachAsync_>d__174.MoveNext() in ForEach.cs
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Google.Cloud.Firestore.Query+<GetSnapshotAsync>d__54.MoveNext() in Query.cs
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()

Any Idea?

Upvotes: 2

Views: 805

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500765

Note: this answer was written before the release of Google.Cloud.Firestore 2.1.0. As of 2.1.0, the original code should work.


This is a server-generated exception, but it's possible to transform the query on the client-side so that it works. If the values provided are DocumentReference values instead of just strings, the query works.

That means right now you can fix your code like this:

CollectionReference coll = FirestoreDb.Collection(_collectionName);
var docRefs = documentIds.Select(id => coll.Document(id)).ToList();
Query query = coll.WhereIn(FieldPath.DocumentId, docRefs);
QuerySnapshot querySnapshot = await query.GetSnapshotAsync();

In the future we hope to do this for you automatically; progress on this will be tracked on this GitHub issue.

Note that if you just want to fetch a collection of document snapshots and you have (or can create) a sequence of DocumentReference values, an alternative is to use FirestoreDb.GetAllSnapshotsAsync.

Upvotes: 1

Related Questions