环境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])