在 Android Studio Firestore 中获取查询时出现错误

Posted

技术标签:

【中文标题】在 Android Studio Firestore 中获取查询时出现错误【英文标题】:Error is coming while get query in Android Studio Firestore 【发布时间】:2021-12-22 12:47:10 【问题描述】:

当我在 Firestore 中使用以下查询时,出现了一个错误:

代码:

query = database.collection("CustomerViews/Data/Post")
  .whereGreaterThanOrEqualTo("postDate", startDate)
  .whereLessThanOrEqualTo("postDate", endDate)
  .orderBy("postViews", Query.Direction.DESCENDING)
  .orderBy("postDate", Query.Direction.DESCENDING) 

错误:

Invalid query. You have an inequality where filter (whereLessThan(), whereGreaterThan(), etc.) on field 'postDate' 
and so you must also have 'postDate' as your first orderBy() field, but your first orderBy() is currently on field
'postViews' instead.

【问题讨论】:

【参考方案1】:

错误消息对错误非常明确。您在“postDate”字段上同时使用“whereGreaterThan()”和“whereLessThan()”,但您不是 first 根据该字段对结果进行排序,因此会出现该错误。请记住,Firestore 中方法调用的顺序非常重要。要解决此问题,请将您的查询更改为:

query = database.collection("CustomerViews/Data/Post")
  .orderBy("postDate", Query.Direction.DESCENDING)
  .whereGreaterThanOrEqualTo("postDate", startDate)
  .whereLessThanOrEqualTo("postDate", endDate)
  .orderBy("postViews", Query.Direction.DESCENDING)

然后,只需创建相应的index。就是这样。


编辑:

根据您的第一条评论:

通过使用您的代码,数据即将到来,但“postViews”降序并未发生。只有 postDate 降序即将到来。

是的,结果将按照“postDate”降序返回。如果两个或多个元素具有相同“postDate”,那么只有那些结果将在那之后根据“postViews”降序排列。这就是 Firestore 的工作原理。

根据您的第二条评论:

我希望在给定日期范围内按降序排列“postViews”。

Cloud Firestore 查询只能对单个字段的范围进行排序或过滤。您试图实现的目标是不可能的,因为您试图在“postDate”上进行过滤,然后在“postViews”上进行排序。

在official documentation 中,有一个关于如何做到这一点的示例:

不同字段上的范围过滤器和一阶排序

 citiesRef.whereGreaterThan("population", 100000).orderBy("country"); //Invalid

根据你上一条评论:

我找到了解决问题的方法。在将 ArrayList 附加到适配器之前,我添加了以下行。

postArrayList.sortByDescending  it.PostViews  

确实,如果您将所有文档下载到客户端并在那里进行过滤,它会起作用,但是您下载的每个文档都需要阅读一个文档。

【讨论】:

感谢您的回复。通过使用您的代码数据即将到来,但 postViews 降序不会发生。只有 postDate 降序即将到来。 @Alex-Memo,我希望 postViews 在给定日期范围内按降序排列。如何获得相同的。是否可以使用 arraylist 排序。请提出建议。 请查看我更新的答案。我希望现在很清楚。是吗? 我找到了解决问题的方法。在将数组列表附加到适配器之前,我已经添加了以下行。 postArrayList.sortByDescending it.PostViews 感谢@Alex-Memo 的回复。我是你的忠实粉丝。【参考方案2】:

根据您的示例代码,您有一个不等式,其中 postDate 应在 postViews 之前首先初始化,如错误提示所示。这是目前orderBy() 子句的限制,其中您的第一个排序必须在同一字段上。

除了@Alex 的回答,您可以查看以下链接以了解类似情况

Firestore query order on field with filter on a different field Firestore "Invalid query" - Am I using Indexing wrong?

最后,这是limitations of order and limit data with Cloud Firestore 的文档。

【讨论】:

【参考方案3】:

我找到了解决问题的方法。在将数组列表附加到适配器之前,我已添加以下行。

postArrayList.sortByDescending it.PostViews

【讨论】:

以上是关于在 Android Studio Firestore 中获取查询时出现错误的主要内容,如果未能解决你的问题,请参考以下文章

android studio 创建 一个 布局文件在哪

android-gif-drawable在android studio上怎么配置

android studio preview在哪 在 View -> Tool Windows 没有 Preview

如何在mac上安装android studio

android studio source在哪儿

Android studio的preview界面一直在加载,该如何解决?