有没有办法在Firestore中搜索子字符串? [英] Is there a way to search sub string at 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")
但是我需要像这样的功能
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 .
For a concrete example, please also see my answer from this post.
这篇关于有没有办法在Firestore中搜索子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!