Java – how to use firebase to query equal to (value, key)?
As a novice in firebase, I try to imitate a "where clause" request to retrieve a user's wallet in this simple use case:
User 48bde8f8-3b66-40bc-b988-566ccc77335c email: "toto@acme.com" username: "userTest1" UserWallet F4PvtvNT2Z coins: 26 someList elemet1 elemet2 user: "48bde8f8-3b66-40bc-b988-566ccc77335c"
First, I try to write my request with my request:
Firebase root = new Firebase("https://myApp.firebaseio.com/"); Firebase ref = root.child("UserWallet"); Query query = ref.equalTo("48bde8f8-3b66-40bc-b988-566ccc77335c","user");
The result is null, so I wrote this query:
Query query = ref.orderByChild("user").equalTo("48bde8f8-3b66-40bc-b988-566ccc77335c","user");
The result is null again The only way to retrieve a wallet is to use the following query:
Query query = ref.orderByChild("user").equalTo("48bde8f8-3b66-40bc-b988-566ccc77335c");
So should I always use "equalto()" before en "orderbychild()" query? So what is the purpose of querying "equalto (string value, string key)" and "equalsto (string value)", because only the second one runs correctly?
Solution
Some edge cases do not require orderby... (), but generally, an orderby... () is required before the filtering operation (equalsto(), startat(), endat())
I strongly recommend that you read the firebase programming guide for Android first (95% of which is applicable to regular Java) After spending a few hours in this guide, dozens of questions can be saved For example, this is section on queries
After reading, you may also want to read this guide in NoSQL data modeling It covers many common patterns in NoSQL data modeling and will help you realize the mapping of SQL queries to NoSQL database as soon as possible. It is a logical idea, but it is rarely a good one
My initial (no idea of your use case, except "I need to be able to find a user's wallet") model:
UserWallet "48bde8f8-3b66-40bc-b988-566ccc77335c" "F4PvtvNT2Z" coins: 26 someList element1 element2
In the above model, I invert the wallet under the user wallet and the user to make it easier for the user to find the wallet
ref.child('UserWallet').child(auth.uid).addValueEventListener(...
Please note that there are no queries involved, so the loading speed will be the same no matter how many users there are in your database
Or:
User "48bde8f8-3b66-40bc-b988-566ccc77335c" email: "toto@acme.com" username: "userTest1" Wallet "F4PvtvNT2Z" coins: 26 someList element1 element2 UserWallet "48bde8f8-3b66-40bc-b988-566ccc77335c" "F4PvtvNT2Z"
Now we have finished the flat structure To determine a user's wallet, go to userwaller / $uid and load each wallet from wallet / $walletid It may be more code, but it will be very effective (because there is no query involved)