I will mark this question as a duplicate, but this code might be helpful for you to get started building your own search index:
(我会将这个问题标记为重复,但是以下代码可能对您开始构建自己的搜索索引很有帮助:)
var ref = new Firebase('https://yours.firebaseio.com/users');
var index = new Firebase('https://yours.firebaseio.com/index');
function createIndex() {
ref.once('value', function(snapshot) {
snapshot.forEach(function(userSnapshot) {
var user = userSnapshot.val();
index.child(user.age).child(userSnapshot.key()).set(true);
Object.keys(user.activities).forEach(function(activity) {
index.child(activity).child(userSnapshot.key()).set(true);
});
});
});
}
Since you want to search across all users, the code loops over all users (you should normally do this when the users are added or modified, so by listening for the child_
events).
(由于要在所有用户之间进行搜索,因此代码会在所有用户上循环(通常应在添加或修改用户时执行此操作,因此可以侦听child_
事件)。)
It then adds the relevant nodes to the index: one for the age and one for every category.(然后将相关节点添加到索引:一个用于年龄,一个用于每个类别。)
After running this on your data, the index
node looks like this:
(在数据上运行之后, index
节点如下所示:)
{
"21": {"123":true},
"30":{"124":true},
"bike":{"124":true},
"horse":{"123":true}
}
So with that you can get all users that are between 20 and 30 by:
(这样一来,您可以通过以下方式获得20至30岁之间的所有用户:)
ref.orderByKey().startAt("20").endAt("30").on('child_added'
Or all users with a "horse" activity by:
(或通过以下方式进行“马”活动的所有用户:)
ref.orderByKey().equalTo("horse").on('child_added'
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…