Skip to content
Advertisement

How to search in firebase database

I’m trying to filter the data from my database using this code:

fdb.orderByChild("title").startAt(searchquery).endAt(searchquery+"uf8ff").addValueEventListener(valuelistener2);

My database is like this:

  "g12" : {
    "Books" : {
      "-Mi_He4vHXOuKHNL7yeU" : {
        "title" : "Technical Sciences P1"
      },
      "-Mi_He50tUPTN9XDiVow" : {
        "title" : "Life Sciences"
      },
      "-Mi_He51dhQfl3RAjysQ" : {
        "title" : "Technical Sciences P2"
      }}

While the code works, it only returns the first value that matches the query and doesn’t fetch the rest of the data even though it matches.

If I put a “T” as my search query, I just get the first title “Technical Sciences P1 ” and don’t get the other one with P2

(Sorry for the vague and common question title, it’s just I’ve been looking for a solution for so long)

Advertisement

Answer

While the codes works, it only returns the first value that matches the query

That’s the expected behavior since Firebase Realtime Database does not support native indexing or search for text fields in database properties.

When you are using the following query:

fdb.orderByChild("title").startAt(searchquery).endAt(searchquery+"uf8ff")

It means that you are trying to get all elements that start with searchquery. For example, if you have a title called “Don Quixote” and you search for “Don”, your query will return the correct results. However, searching for “Quix” will yield no results.

You might consider downloading the entire node to search for fields client-side but this solution 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.

If you consider at some point in time to try using Cloud Firestore, please see the following example:

To see how it works with Cloud Firestore but in the same way, you can use it with Firebase Realtime Database.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement