用 Whoosh 取代 Elasticsearch

问题描述 投票:0回答:1

我正在学习 Flask 大型教程第 XVI 部分,但在切换到 Whoosh 搜索引擎时遇到问题。

正如 Miguel 所说,要从 Elasticsearch 切换到任何其他引擎,我只需要重写 search.py 函数。

我决定用 Whoosh 来做这件事。但搜索不起作用,只是将我重定向到“探索”页面。

这是我的init.py

...
from whoosh.index import create_in, open_dir
from whoosh.fields import Schema, TEXT, ID
...

def create_app(config_class=Config):
    ...
    init_whoosh(app)
    ...

def init_whoosh(app):
    schema = Schema(
        id = ID(stored=True),
        title = TEXT(stored=True),
        content = TEXT
    )

    with app.app_context():
        if not os.path.exists(current_app.config['WHOOSH_INDEX_DIR']):
            os.mkdir(current_app.config['WHOOSH_INDEX_DIR'])
            app.whoosh_index = create_in(current_app.config['WHOOSH_INDEX_DIR'], schema)
        else:
            app.whoosh_index = open_dir(current_app.config['WHOOSH_INDEX_DIR'])

这里是search.py

from whoosh.qparser import MultifieldParser

def add_to_index(index, model):
    writer = index.writer()
    doc = {
        "id": str(model.id),
        "title": model.title,
        "content": model.content,
    }
    writer.add_document(**doc)
    writer.commit()

def remove_from_index(index, model):
    writer = index.writer()
    writer.delete_by_term("id", str(model.id))
    writer.commit()

def query_index(index, query, page, per_page):
    searcher = index.searcher()
    parser = MultifieldParser(["title", "content"], schema=index.schema)
    parsed_query = parser.parse(query)
    results = searcher.search_page(parsed_query, page, pagelen=per_page)
    ids = [int(result["id"]) for result in results]
    return ids, results.total

WHOOSH_INDEX_DIR = os.path.join(basedir, 'whoosh_index')
也被添加到配置文件中

python flask whoosh
1个回答
0
投票

要将 Whoosh 搜索引擎添加到 Flask 应用程序中,您可以使用 flask-whooshee

© www.soinside.com 2019 - 2024. All rights reserved.