I have been using two codes below when i'm trying to find record by email or phone number, sometimes first code working fine sometimes not working and also the second code same too.
what is the difference between codes below and when i should use "equalTo" or "startAt and endAt"?
ref.orderByChild("email")
.equalTo(str)
and
ref.orderByChild("email")
.startAt(str)
.endAt(str+"\\uf8ff")
ref.orderByChild("email").equalTo(str)
The above means that the email has to be equal to the value of str. It is the same as saying WHERE email= '[email protected]'
ref.orderByChild("email").startAt(str).endAt(str+"\\uf8ff")
This is like saying WHERE email LIKE ca% which will return all emails that start with "ca"
public Query startAt (String value)Create a query constrained to only return child nodes with a value greater than or equal to the given value, using the given orderBy directive or priority as default.
public Query endAt (String value)Create a query constrained to only return child nodes with a value less than or equal to the given value, using the given orderBy directive or priority as default.
The
\uf8ffis simply the last character in unicode, so acts as an end guard.
Check this for queries:
https://www.youtube.com/watch?v=sKFLI5FOOHs
It's true that in "some" cases, you can achieve the same thing using either the first approach or either the other but from the official documentation regarding filtering data, each method has a difference purpose as:
equalTo() - Return items equal to the specified key or value depending on the order-by method chosen.
startAt() - Return items greater than or equal to the specified key or value depending on the order-by method chosen.
endAt() - Return items less than or equal to the specified key or value depending on the order-by method chosen.
But as a conclusion, use the first approach when you want to have a perfect match. The second approach is used usually for a search query when you want to filter data that starts with some characters. In terms of SQL, note that there isn't an equivalent to LIKE clause in Firebase but with the second approach we simulate the exact same behaviour.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With