Firebase在安卓中的多重查询

huangapple go评论67阅读模式
英文:

Firebase multiple queries in android

问题

我有这个数据库

[![Firebase数据库][1]][1]

candidates集合包含多个类别例如president和secretary每个候选人还有'totalVotes'。
我想查询

1. 按类别查询例如总统或秘书
2. 每个类别中总票数最高的候选人即总统得票最多的候选人和得票最多的秘书

这是我的代码但不起作用

    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 + " 票");
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            throw databaseError.toException(); // 不要忽略错误
        }
    });

<!-- 结束代码片段 -->

我该如何实现这个谢谢

  [1]: https://i.stack.imgur.com/kQU0G.png
英文:

I have this database:

Firebase在安卓中的多重查询

The candidates collection contains several categories such as president and secretary. It also has totalVotes for each candidate.
I would like to query:

  1. Results by category eg President or Secretary
  2. The candidate with highest 'totalVotes' per category, i.e, the President with the highest votes, and the secretary with highest votes.

Here is my code that is not working:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference candidatesRef = rootRef.child(&quot;candidates&quot;);
Query specific = candidatesRef.orderByChild(&quot;category&quot;).equalTo(&quot;President&quot;);
specific.orderByChild(&quot;totalVotes&quot;).limitToFirst(1);
specific.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot){
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
String firstname = childSnapshot.child(&quot;firstname&quot;).getValue(String.class);
String lastname = childSnapshot.child(&quot;lastname&quot;).getValue(String.class);
Long votes = childSnapshot.child(&quot;totalVotes&quot;).getValue(Long.class);
pres.setText(firstname + &quot; &quot; + lastname+&quot; - &quot;+votes+&quot; Votes&quot;);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don&#39;t swallow errors
}
});

<!-- end snippet -->

How can I achieve this? Thanks

答案1

得分: 1

很遗憾,Firebase 中没有 OR 子句。因此,您无法根据多个值过滤 category 属性上的候选人。

有一个解决方案可能适用,但仅限于这些值在一个范围内的情况。在您的情况下,您可以获取所有匹配 PresidentSecretary 的候选人:

ref.child("candidates")
   .orderByChild("category")
   .startAt("President")
   .endAt("Secretary")

这里的问题是,它还会匹配其他类别的候选人,只要其类别位于 PresidentSecretary 之间。除此之外,您无法将查询限制为 12,因为您永远不会知道哪个候选人的选票数最高。它可能是总统,也可能是秘书。

因此,在 Firebase 实时数据库中无法将多个值传递给查询。您需要针对此进行单独的查询,并在客户端上合并结果。

如果您在某个时候考虑尝试使用 Cloud Firestore,您可以在那里找到 Query 的 whereIn(String field, List<? extends Object> values) 方法,可以帮助您解决这个问题。

英文:

Unfortunately, there is no OR clause in Firebase. So you cannot filter the candidates on the category property based on multiple values.

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(&quot;candidates&quot;)
.orderByChild(&quot;category&quot;)
.startAt(&quot;President&quot;)
.endAt(&quot;Secretary&quot;)

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.

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.

If you consider at some point in time to try using Cloud Firestore, you can find there Query's whereIn(String field, List<? extends Object> values) method that can help you solve this issue.

huangapple
  • 本文由 发表于 2020年4月9日 01:59:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/61107058.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定