使用文档快照和“where”子句分页时出现 Firestore 错误

问题描述 投票:0回答:1
def getPayments ():
    col = firestoreClient.collection('payments')
    query = col.where('paymentId', '==', None).limit(10).order_by('__name__')

    lastDoc = None
    for doc in query.stream():
        lastDoc = doc

    query = col.where('paymentId', '==', None).limit(10).order_by('__name__').start_after(lastDoc)

    lastDoc = None
    for doc in query.stream(): # Errors here
        lastDoc = doc

在第二个 query.stream() 上,我收到此错误

google.api_core.exceptions.InvalidArgument: 400 order by clause cannot contain more fields after the key

我遵循了分页文档,但添加了一个

where
子句,这破坏了它。如果我删除
where
子句,它就可以正常工作。

python google-cloud-firestore
1个回答
0
投票

TLDR - 您需要在

.orderBy
中使用的字段上添加
.where
。我没有很好的解释为什么。在我看来,Firestore 需要更好的文档/错误消息传递。

我刚刚遇到了这个问题(我使用的是nodejs 库)。我按照文档进行了分页,然后我还需要添加

.where('createdAt', '>=', startAfterDateString)
。结果的第一页将返回,后续页面将抛出无用的“order by 子句不能在键后包含更多字段”错误。

export async function getAllThingsInSpecificOrder(
  collection: FirebaseFirestore.CollectionReference<FirebaseFirestore.DocumentData>,
  pageSize: number,
  lastDoc?: FirebaseFirestore.DocumentSnapshot<any>,
  startAfterDateString?: string
) {
  let query = collection.withConverter(thingConverter)

    // https://cloud.google.com/firestore/docs/query-data/order-limit-data#orderby_and_existence
    .orderBy('field1')
    .orderBy('field2')
    .orderBy('field3')
    .orderBy('field4')
    

  if(startAfterDateString) {
    query = query.orderBy('createdAt')
                 .where('createdAt', '>=', startAfterDateString) // this did not work until including the .orderBy above
  }

  if (lastDoc) {
    query = query.startAfter(lastDoc);
  }

  query = query.limit(pageSize);

  return query.get();
}
© www.soinside.com 2019 - 2024. All rights reserved.