Firebase Realtime Database Search by Word in Between the Query

Firebase Realtime Database Search by word in between the query?

when I type some word that is in between the query it doesn't work

This is happening because Firebase does not support native indexing or search for text fields in database properties. Additionally, downloading an entire node to search for fields client-side isn't practical at all. To enable full text search of your Firebase realtime database data, I recommend you to use a third-party search service like Algolia or Elasticsearch.

This is an example on how it works with Cloud Firestore but in the same way you can use it with Firebase realtime database.

How can I perform OR query while searching in firebase?

As @Puf said, you can't achieve it at Firebase Realtime Database but you can do it at client side which mean at the Android part.

First, you cannot use FirebaseUI which is you are currently using, instead you need to use https://firebase.google.com/docs/database/android/read-and-write#read_data

ValueEventListener postListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// You have to make for each loop
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
DoctorHelperClass doc = snapshot.getValue(DoctorHelperClass.class);
//List them in an array
docList.add(doc);
}
}

@Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
}
};
mPostReference.addValueEventListener(postListener);

Once you have added all the list of doctors. You can compare them using the arrayList.

You can do something like this.

private void searchDoc(final String inputDoc){
boolean isFound = false;
for (DoctorHelperClass doc in docList){
if (doc.getFullName() == inputDoc && doc.getHospitalName() == inputDoc){
isFound = true;
//Do something if found
}
}
}

I hope you get the concept of it.

How to search anywhere in string in Firebase Database - Android

To seach for a string within a String please use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference animalsRef = rootRef.child("Animals");
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Boolean found;
String search = "Animals";
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String movieName = ds.child("movieName").getValue(String.class);
found = movieName.contains(search);
Log.d("TAG", movieName + " / " + found);
}
}

@Override
public void onCancelled(DatabaseError databaseError) {}
};
animalsRef.addListenerForSingleValueEvent(eventListener);

As you see, we query the database for all the movie names and then search for the desired word within the movieName.

Android: Firebase query single word among values

Unfortunately, there is no query in Firebase real-time database that looks something like this:

mRef.child("app").orderByChild("cities").contains(city)

But for small datasets, there is a workaround that can help you solve this, which is by querying the database to get all the value for your cities property and use contains() method like this:

String str1 = dataSnapshot.child("cities").getValue(String.class);
String str2 = "london";
boolean b = str1.toLowerCase().contains(str2.toLowerCase());

If you'll try to print the value of b, you'll see that is true. But the above examples works well enough only for very small datasets, it doesn't work for large datasets and this is because downloading an entire object to search for fields client-side isn't practical. In this case, I recommend use a third-party search service like Algolia.

How to do a simple search in string in Firebase database?

In my case I was able to partly achieve a SQL LIKE in the following way:

databaseReference.orderByChild('_searchLastName')
.startAt(queryText)
.endAt(queryText+"\uf8ff")

The character \uf8ff used in the query is a very high code point in the Unicode range (it is a Private Usage Area [PUA] code). Because it is after most regular characters in Unicode, the query matches all values that start with queryText.

In this way, searching by "Fre" I could get the records having "Fred, Freddy, Frey" as value in _searchLastName property from the database.

Firebase realtime database query for specific field

In this line, you are awaiting the Reference itself - not fetching its data:

const userData = (await UsersDatabase.ref("Users").child("userData").orderByChild("Email").equalTo("test@domain.com"));

This line should be (fixed the query and shattered for readability):

const userData = (
await UsersDatabase.ref("Users")
.orderByChild("Email") // <-- removed .child("userData")
.equalTo("test@domain.com")
.once('value') // <-- this was missing
).val();

/*
userData will be:

{
"oi73WHp4T8LUCgtZzesN": { // <- this will be random
"Account Created":1647458347685,
"Date of Birth":"01/01/1901",
"Email":"test@domain.com",
"Gender":"male",
"Name":"Test Account"
}
}
*/

Although I would rewrite it like this to unwrap the data:


const foundUsersQuerySnapshot = await UsersDatabase.ref("Users")
.orderByChild("Email")
.equalTo("test@domain.com")
.limitToFirst(1)
.once('value');

let userData = null;
foundUsersQuerySnapshot.forEach(childSnapshot => {
userData = { ...childSnapshot.val(), _key: childSnapshot.key };
return true; // <- only return first entry
});

/*
userData will either be null (not found) or:

{
"_key": "oi73WHp4T8LUCgtZzesN",
"Account Created":1647458347685,
"Date of Birth":"01/01/1901",
"Email":"test@domain.com",
"Gender":"male",
"Name":"Test Account"
}
*/


Related Topics



Leave a reply



Submit