#!/usr/bin/env #coding:utf-8 from whoosh.fields import * from whoosh.index import create_in from whoosh.index import open_dir from whoosh.qparser import QueryParser def createIndexs(dirName): schema = Schema(title=TEXT(stored=True), path=ID(stored=True), content=TEXT) ix = create_in(dirName, 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.add_document(title=u"edc document", path=u"/c", content=u"The edc's demo!") p = writer.commit() def query(dirName,key): ix = open_dir(dirName) with ix.searcher() as searcher: query = QueryParser("title", ix.schema).parse(key) results = searcher.search(query) return {"total":len(results),"items":results} if __name__ == '__main__': createIndexs("indexDir") rt = query("indexdir",'document') print rt
執行代碼前保證文件夾"indexDir"已經存在,不然報錯。rest