有没有办法在 Firestore 中搜索子字符串?

Rez*_*rim 4 android firebase google-cloud-firestore

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

firestore有一些功能,比如,

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")
Run Code Online (Sandbox Code Playgroud)

但我需要一个像这样的功能,

db.collection("cities").whereContain("name", "Cali")
Run Code Online (Sandbox Code Playgroud)

它应该返回包含“Cali”子字符串的完整字符串。

Ale*_*amo 7

不幸的是,Firestore 中没有这样的查询:

db.collection("cities").whereContains("name", "Cali")
Run Code Online (Sandbox Code Playgroud)

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

String str1 = document.getString("yourProperty");
String str2 = "Cali";
boolean b = str1.toLowerCase().contains(str2.toLowerCase());
Run Code Online (Sandbox Code Playgroud)

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

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

有关具体示例,另请参阅我在这篇文章中的回答。