How would you structure your Cloud Firestore db.
I have collections of Teams, Arenas and Games:
public class Team {
public String name;
public String homeCourtId;
}
public class Game{
public String matchId;
public String date;
public Arena arena;
public Team homeTeam;
public Team awayTeam;
}
public class Arena {
public String name;
public String phone;
public String email;
public String address;
public String postalCode;
public String city;
public String district;
public String cordLat;
public String cordLong;
}
A team can be a home team or away team in Games and a Game always has an Arena.
So currently my thought is to structure this as all games go into the Games collection and when i want to find out all games for a Team i need to query the Games collection and find all games where selected team is either home team or away team.
Should I have references to the teams by there Firestore generated id or should I go for team names? Any pointers where i can read more about this?
Is their a better way to structure my data in Firestore? (or any nosql db)
I need to query the Games collection and find all games where selected team is either home team or away team.
Cloud Firestore official documentation is quite explicit regarding this kind of query. Unfortunately, there are some query limitations, when it comes to Firestore:
Cloud Firestore does not support the following types of queries:
- Logical OR queries. In this case, you should create a separate query for each OR condition and merge the query results in your app.
So you cannot query a collection to find all games where selected team is either home team or away team in single go.
A workaroung would be to query your database twice and combine the results of those queries client side. It's not perfect, since you need to query twice but I think it will do the trick.
For Android, this is how you can merge two queries locally:
- Firestore - Merging two queries locally
But, according to Frank van Puffelen's answer regarding the same topic:
OR queries, since those would require skipping through the index, which would make it impossible to guarantee the performance. Note that work is under way to support a subset of possible IN queries, so that you could query for something like "give me all restaurants that serve either Thai or Italian food".
You can wait till this feature will be available or you can use my solution above.
Should i have references to the teams by there firestore generated id or should i go for team names?
In most of the cases, we asually use user ids and not names, the reason being that names can change while ids not. But it's up to you to decide if it's better to search by names rather than by ids.
P.S. If you're looking instead of "OR"
query an "AND"
query, please note that chaining multiple whereTo()
calls is permitted.