Whooshで全文検索してみました。
WhooshはピュアPythonな検索ライブラリです。
Whooshのインストール
pipでインストールできます。
$ pip3 install whoosh
英語のテキストを登録して検索
テキストを登録する。
add.py
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()
テキストを検索する。
search.py
from whoosh.index import open_dir
from whoosh.fields import *
from whoosh.qparser import QueryParser
schema = Schema(title=TEXT(stored=True), path=ID(stored=True), content=TEXT)
ix = open_dir('indexdir')
with ix.searcher() as searcher:
query = QueryParser("content", ix.schema).parse("first")
results = searcher.search(query)
print(results)
for r in results:
print(r)
実行してみた。
$ python3 add.py
$ python3 search.py
<Hit {'path': '/a', 'title': 'First document'}>
検索用のindexは指定したディレクトリに作成される。
$ ls indexdir/
MAIN_WRITELOCK MAIN_nhzytp3bq1twwpkx.seg _MAIN_1.toc