Searcher's search()
has parameter filter
:
https://whoosh.readthedocs.io/en/latest/searching.html#filtering-results
For filtering you can use a query like
'author:"Name of Author" AND category:Genre'
To build filtering queries automatically, let's assume we have sets authors
and categories
:
from whoosh.query import *
from whoosh.qparser import MultifieldParser
if categories:
# Filter the search by selected categories:
if len(categories) > 1:
# Must be: Category1 OR Category2 OR Category3...
cat_q = Or([Term('category', x) for x in categories])
else:
# If there's just 1 category in the set:
cat_q = Term('category', next(iter(categories)))
print('Query to filter categories:', cat_q)
if authors:
# Filter the search by authors:
if len(authors) > 1:
# Must be: Author1 OR Author2 OR Author3...
aut_q = Or([Term('author', x) for x in authors])
else:
# If there's just 1 author in the set:
aut_q = Term('author', next(iter(authors)))
print('Query to filter authors:', au_q)
# Now combine the two filters:
if categories:
# Both fields are used for filtering:
final_filter = And([cat_q, aut_q])
else:
# Only authors:
final_filter = aut_q
elif categories:
# Only categories:
final_filter = cat_q
else:
# None:
final_filter = None
print('final_filter:', final_filter)
# Now parse the user query for 2 fields:
parser = MultifieldParser(["title", "summary"], ix.schema)
query = parser.parse(q1)
if final_filter is None:
results = s.search(query)
else:
# Using the filter:
results = s.search(query, filter=final_filter)