搜索也很方便,一个简单的方法可以查询索引,因为它只是一个JS对象:
// Run a search
index.search(“foo”)
// Inspect the actual index to see which docs match a term
index2.tokenStore.root.f.o.o.docs
当我第一次接触全文索引,我对他所谓的"文档"有所迷惑-它包括了一个PDF或者一个办公文档以及任何一个数据库,很可能包括大堆的文本.
如果你不得不时刻构建索引,全文索引将会是愚蠢的,而Lunr则使索引自身的序列化和反序列化变得真正简单起来:
var serializedIndex = JSON.stringify(index1.toJSON())
var deserializedIndex = JSON.parse(serializedIndex)
var index2 = lunr.Index.load(deserializedIndex)
Index.toJSON也会返回一个“bean”风格的对象(而不是一个string)。我从来没有见过像这样的API,但是我喜欢这个创意——它给了你一个干净的Javascript对象,只带有需要被序列化的数据。
下面是索引的属性:
- corpusTokens – 已经排好序的token列表
- documentStore – 每一份文档的列表 – 系
- fields – 用来描述每一份文档的域 (类似于数据库中列)
- pipeline – 用来处理token的管道对象
- tokenStore – 每一份文档中关键词出现的位置和频率
这种索引最棒的一个特性是作业可以并行完成,然后作为一个map-reduce作业被整合。上述对象只有三个条目需要被整合,因为“域”和“管道”是静态的。下面就展示了再现步骤的实现(注意jQuery被引入了):
(function reduce(a, b) {
var j1 = a.toJSON();
var j2 = b.toJSON();
// The "unique" function does uniqueness by sorting,
// which we need here.
var corpusTokens =
$.unique(
$.merge(
$.merge([], j1.corpusTokens),
j2.corpusTokens));
// It's important to create new arrays and
// objects throughout, or else you modify
// the source indexes, which is disastrous.
var documentStore =
{store: $.extend({},
j1.documentStore.store,
j2.documentStore.store),
length: j1.documentStore.length + j2.documentStore.length};
var jt1 = j1.tokenStore;
var jt2 = j2.tokenStore;
// The 'true' here triggers a deep copy
var tokenStore = {
root: $.extend(true, {}, jt1.root, jt2.root),
length: jt1.length + jt2.length
};
return {version: j1.version,
fields: $.merge([], j1.fields),
ref: j1.ref,
documentStore: documentStore,
tokenStore: tokenStore,
corpusTokens: corpusTokens,
pipeline: $.merge([], j1.pipeline)};
})(index1, index2)
通过创建三个索引我测试了这段代码:index1,index2和index3。index1是{doc1},index2是{doc2,doc3},而index3则是{doc1,doc2,doc3}。为了测试这段代码,你需要简单的改变:
JSON.stringify(index3.toJSON())
JSON.stringify(combine(index1, index2))
可能性
总的来说这项技术很浪费网络I/O,使得这看起来很傻。从另外一方面来看,ebay和fiberr上待售清单上充斥着“网络交通流量”的叫卖,通常来自背后弹出式广告,僵尸网络,隐藏的iframe等等。你能很容易的发现像“3美元20000次点击”的列表,小批量的。因为没有多少商业价值它通常是很便宜的,此外还得犯下各种形式的欺诈行为。
你需要一个便宜点的VM负载作为一个代理的带宽,以及公共可用的数据——你不能将其作为一项针对浏览器跨域请求保护的搜刮技术。你也需要使用一种独特的方式来生成单独的文档ID,也许要使用到原生的URL。
如果一种交通资源在现代浏览器上面运行,某些人就可能会将其作为一种潜在的廉价且拥有无限制处理能力的资源来加以利用,即使是出于整合索引的目的,尽管必须针对系统的自然不稳定性做出规定。
