LoginSignup
3
2

More than 5 years have passed since last update.

Whooshで全文検索

Last updated at Posted at 2019-01-02

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
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2