Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if any documents in Firestore contain a substring [duplicate]

I have a pretty large collection of documents in Firestore with random IDs and each one of those documents has two fields, a name and a description. I want my app to allow the user to enter a series of characters and then present to him all the documents which contain that sequence of chars in let's say the name field. Is this feasible using Firebase & its queries and if so, could you give me a code example in Kotlin or Java? I know there are some methods such as hasChild() or child("child name").exists() but since i don't yet know which document the user is looking for i can't use them if i'm not mistaken.

For example, if i had a collection of 3 documents which had the following names ("mike","michael","dave") and the user entered "mi", i'd like to be able to retrieve the documents whose names are "mike" & "michael".

like image 627
Stelios Papamichail Avatar asked Mar 20 '26 06:03

Stelios Papamichail


1 Answers

If you want to get all documents where the name field starts with mi, you can do so with:

db.collection("users")
  .whereGreaterThanOrEqualTo("name", "mi")
  .whereLessThanOrEqualTo("name", "mi\uF7FF")
  .get()
  .addOnSuccessListener { documents ->
    for (document in documents) {
      Log.d(TAG, "${document.id} => ${document.data}")
    }
  }
    .addOnFailureListener { exception ->
        Log.w(TAG, "Error getting documents: ", exception)
    }

The \uF7FF value used here is the last Unicode character that exists, so this:

  1. Orders all documents by their name value
  2. Finds the first document that starts with mi
  3. returns all documents, until it reaches one that's bigger than mi

For much more on this, read the Firebase documentation on querying data.

I also recommend checking out these related questions:

  • Google Firestore: Query on substring of a property value (text search)
  • Cloud Firestore Case Insensitive Sorting Using Query
like image 54
Frank van Puffelen Avatar answered Mar 21 '26 20:03

Frank van Puffelen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!