Firestore查询文档startswith一个字符串

Bis*_*Roy 27 java firebase google-cloud-firestore

是否可以查询firestore集合以获取以特定字符串开头的所有文档?

我已经阅读了文档,但没有找到任何合适的查询.

Gil*_*ert 46

你可以,但它很棘手.您需要搜索大于或等于所需字符串且小于后续密钥的文档.

例如,要查找包含'foo''bar'您一起凝视的字段的文档,请查询:

db.collection(c)
    .where('foo', '>=', 'bar')
    .where('foo', '<', 'bas');
Run Code Online (Sandbox Code Playgroud)

这实际上是我们在客户端实现中用于扫描与路径匹配的文档集合的技术.我们的后继密钥计算扫描程序调用,该扫描程序正在查找以当前用户ID开头的所有密钥.

  • 后继键绑定查询,使得结果仅包含以特定字符串开头的字符串.如果没有它只搜索foo> ='bar'也会返回'zoo',因为该字符串在词典上也比bar更大. (2认同)

Kyo*_*agi 30

与Gil Gilbert的回答相同.只是一个增强和一些示例代码.使用String.fromCharCodeString.charCodeAt

var strSearch = "start with text here";
var strlength = strSearch.length;
var strFrontCode = strSearch.slice(0, strlength-1);
var strEndCode = strSearch.slice(strlength-1, strSearch.length);

var startcode = strSearch;
var endcode= strFrontCode + String.fromCharCode(strEndCode.charCodeAt(0) + 1);
Run Code Online (Sandbox Code Playgroud)

然后过滤下面的代码.

db.collection(c)
.where('foo', '>=', startcode)
.where('foo', '<', endcode);
Run Code Online (Sandbox Code Playgroud)

适用于任何语言和任何Unicode.

警告:firestore中的所有搜索条件都是CASE SENSITIVE.

  • 也许这会击中 [此外,您只能在单个字段上执行范围比较 (&lt;、&lt;=、&gt;、&gt;=)](https://firebase.google.com/docs/firestore/query-data/queries ) (2认同)

kid*_*oca 18

用较短的版本扩展以前的答案:

  const text = 'start with text here';
  const end = text.replace(/.$/, c => String.fromCharCode(c.charCodeAt(0) + 1));

  query
    .where('stringField', '>=', text)
    .where('stringField', '<', end);
Run Code Online (Sandbox Code Playgroud)

IRL示例

async function search(startsWith = '') {
  let query = firestore.collection(COLLECTION.CLIENTS);

  if (startsWith) {
      const end = startsWith.replace(
        /.$/, c => String.fromCharCode(c.charCodeAt(0) + 1),
      );

      query = query
        .where('firstName', '>=', startsWith)
        .where('firstName', '<', end);
  }

  const result = await query
    .orderBy('firstName')
    .get();

  return result;
}
Run Code Online (Sandbox Code Playgroud)


dan*_*y74 8

我发现了这个,它非常适合startsWith

const q = query(
  collection(firebaseApp.db, 'capturedPhotos'),
  where('name', '>=', name),
  where('name', '<=', name + '\uf8ff')
)
Run Code Online (Sandbox Code Playgroud)


Ale*_*x.F 7

如果你来这里寻找 Dart/Flutter 版本

归功于 Kyojava 答案

final strFrontCode = term.substring(0, term.length - 1);
final strEndCode = term.characters.last;
final limit =
  strFrontCode + String.fromCharCode(strEndCode.codeUnitAt(0) + 1);

final snap = await FirebaseFirestore.instance
  .collection('someCollection')
  .where('someField', isGreaterThanOrEqualTo: term)
  .where('someField', isLessThan: limit)
  .get();
Run Code Online (Sandbox Code Playgroud)