Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

It is possible to have a contains search query in firebase? [duplicate]

I tried this:

Query firebaseSearchQuery = 
myRef.orderByChild("from").startAt(searchText).endAt(searchText+"\uf8ff");

but i want something like this

Query firebaseSearchQuery = 
myRef.orderByChild("from").contains(searchText);

it is possible ?

like image 478
Angelo Lucena Avatar asked Jul 21 '18 04:07

Angelo Lucena


People also ask

What is getKey () in firebase?

public String getKey () Returns. The key name for the source location of this snapshot or null if this snapshot points to the database root.

Can we use SQL queries in firebase?

FireSQL is a library built on top of the official Firebase SDK that allows you to query Cloud Firestore using SQL syntax. It's smart enough to issue the minimum amount of queries necessary to the Firestore servers in order to get the data that you request.

What is DataSnapshot in firebase?

A DataSnapshot is an efficiently-generated immutable copy of the data at a Firebase Location.


2 Answers

For small datasets you can use the following code:

ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        List<String> list = new ArrayList<>();
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String from = ds.child("from").getValue(String.class);
            list.add(from);
        }

        for(String str : list) {
            if(str.contains(searchText)) {
                Log.d("TAG", "String found!");
            }
        }
    }

    @Override
    public void onCancelled(DatabaseError error) {
        Log.d("TAG", error.getMessage()); //Never ignore potential errors!
    }
};
myRef.addListenerForSingleValueEvent(valueEventListener);

This solution is not recommended for large datasets because you'll need to download the entire node in order to make a search. In this case, Algolia or Elasticsearch are recommended.

If you intend to use Cloud Firestore, I recommend you to see my answer from this post. For more information, I also recommend you see this video.

like image 78
Alex Mamo Avatar answered Oct 04 '22 16:10

Alex Mamo


You need maybe this:

Query firebaseSearchQuery = myRef.orderByChild("from").equalTo(searchText + "\uf8ff");

EDIT

I guess it is not possible using firebase, it needs a special service in order to be done. A service that has to do with advanced searching (something like elastic search).

like image 26
Hasan Bou Taam Avatar answered Oct 04 '22 14:10

Hasan Bou Taam