whoosh搜索引擎使用

1
pip install whoosh
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
from ast import And
from fileinput import filename
from msilib.schema import tables
import os.path
from tokenize import String
from whoosh.index import create_in
from whoosh.index import open_dir
from whoosh.fields import *
# from jieba.analyse import ChineseAnalyzer
schema = Schema(fileName=TEXT(stored=True),content=TEXT(stored=True))
filepath = "./tmp/indexfile"
if not os.path.exists(filepath):     #如果目录 index_data 不存在则创建
    # os.mkdir(filepath)
    os.makedirs(filepath) 
ix = create_in(filepath,schema)      #按照之前创建的schema模式建立索引目录
ix = open_dir(filepath)           #打开该目录一遍存储索引文件

# writer.close()
def writeFile():
    writer = ix.writer()
    writer.add_document(fileName=u"my document", content=u"this is my document")
    writer.add_document(fileName=u"my second document", content=u"this el-column is my second document",)
    writer.commit()

def searchByKey(key):
    from whoosh.qparser import QueryParser
    with ix.searcher() as searcher:
        # And()s
        query = QueryParser("content",ix.schema).parse(key)

        result = searcher.search(query,limit=20)
        print(result)
        for v in result:
            print(v)

writeFile()
searchByKey("this is  el-column")

其他笔记

[[post/11.个人总结/中间件/搜索引擎/lucene|lucene学习]]