python使用whoos搜索入門【上篇】

環境python2.7:

#  本來py3 的環境,由於一直報錯找不到 whoosh 模塊 換了2.7 就解決了

 

pip install whoosh

 

#!/user/bin/env python    
#-*- coding:utf-8 -*-



from whoosh.index import create_in
from whoosh.fields import *
from whoosh.qparser import QueryParser


#  建立索引對象 和字段
schema = Schema(title=TEXT(stored=True), path=ID(stored=True), content=TEXT)

ix = create_in("indexdir/", schema)  # indexdir  在這個目錄下創建索引文件


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()  # 寫入完成提交


#  創建搜索對象寫入查詢數據
with ix.searcher() as searcher:
    query = QueryParser("content", ix.schema).parse("first")
    results = searcher.search(query)
    print(results[0])


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章