Whoosh搜索引擎
whoosh 是一个纯python实现的全文搜索引擎,它小巧轻便,安装简单,设计上参考了 Lucene ,性能上虽有欠缺,但贵在方便,无需复杂安装,对于构建小型网站的搜索引擎来说,是一个不错的选择。
1. 快速入门
whoosh 可以使用pip进行安装
pip install whoosh
现在通过官网的例子,快速体验
from whoosh.index import create_in
from whoosh.fields import *
# 构建索引
schema = Schema(title=TEXT(stored=True), path=ID(stored=True), content=TEXT)
ix = create_in("indexdir", schema)
writer = ix.writer()
writer.add_document(title=u"First document", path=u"/a",content=u"This is the first document we've added!")
writer.add_document(title=u"Second document", path=u"/b", content=u"The second one is even more interesting!")
writer.commit()
# 搜索
from whoosh.qparser import QueryParser
with ix.searcher() as searcher:
query = QueryParser("content", ix.schema).parse("first")
results = searcher.search(query)
print(results[0])
程序最终输出结果为
官网上的例子,我没有做任何修改,只是添加了两行注释。整个程序分为两部分,第一部分是构建索引的过程,第二部分是搜索的过程。
2. 构建索引