Home > Software engineering >  Query and algorithms using firestore db?
Query and algorithms using firestore db?

Time:01-29

I am currently trying to figure out how to match and/or compare data in firestore database. Lets say I have 10 apples. My apple has the color red. I want to be able to compare my color to the other 10 apples and then match only with the ones who has the color red (there are 2 apples with the color red). How can I achieve this while using firestore database as the main database for all apples?

Firebase Db looks something like this:

enter image description here

apple1 is red and should match with apple5. The rest are different colors. When the user press the search button, it should filter the firestore Db and only match with the adequate respons (in this case apple5 which is also red) How can I achieve this? Do I need to use a third party library to create this algorithm or can it be done in kotlin since it is to my understanding that some features does not work with firestore Db? Appreciate any feedback!

CodePudding user response:

That's a pretty straightforward query, 'fetch documents where the value of field color is red'. Try:

db.collection("apples")
        .whereEqualTo("color", "red")
        .get()
        .addOnSuccessListener { documents ->
            for (document in documents) {
                Log.d(TAG, "${document.id} => ${document.data}")
            }
        }
        .addOnFailureListener { exception ->
            Log.w(TAG, "Error getting documents: ", exception)
        }

Checkout the documentation for more query examples that Firestore supports.

CodePudding user response:

Basically, you can use Queries to match a certain condition and get all documents.

For your case, you can use the following code snippet to get the data based on color

try {
AsyncSnapshot<QuerySnapshot> data = firestore.collection("hubs")
                                    .where("color", isEqualTo: "red")
                                    .get();
final docs = data.data!.docs; 

docs.forEach((e)=>{
    //each firestore document
});
}

Find the official documentation here.

  • Related