有没有办法在 Firestore 中搜索子字符串? [英] Is there a way to search sub string at Firestore?

查看:28
本文介绍了有没有办法在 Firestore 中搜索子字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果 firestore 数据库中有一个名为 'California' 的字符串,并且我想从 android 应用程序中搜索为 'Cali' 那么 firebase 应该返回我加利福尼亚.我怎样才能做那个查询?

If there is a String named 'California' at firestore database and i want to search from android app as 'Cali' then the firebase should return me California. How can i do that query?

firestore 有一些功能,比如,

There has some function at firestore like,

db.collection("cities").whereEqualTo("name", "Cali")
 db.collection("cities").whereLessThan("name", "Cali")
 db.collection("cities").whereGreaterThanOrEqualTo("name", "Cali")
 db.collection("cities").whereGreaterThan("name", "Cali")
 db.collection("cities").whereGreaterThanOrEqualTo("name", "Cali")

但我需要一个像 as 的函数,

But i need a function like as,

db.collection("cities").whereContain("name", "Cali")

应该返回包含Cali"子字符串的完整字符串.

which should return full string that contains 'Cali' substring.

推荐答案

很遗憾,Firestore 中没有这样的查询:

Unfortunately, there is no query in Firestore that looks like this:

db.collection("cities").whereContains("name", "Cali")

但是对于小数据集,有一种解决方法可以帮助您解决这个问题,即通过查询数据库获取所有城市名称并使用 contains() 方法,如下所示:

But for small datasets, there is a workaround that can help you solve this, which is by querying the database to get all city names and use contains() method like this:

String str1 = document.getString("yourProperty");
String str2 = "Cali";
boolean b = str1.toLowerCase().contains(str2.toLowerCase());

如果您尝试打印 b 的值,您会看到它是 true.但是上面的例子仅适用于数据集,它不适用于大型数据集,这是因为下载整个集合来搜索客户端的字段是不切实际的.在这种情况下,正如 官方文档 所建议的那样:

If you'll try to print the value of b, you'll see that is true. But the above examples works well enough only for small datasets, it doesn't work for large datasets and this is because downloading an entire collection to search for fields client-side isn't practical. In this case, as the official documentation recommends:

要启用对 Cloud Firestore 数据的全文搜索,请使用第三方搜索服务,例如 Algolia.

To enable full text search of your Cloud Firestore data, use a third-party search service like Algolia.

有关具体示例,另请参阅我的回答 发布.

For a concrete example, please also see my answer from this post.

这篇关于有没有办法在 Firestore 中搜索子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆