I am working through The Flask Mega-Tutorial Part XVI and having troubles switching to Whoosh search engine.
As Miguel said, to switch from Elasticsearch to any other engines I just need to rewrite search.py functions.
I decided to do it with Whoosh. But searching is not working and just redirecting me to "explore" page.
Here is my 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'])
Here is 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') was added to config file too