查询firebase中的列表

时间:2018-06-08 22:47:30

标签: android firebase google-cloud-firestore

我有以下自定义的firebase模型,我需要查询具有特定标签的城市,我尝试了下面的代码,但没有用:(

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)
                }
            }

2 个答案:

答案 0 :(得分:1)

我的方法是在onCreate触发器上向可搜索对象添加一些数据。

// 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>

在客户端(在JS中)上进行搜索...

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

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

答案 1 :(得分:0)

Firestore查询仅支持相等和范围操作。他们不支持正则表达式。您必须执行两个查询并将结果合并到客户端上。

请参阅: