Firestore查询文档startswith一个字符串

时间:2017-10-04 20:40:32

标签: java firebase google-cloud-firestore

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

我已浏览过文档但未找到任何合适的查询。

5 个答案:

答案 0 :(得分:36)

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

例如,要查找包含import pytesseract im = imageOfDate im = pytesseract.image_to_string(im, config='outputbase digits') print(im) 字段'foo'的文档,您会查询:

'bar'

这实际上是我们在客户端实现中用于扫描与路径匹配的文档集合的技术。我们的successor key computationscanner调用,它正在寻找以当前用户ID开头的所有密钥。

答案 1 :(得分:24)

与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);

然后过滤下面的代码。

db.collection(c)
.where('foo', '>=', startcode)
.where('foo', '<', endcode);

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

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

答案 2 :(得分:3)

使用更短的版本扩展先前的答案:

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

  query
    .where('stringField', '>=', text)
    .where('stringField', '<', end);

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;
}

答案 3 :(得分:2)

以上是正确的!只是想给出一个更新的答案!

var end = s[s.length-1]
val newEnding = ++end

var newString = s
newString.dropLast(1)
newString += newEnding

query
  .whereGreaterThanOrEqualTo(key, s)
  .whereLessThan(key, newString)
  .get()

答案 4 :(得分:1)

如果您在这里寻找Dart / Flutter版本

贷记到java answer by Kyo

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();