如何基于Firestore数据库中的字段从集合中搜索文档?

时间:2019-05-06 08:02:37

标签: firebase react-native firebase-realtime-database google-cloud-firestore

我正在使用React Native应用程序,并且正在从firebase集合中获取配置文件。 我想添加一个搜索功能,当我输入用户名的前1个或2个(或更多)字母并按搜索按钮时,就可以添加该功能。 我应该能够获取以1或2个字母开头的用户名。

我确实检查了Cloud Firestore查询,但找不到我的问题。

更新的问题:

enter image description here

在上面的代码中,我添加了下面的代码,正如Renaud Tarnec回答的那样。

 let queries = hashes.map(hash => rangeQueryParams(hash))
            .map(range => profiles.where('hash', '>=', range.start).where('hash', '<', range.end)
            .orderBy('displayName') // displayName is the name of Field here
            .startAt(searchString)
            .endAt(searchString + '\uf8ff')
            .get());

但这似乎不起作用。我猜这是因为范围过滤器和orderBy在这里位于不同的字段。

2 个答案:

答案 0 :(得分:2)

您应该结合使用orderBy()startAt()endAt(),请参阅此处的文档:https://firebase.google.com/docs/firestore/query-data/order-limit-data?authuser=0

 var searchString = 'Sh'   //Example of value
 firebase
      .firestore()
      .collection('yourCollectioName')
      .orderBy('username')
      .startAt(searchString)
      .endAt(searchString + '\uf8ff')
      .get()
  .then(...)

查询中使用的字符\uf8ff在Unicode中大多数常规字符之后,因此查询匹配所有以searchString开头的值。

答案 1 :(得分:0)

Firebase建议的全文搜索方法是使用Algolia https://firebase.google.com/docs/firestore/solutions/search

使用Firestore的查询(以开始于和结束于有序集合)确实可行。例如,如果您需要在其他需要拼写容忍等功能的应用中进行全文搜索,则值得考虑使用Algolia,而不是使用复合式Firestore查询