更新:随着 Firebase Cloud Functions 的发布,还有另一种优雅的方法可以通过通过函数将 Firebase 连接到 Algolia https://github.com/firebase/functions-samples/tree/master/fulltext-search.这里的权衡是,Functions/Algolia 几乎是零维护,但与在 Node.js 中自行部署相比,成本可能会增加。
目前 Firebase 中没有内容搜索。随着 API 的不断扩展,许多更常见的搜索场景(例如按属性搜索)将被纳入 Firebase 中。
与此同时,当然也可以发展自己的业务。然而,搜索是一个广泛的主题(想想创建一个巨大的实时数据存储),被大大低估了,并且是应用程序的一个关键功能——您不想临时使用它,甚至不需要像 Firebase 这样的人来代表您提供。因此,采用可扩展的第三方工具来处理索引、搜索、标签/模式匹配、模糊逻辑、加权排名等通常更简单。
Firebase 博客的特色是关于使用 ElasticSearch 建立索引的博客文章 https://www.firebase.com/blog/2014-01-02-queries-part-two.html其中概述了一种将快速但功能极其强大的搜索引擎集成到 Firebase 后端的简单方法。
本质上,它分两步完成。监控数据并对其建立索引:
var Firebase = require('firebase');
var ElasticClient = require('elasticsearchclient')
// initialize our ElasticSearch API
var client = new ElasticClient({ host: 'localhost', port: 9200 });
// listen for changes to Firebase data
var fb = new Firebase('<INSTANCE>.firebaseio.com/widgets');
fb.on('child_added', createOrUpdateIndex);
fb.on('child_changed', createOrUpdateIndex);
fb.on('child_removed', removeIndex);
function createOrUpdateIndex(snap) {
client.index(this.index, this.type, snap.val(), snap.name())
.on('data', function(data) { console.log('indexed ', snap.name()); })
.on('error', function(err) { /* handle errors */ });
}
function removeIndex(snap) {
client.deleteDocument(this.index, this.type, snap.name(), function(error, data) {
if( error ) console.error('failed to delete', snap.name(), error);
else console.log('deleted', snap.name());
});
}
当你想进行搜索时查询索引:
<script src="elastic.min.js"></script>
<script src="elastic-jquery-client.min.js"></script>
<script>
ejs.client = ejs.jQueryClient('http://localhost:9200');
client.search({
index: 'firebase',
type: 'widget',
body: ejs.Request().query(ejs.MatchQuery('title', 'foo'))
}, function (error, response) {
// handle response
});
</script>
这里有一个示例和一个用于简化集成的第三方库。 http://firebase.github.io/flashlight/