Firebase查询中有多个WHERE子句
我正在尝试检索仅在到达日期和机场匹配时才返回飞行数据的数据。我似乎无法找出最佳解决方案。我只能在机场或到达日期相同的地方提取数据,而不能在两者都提取(只能使用equalTo()
一次)。这是我当前的Java代码如下所示:
Firebase ref = mFirebaseRef.child(FirebaseReference.CHILD_FLIGHTS);Query queryRef = ref.orderByChild("airport").equalTo(getAirport());
queryRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println(TAG + " datasnapshot is equal to " + dataSnapshot);
}
}
这是数据本身:
{ "flight":{
"1ddf3c02-1f2e-4eb7-93d8-3d8d4f9e3da2":{
"airport":"Gothenburg, Sweden - Landvetter (GOT)",
"arrivalDate":"2016-06-21",
"arrivalTime":"20:58",
"code":"GOT",
"departureDate":"2016-06-23",
"departureTime":"20:58"
},
"c2c86e54-b4d0-4d83-934b-775a86f0a16c":{
"airport":"Gothenburg, Sweden - Landvetter (GOT)",
"arrivalDate":"2016-06-21",
"arrivalTime":"20:50",
"code":"GOT",
"departureDate":"2016-06-23",
"departureTime":"20:50"
}
},
"users":{
"1ddf3c02-1f2e-4eb7-93d8-3d8d4f9e3da2":{
"age":"25",
"createdTime":"1466533088358",
"email":"test2@test.com",
"provider":"password",
"sex":"M",
"username":"user2"
},
"c2c86e54-b4d0-4d83-934b-775a86f0a16c":{
"age":"25",
"createdTime":"1466374588255",
"email":"test1@test.com",
"provider":"password",
"sex":"M",
"username":"user1"
}
}
}
当前的Java代码将返回
具有相同机场的所有子级。如您所料,当客户端需要排序的数据量比上述测试数据大得多时,这是不可行的。如何更好地在Firebase端过滤数据?
回答:
实时数据库不支持多个where子句,但是您可以创建一个额外的密钥来使其成为可能。
A“飞行”在您的"flight"
列表可以有一个组合键"arrivalDate"
和"code"
。
"1ddf3c02-1f2e-4eb7-93d8-3d8d4f9e3da2" : { "airport" : "Gothenburg, Sweden - Landvetter (GOT)",
"arrivalDate" : "2016-06-21",
"arrivalTime" : "20:58",
"arrivalDate_code": "2016-06-21_GOT", // combined key
"code" : "GOT",
"departureDate" : "2016-06-23",
"departureTime" : "20:58"
}
然后,您可以查询该密钥。
Firebase ref = mFirebaseRef.child(FirebaseReference.CHILD_FLIGHTS);Query queryRef = ref.orderByChild("arrivalDate_code").equalTo("2016-06-21_GOT");
queryRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
});
另一个选择是从数据结构的字段中取消:
/ flights / $code
/ $flight_id
这意味着您的数据将如下所示:
"flight" : { "GOT": {
"1ddf3c02-1f2e-4eb7-93d8-3d8d4f9e3da2" : {
"airport" : "Gothenburg, Sweden - Landvetter (GOT)",
"arrivalDate" : "2016-06-21",
"arrivalTime" : "20:58",
"code" : "GOT",
"departureDate" : "2016-06-23",
"departureTime" : "20:58"
}
}
}
然后,您可以制定如下查询:
Firebase ref = mFirebaseRef.child(FirebaseReference.CHILD_FLIGHTS);Query queryRef = ref.child("GOT").orderByChild("arrivalTime").equalTo("2016-06-21_GOT");
queryRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
});
以上是 Firebase查询中有多个WHERE子句 的全部内容, 来源链接: utcz.com/qa/405156.html