我正在尝试使用以下代码按时间和业力对热门帖子进行排序:
FirebaseFirestore.getInstance().collection("topics")
.orderBy("time", com.google.firebase.firestore.Query.Direction.DESCENDING)
.whereGreaterThanOrEqualTo("time",(System.currentTimeMillis() % 1000)-1000*60*60*24*7)
.orderBy("karma", com.google.firebase.firestore.Query.Direction.DESCENDING).startAfter(currentDoc).limit(10).get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot documentSnapshots) {
for (DocumentSnapshot d : documentSnapshots.getDocuments()){
Topic topic = new Topic();
topic.setId(d.getId());
topic.setUsername(d.getString("username"));
topic.setCaption(d.getString("caption"));
topic.setPic(d.getString("pic"));
topic.setTime(d.getLong("time"));
topic.setType(d.getString("type"));
topic.setImage(d.getString("image"));
topics.add(topic);
if (topics.size()==documentSnapshots.size()){
currentDoc = d;
adapter.updateList(topics);
loading.setVisibility(View.GONE);
}
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
e.printStackTrace();
}
});
我在 Firestore 中添加了索引。但它不起作用。
我的意思是它显示的是 7 天前的帖子。但它不是按业力排序的。它显示了按时间排序的 7 天前的帖子。如果我从查询中删除 orderBy("time")。它正在崩溃。
需要帮助:(
最佳答案
查询词的顺序很重要。要解决此问题,请像这样更改顺序:
FirebaseFirestore.getInstance().collection("topics")
.orderBy("karma", com.google.firebase.firestore.Query.Direction.DESCENDING)
.orderBy("time", com.google.firebase.firestore.Query.Direction.DESCENDING)
.startAfter(currentDoc).limit(10).get().addOnSuccessListener(/* ... */);
只要您使用的是 index,它就可以工作.
如您所见,我已从查询中删除了以下代码行:
.whereGreaterThanOrEqualTo("time",(System.currentTimeMillis() % 1000)-1000*60*60*24*7)
因为根据关于 Order and limit data with Cloud Firestore 的官方文档你不能:
Range filter and first orderBy on different fields.
另一种方法是使用:
FirebaseFirestore.getInstance().collection("topics")
.orderBy("time", com.google.firebase.firestore.Query.Direction.DESCENDING)
.whereGreaterThanOrEqualTo("time",(System.currentTimeMillis() % 1000)-1000*60*60*24*7)
.startAfter(currentDoc).limit(10).get().addOnSuccessListener(/* ... */);
如您所见,orderBy
和 whereGreaterThanOrEqualTo
都用于同一属性。
关于java - 按时间和分数对帖子进行排序的 Firestore 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48484478/