Firebase Android中的多个查询 [英] Firebase multiple queries in android
问题描述
我有这个数据库:
候选人集包含总统和秘书等几类.每个候选者还具有totalVotes
.
我想查询:
The candidates collection contains several categories such as president and secretary. It also has totalVotes
for each candidate.
I would like to query:
- 按类别划分的结果,例如总裁或秘书
- 每个类别的总投票"数最高的候选人,即,具有最高投票权的总统和具有最高投票权的秘书.
这是我的代码不起作用:
Here is my code that is not working:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference candidatesRef = rootRef.child("candidates");
Query specific = candidatesRef.orderByChild("category").equalTo("President");
specific.orderByChild("totalVotes").limitToFirst(1);
specific.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot){
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
String firstname = childSnapshot.child("firstname").getValue(String.class);
String lastname = childSnapshot.child("lastname").getValue(String.class);
Long votes = childSnapshot.child("totalVotes").getValue(Long.class);
pres.setText(firstname + " " + lastname+" - "+votes+" Votes");
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't swallow errors
}
});
我该如何实现?谢谢
推荐答案
不幸的是,Firebase中没有OR
子句.因此,您不能基于多个值来过滤category
属性上的候选项.
Unfortunately, there is no OR
clause in Firebase. So you cannot filter the candidates on the category
property based on multiple values.
有一种解决方案可能会起作用,但仅(如果这些值在范围内).就您而言,您可以获得与President
或Secretary
匹配的所有候选:
There is a solution that might work but only if those values are in a range. In your case, you can get all candidates matching President
or Secretary
with:
ref.child("candidates")
.orderByChild("category")
.startAt("President")
.endAt("Secretary")
这里的问题是,如果存在类别President
和Secretary
之间的其他类别,它还将与其他类别的候选者匹配.除此之外,您可以不将查询限制为1
或2
,因为您将永远不知道哪个候选人将获得最高的投票数.可能是总统,也可能是秘书.
The issue here is that it will also match candidates for other categories whose category is between President
and Secretary
if it exists. Besides that, you can not limit the query to 1
or 2
because you'll never know which candidate will have the highest number of votes. It might be a president, as well as a secretary.
因此,Firebase实时数据库中无法将多个值传递到查询中.您需要为此执行单独的查询,然后在客户端上合并结果.
So, there is no way in the Firebase Realtime Database to pass multiple values into a query. You need to perform separate queries for that and merge the result on the client.
如果您考虑在某个时间点尝试使用 Cloud Firestore ,则可以在此处找到查询的
If you consider at some point in time to try using Cloud Firestore, you can find there Query's whereIn(String field, List values) method that can help you solve this issue.
这篇关于Firebase Android中的多个查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!