Hasan A Yousef
Hasan A Yousef

Reputation: 24928

Query over list in firebase

I've the below custom model for firebase, I need to query for the cities with specific tags, I tried the below code but did not work :(

data class City(
        val name: String,
        val state: String?,
        val country: String,
        val capital: Boolean,
        val population: Long,
        val tags : List<String>
)

val sf = City("San Francisco", "CA", "USA",false,
            860000, listOf("tag 1", "tag 2", "tag 3"))

var cities = db.collection("cities")
cities.document("SF").set(sf)

val tags = "(tag 1)|(tag 5)".toRegex()
db.collection("cities")
            .whereEqualTo("name",tags)  // This is wrong 
            .get()
            .addOnCompleteListener { task ->
                if (task.isSuccessful) {
                    for (document in task.result) {
                        Log.d(TAG, document.id + " => " + document.data)
                    }
                } else {
                    Log.d(TAG, "Error getting documents: ", task.exception)
                }
            }

Upvotes: 0

Views: 445

Answers (2)

danh
danh

Reputation: 62686

My approach is to add some data to the searchable object on its onCreate trigger.

// for structured data...
// const myCity = { name: 'Baltimore', state: 'Maryland', country: 'USA' }
// const names = [myCity.name, myCity.state, myCity.country]

// or for strings, like names...
const names = ["Benjamin Franklin", "Franklin Delano Roosevelt"]

const searchArray = _.flatten(names.map(n => n.toLowerCase().split(' ')))
const searchObject = searchArray.reduce((acc, n) => {
  acc[n] = true;
  return acc
}, {})
console.log(searchObject)
// update the created object with searchObject
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.core.js"></script>

On the client (in JS), to do a search...

// say you're searching for "Franklin"
let searchTerm = "Franklin"

const key = `searchObject.${searchTerm.toLowerCase()}`
const query = db.collection("MyCollection").where(key, '==', true)

Upvotes: 1

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

Firestore queries only support equality and range operations. They don't support regular expressions. You will have to perform two queries and merge the result on the client.

See:

Upvotes: 0

Related Questions