有人能解释一下如何查询 Firebase 的特殊字符吗?
我有一些这样的数据 -
posts
post_1
description: "This is a post! #thisdoesntwork"
post_2
description: "Heres another post! #neitherdoesthis"
如果我快速运行查询 -
let db = Database.database().reference()
db.child("posts").queryOrdered(byChild: "description").queryStarting(atValue: "[a-zA-Z0-9]*").queryEnding(atValue: "#thisdoesntwork").observeSingleEvent(of: .value) { (snapshot) in
// No results!
}
什么也得不到。但是,当我像这样省略主题标签时它会起作用 -
db.child("posts").queryOrdered(byChild: "description").queryStarting(atValue: "[a-zA-Z0-9]*").queryEnding(atValue: "thisdoesntwork").observeSingleEvent(of: .value) { (snapshot) in
// One post gets returned here
}
这是因为哈希是我需要以某种方式转义的特殊字符吗?还是我以错误的方式查询它?
提前致谢。
你认为正在发生的不是。让我解释并提供一个例子:
看来您正在尝试执行字符串搜索。甚至可能是子字符串搜索。
Firebase 不提供子字符串搜索功能,甚至字符串搜索也不完全是字符串搜索,就像在 swift 这样的语言中一样。
所以对于初学者来说这是无效的
queryStarting(atValue: "[a-zA-Z0-9]*")
这将逐字搜索以等于 [a-zA-Z0-9]* 的字符串或字符开头的节点。因此,如果您的节点碰巧如下所示:
posts
post_x
description: "[a-zA-Z0-9]* This node would be returned"
这将是一场比赛。
.startWith: a query that starts with the given string
.endWith: a query ending with a string that starts with the given string
(not the ending part of a string or a substring)
让我根据您的结构提供一个示例结构
posts
post_1
description: "This is a post! #thisdoesntwork"
post_2
description: "Heres another post! #neitherdoesthis"
post_3
description: "a"
post_4
description: "n"
和一个示例查询
let postsRef = ref.child("posts")
let queryRef = postsRef.queryOrdered(byChild: "description")
.queryStarting(atValue: "This")
.queryEnding(atValue: "z")
queryRef.observeSingleEvent(of: .value) { snapshot in
print(snapshot)
}
此查询将返回帖子 1、3 和 4。为什么?
post_1 以大写字母 T 开头,即 ascii 84。
该查询将返回具有以 84 (ascii T) 开头并以 122 (ascii z) 结尾的 ascii 值的所有节点。所以 post 3 是一个 a,它是 ascii 97,post 4,一个 n,是 ascii 110。所以所有这些都被返回。
*对于后面的人,查询实际上以单词“This”开头,以单词“z”结尾,但在此示例中进行了简化。
虽然一方面这似乎有点限制,但它实际上非常强大。
一种用途是当您要查询以特定字符串开头的一系列值时。假设您拥有一家农产品分销公司,并拥有苹果、香蕉、花生和核桃等产品。你可以像这样组织你的数据库
items
item_0
description: fruit_apple
item_1
description: fruit_banana
item_2
description: nut_peanut
item_3
description: nut_walnut
如果您想要所有水果的列表,您可以像这样查询
let queryRef = postsRef.queryOrdered(byChild: "description")
.queryStarting(atValue: "fruit_")
.queryEnding(atValue: "fruit_")
这称为复合值。
在您的情况下,底线答案是您不能直接搜索字符串中的特殊字符,但是,您可以搜索以 ascii 代码范围内的字符开头的一系列字符。
以“!”开头的查询 并以“/”结尾将返回所有以字符开头的字符串:
33 !
34 \"
35 #
36 $
37 %
38 &
39 '
40 (
41 )
42 *
43 +
44 ,
45 -
46 .
47 /
这个超长的答案并不是真正的解决方案,但可能有助于重组您的 Firebase,以便您可以获取要查询的数据。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句