searching module

This module contains classes and functions related to searching the index.

Searching classes

class whoosh.searching.Searcher(reader, weighting=<class 'whoosh.scoring.BM25F'>, closereader=True, fromindex=None, parent=None)

Wraps an IndexReader object and provides methods for searching the index.

Parameters:
  • reader – An IndexReader object for the index to search.
  • weighting – A whoosh.scoring.Weighting object to use to score found documents.
  • closereader – Whether the underlying reader will be closed when the searcher is closed.
  • fromindex – An optional reference to the index of the underlying reader. This is required for Searcher.up_to_date() and Searcher.refresh() to work.
boolean_context()

Shortcut returns a SearchContext set for unscored (boolean) searching.

collector(limit=10, sortedby=None, reverse=False, groupedby=None, collapse=None, collapse_limit=1, collapse_order=None, optimize=True, filter=None, mask=None, terms=False, maptype=None, scored=True)

Low-level method: returns a configured whoosh.collectors.Collector object based on the given arguments. You can use this object with Searcher.search_with_collector() to search.

See the documentation for the Searcher.search() method for a description of the parameters.

This method may be useful to get a basic collector object and then wrap it with another collector from whoosh.collectors or with a custom collector of your own:

# Equivalent of
# results = mysearcher.search(myquery, limit=10)
# but with a time limt...

# Create a TopCollector
c = mysearcher.collector(limit=10)

# Wrap it with a TimeLimitedCollector with a time limit of
# 10.5 seconds
from whoosh.collectors import TimeLimitedCollector
c = TimeLimitCollector(c, 10.5)

# Search using the custom collector
results = mysearcher.search_with_collector(myquery, c)
context(**kwargs)

Generates a SearchContext for this searcher.

correct_query(q, qstring, correctors=None, terms=None, maxdist=2, prefix=0, aliases=None)

Returns a corrected version of the given user query using a default whoosh.spelling.ReaderCorrector.

The default:

  • Corrects any words that don’t appear in the index.
  • Takes suggestions from the words in the index. To make certain fields use custom correctors, use the correctors argument to pass a dictionary mapping field names to whoosh.spelling.Corrector objects.

Expert users who want more sophisticated correction behavior can create a custom whoosh.spelling.QueryCorrector and use that instead of this method.

Returns a whoosh.spelling.Correction object with a query attribute containing the corrected whoosh.query.Query object and a string attributes containing the corrected query string.

>>> from whoosh import qparser, highlight
>>> qtext = 'mary "litle lamb"'
>>> q = qparser.QueryParser("text", myindex.schema)
>>> mysearcher = myindex.searcher()
>>> correction = mysearcher().correct_query(q, qtext)
>>> correction.query
<query.And ...>
>>> correction.string
'mary "little lamb"'
>>> mysearcher.close()

You can use the Correction object’s format_string method to format the corrected query string using a whoosh.highlight.Formatter object. For example, you can format the corrected string as HTML, emphasizing the changed words.

>>> hf = highlight.HtmlFormatter(classname="change")
>>> correction.format_string(hf)
'mary "<strong class="change term0">little</strong> lamb"'
Parameters:
  • q – the whoosh.query.Query object to correct.
  • qstring – the original user query from which the query object was created. You can pass None instead of a string, in which the second item in the returned tuple will also be None.
  • correctors – an optional dictionary mapping fieldnames to whoosh.spelling.Corrector objects. By default, this method uses the contents of the index to spell check the terms in the query. You can use this argument to “override” some fields with a different correct, for example a whoosh.spelling.GraphCorrector.
  • terms – a sequence of ("fieldname", "text") tuples to correct in the query. By default, this method corrects terms that don’t appear in the index. You can use this argument to override that behavior and explicitly specify the terms that should be corrected.
  • maxdist – the maximum number of “edits” (insertions, deletions, subsitutions, or transpositions of letters) allowed between the original word and any suggestion. Values higher than 2 may be slow.
  • prefix – suggested replacement words must share this number of initial characters with the original word. Increasing this even to just 1 can dramatically speed up suggestions, and may be justifiable since spellling mistakes rarely involve the first letter of a word.
  • aliases – an optional dictionary mapping field names in the query to different field names to use as the source of spelling suggestions. The mappings in correctors are applied after this.
Return type:

whoosh.spelling.Correction

doc_count()

Returns the number of UNDELETED documents in the index.

doc_count_all()

Returns the total number of documents, DELETED OR UNDELETED, in the index.

docs_for_query(q, for_deletion=False)

Returns an iterator of document numbers for documents matching the given whoosh.query.Query object.

document(**kw)

Convenience method returns the stored fields of a document matching the given keyword arguments, where the keyword keys are field names and the values are terms that must appear in the field.

This method is equivalent to:

searcher.stored_fields(searcher.document_number(<keyword args>))

Where Searcher.documents() returns a generator, this function returns either a dictionary or None. Use it when you assume the given keyword arguments either match zero or one documents (i.e. at least one of the fields is a unique key).

>>> stored_fields = searcher.document(path=u"/a/b")
>>> if stored_fields:
...   print(stored_fields['title'])
... else:
...   print("There is no document with the path /a/b")
document_number(**kw)

Returns the document number of the document matching the given keyword arguments, where the keyword keys are field names and the values are terms that must appear in the field.

>>> docnum = searcher.document_number(path=u"/a/b")

Where Searcher.document_numbers() returns a generator, this function returns either an int or None. Use it when you assume the given keyword arguments either match zero or one documents (i.e. at least one of the fields is a unique key).

Return type:int
document_numbers(**kw)

Returns a generator of the document numbers for documents matching the given keyword arguments, where the keyword keys are field names and the values are terms that must appear in the field. If you do not specify any arguments (Searcher.document_numbers()), this method will yield all document numbers.

>>> docnums = list(searcher.document_numbers(emailto="matt@whoosh.ca"))
documents(**kw)

Convenience method returns the stored fields of a document matching the given keyword arguments, where the keyword keys are field names and the values are terms that must appear in the field.

Returns a generator of dictionaries containing the stored fields of any documents matching the keyword arguments. If you do not specify any arguments (Searcher.documents()), this method will yield all documents.

>>> for stored_fields in searcher.documents(emailto=u"matt@whoosh.ca"):
...   print("Email subject:", stored_fields['subject'])
get_parent()

Returns the parent of this searcher (if has_parent() is True), or else self.

idf(fieldname, text)

Calculates the Inverse Document Frequency of the current term (calls idf() on the searcher’s Weighting object).

key_terms(docnums, fieldname, numterms=5, model=<class 'whoosh.classify.Bo1Model'>, normalize=True)

Returns the ‘numterms’ most important terms from the documents listed (by number) in ‘docnums’. You can get document numbers for the documents your interested in with the document_number() and document_numbers() methods.

“Most important” is generally defined as terms that occur frequently in the top hits but relatively infrequently in the collection as a whole.

>>> docnum = searcher.document_number(path=u"/a/b")
>>> keywords_and_scores = searcher.key_terms([docnum], "content")

This method returns a list of (“term”, score) tuples. The score may be useful if you want to know the “strength” of the key terms, however to just get the terms themselves you can just do this:

>>> kws = [kw for kw, score in searcher.key_terms([docnum], "content")]
Parameters:
  • fieldname – Look at the terms in this field. This field must store vectors.
  • docnums – A sequence of document numbers specifying which documents to extract key terms from.
  • numterms – Return this number of important terms.
  • model – The classify.ExpansionModel to use. See the classify module.
  • normalize – normalize the scores.
Returns:

a list of (“term”, score) tuples.

key_terms_from_text(fieldname, text, numterms=5, model=<class 'whoosh.classify.Bo1Model'>, normalize=True)

Return the ‘numterms’ most important terms from the given text.

Parameters:
  • numterms – Return this number of important terms.
  • model – The classify.ExpansionModel to use. See the classify module.
more_like(docnum, fieldname, text=None, top=10, numterms=5, model=<class 'whoosh.classify.Bo1Model'>, normalize=False, filter=None)

Returns a Results object containing documents similar to the given document, based on “key terms” in the given field:

# Get the ID for the document you're interested in
docnum = search.document_number(path=u"/a/b/c")

r = searcher.more_like(docnum)

print("Documents like", searcher.stored_fields(docnum)["title"])
for hit in r:
    print(hit["title"])
Parameters:
  • fieldname – the name of the field to use to test similarity.
  • text – by default, the method will attempt to load the contents of the field from the stored fields for the document, or from a term vector. If the field isn’t stored or vectored in the index, but you have access to the text another way (for example, loading from a file or a database), you can supply it using the text parameter.
  • top – the number of results to return.
  • numterms – the number of “key terms” to extract from the hit and search for. Using more terms is slower but gives potentially more and more accurate results.
  • model – (expert) a whoosh.classify.ExpansionModel to use to compute “key terms”.
  • normalize – whether to normalize term weights.
  • filter – a query, Results object, or set of docnums. The results will only contain documents that are also in the filter object.
postings(fieldname, text, weighting=None, qf=1)

Returns a whoosh.matching.Matcher for the postings of the given term. Unlike the whoosh.reading.IndexReader.postings() method, this method automatically sets the scoring functions on the matcher from the searcher’s weighting object.

reader()

Returns the underlying IndexReader.

refresh()

Returns a fresh searcher for the latest version of the index:

my_searcher = my_searcher.refresh()

If the index has not changed since this searcher was created, this searcher is simply returned.

This method may CLOSE underlying resources that are no longer needed by the refreshed searcher, so you CANNOT continue to use the original searcher after calling refresh() on it.

search(q, **kwargs)

Runs a whoosh.query.Query object on this searcher and returns a Results object. See How to search for more information.

This method takes many keyword arguments (documented below).

See Sorting and faceting for information on using sortedby and/or groupedby. See Collapsing results for more information on using collapse, collapse_limit, and collapse_order.

Parameters:
  • query – a whoosh.query.Query object to use to match documents.
  • limit – the maximum number of documents to score. If you’re only interested in the top N documents, you can set limit=N to limit the scoring for a faster search. Default is 10.
  • scored – whether to score the results. Overriden by sortedby. If both scored=False and sortedby=None, the results will be in arbitrary order, but will usually be computed faster than scored or sorted results.
  • sortedby – see Sorting and faceting.
  • reverse – Reverses the direction of the sort. Default is False.
  • groupedby – see Sorting and faceting.
  • optimize – use optimizations to get faster results when possible. Default is True.
  • filter – a query, Results object, or set of docnums. The results will only contain documents that are also in the filter object.
  • mask – a query, Results object, or set of docnums. The results will not contain any documents that are in the mask object.
  • terms – if True, record which terms were found in each matching document. See How to search for more information. Default is False.
  • maptype – by default, the results of faceting with groupedby is a dictionary mapping group names to ordered lists of document numbers in the group. You can pass a whoosh.sorting.FacetMap subclass to this keyword argument to specify a different (usually faster) method for grouping. For example, maptype=sorting.Count would store only the count of documents in each group, instead of the full list of document IDs.
  • collapse – a facet to use to collapse the results. See Collapsing results for more information.
  • collapse_limit – the maximum number of documents to allow with the same collapse key. See Collapsing results for more information.
  • collapse_order – an optional ordering facet to control which documents are kept when collapsing. The default (collapse_order=None) uses the results order (e.g. the highest scoring documents in a scored search).
Return type:

Results

search_page(query, pagenum, pagelen=10, **kwargs)

This method is Like the Searcher.search() method, but returns a ResultsPage object. This is a convenience function for getting a certain “page” of the results for the given query, which is often useful in web search interfaces.

For example:

querystring = request.get("q")
query = queryparser.parse("content", querystring)

pagenum = int(request.get("page", 1))
pagelen = int(request.get("perpage", 10))

results = searcher.search_page(query, pagenum, pagelen=pagelen)
print("Page %d of %d" % (results.pagenum, results.pagecount))
print("Showing results %d-%d of %d"
      % (results.offset + 1, results.offset + results.pagelen + 1,
         len(results)))
for hit in results:
    print("%d: %s" % (hit.rank + 1, hit["title"]))

(Note that results.pagelen might be less than the pagelen argument if there aren’t enough results to fill a page.)

Any additional keyword arguments you supply are passed through to Searcher.search(). For example, you can get paged results of a sorted search:

results = searcher.search_page(q, 2, sortedby="date", reverse=True)

Currently, searching for page 100 with pagelen of 10 takes the same amount of time as using Searcher.search() to find the first 1000 results. That is, this method does not have any special optimizations or efficiencies for getting a page from the middle of the full results list. (A future enhancement may allow using previous page results to improve the efficiency of finding the next page.)

This method will raise a ValueError if you ask for a page number higher than the number of pages in the resulting query.

Parameters:
  • query – the whoosh.query.Query object to match.
  • pagenum – the page number to retrieve, starting at 1 for the first page.
  • pagelen – the number of results per page.
Returns:

ResultsPage

search_with_collector(q, collector, context=None)

Low-level method: runs a whoosh.query.Query object on this searcher using the given whoosh.collectors.Collector object to collect the results:

myquery = query.Term("content", "cabbage")

uc = collectors.UnlimitedCollector()
tc = TermsCollector(uc)

mysearcher.search_with_collector(myquery, tc)
print(tc.docterms)
print(tc.results())

Note that this method does not return a Results object. You need to access the collector to get a results object or other information the collector might hold after the search.

Parameters:
suggest(fieldname, text, limit=5, maxdist=2, prefix=0)

Returns a sorted list of suggested corrections for the given mis-typed word text based on the contents of the given field:

>>> searcher.suggest("content", "specail")
["special"]

This is a convenience method. If you are planning to get suggestions for multiple words in the same field, it is more efficient to get a Corrector object and use it directly:

corrector = searcher.corrector("fieldname")
for word in words:
    print(corrector.suggest(word))
Parameters:
  • limit – only return up to this many suggestions. If there are not enough terms in the field within maxdist of the given word, the returned list will be shorter than this number.
  • maxdist – the largest edit distance from the given word to look at. Numbers higher than 2 are not very effective or efficient.
  • prefix – require suggestions to share a prefix of this length with the given word. This is often justifiable since most misspellings do not involve the first letter of the word. Using a prefix dramatically decreases the time it takes to generate the list of words.
up_to_date()

Returns True if this Searcher represents the latest version of the index, for backends that support versioning.

Results classes

class whoosh.searching.Results(searcher, q, top_n, docset=None, facetmaps=None, runtime=0, highlighter=None)

This object is returned by a Searcher. This object represents the results of a search query. You can mostly use it as if it was a list of dictionaries, where each dictionary is the stored fields of the document at that position in the results.

Note that a Results object keeps a reference to the Searcher that created it, so keeping a reference to a Results object keeps the Searcher alive and so keeps all files used by it open.

Parameters:
  • searcher – the Searcher object that produced these results.
  • query – the original query that created these results.
  • top_n – a list of (score, docnum) tuples representing the top N search results.
copy()

Returns a deep copy of this results object.

docnum(n)

Returns the document number of the result at position n in the list of ranked documents.

docs()

Returns a set-like object containing the document numbers that matched the query.

estimated_length()

The estimated maximum number of matching documents, or the exact number of matching documents if it’s known.

estimated_min_length()

The estimated minimum number of matching documents, or the exact number of matching documents if it’s known.

extend(results)

Appends hits from ‘results’ (that are not already in this results object) to the end of these results.

Parameters:results – another results object.
facet_names()

Returns the available facet names, for use with the groups() method.

fields(n)

Returns the stored fields for the document at the n th position in the results. Use Results.docnum() if you want the raw document number instead of the stored fields.

filter(results)

Removes any hits that are not also in the other results object.

groups(name=None)

If you generated facet groupings for the results using the groupedby keyword argument to the search() method, you can use this method to retrieve the groups. You can use the facet_names() method to get the list of available facet names.

>>> results = searcher.search(my_query, groupedby=["tag", "price"])
>>> results.facet_names()
["tag", "price"]
>>> results.groups("tag")
{"new": [12, 1, 4], "apple": [3, 10, 5], "search": [11]}

If you only used one facet, you can call the method without a facet name to get the groups for the facet.

>>> results = searcher.search(my_query, groupedby="tag")
>>> results.groups()
{"new": [12, 1, 4], "apple": [3, 10, 5, 0], "search": [11]}

By default, this returns a dictionary mapping category names to a list of document numbers, in the same relative order as they appear in the results.

>>> results = mysearcher.search(myquery, groupedby="tag")
>>> docnums = results.groups()
>>> docnums['new']
[12, 1, 4]

You can then use Searcher.stored_fields() to get the stored fields associated with a document ID.

If you specified a different maptype for the facet when you searched, the values in the dictionary depend on the whoosh.sorting.FacetMap.

>>> myfacet = sorting.FieldFacet("tag", maptype=sorting.Count)
>>> results = mysearcher.search(myquery, groupedby=myfacet)
>>> counts = results.groups()
{"new": 3, "apple": 4, "search": 1}
has_exact_length()

Returns True if this results object already knows the exact number of matching documents.

has_matched_terms()

Returns True if the search recorded which terms matched in which documents.

>>> r = searcher.search(myquery)
>>> r.has_matched_terms()
False
>>>
is_empty()

Returns True if not documents matched the query.

items()

Returns an iterator of (docnum, score) pairs for the scored documents in the results.

key_terms(fieldname, docs=10, numterms=5, model=<class 'whoosh.classify.Bo1Model'>, normalize=True)

Returns the ‘numterms’ most important terms from the top ‘docs’ documents in these results. “Most important” is generally defined as terms that occur frequently in the top hits but relatively infrequently in the collection as a whole.

Parameters:
  • fieldname – Look at the terms in this field. This field must store vectors.
  • docs – Look at this many of the top documents of the results.
  • numterms – Return this number of important terms.
  • model – The classify.ExpansionModel to use. See the classify module.
Returns:

list of unicode strings.

matched_terms()

Returns the set of ("fieldname", "text") tuples representing terms from the query that matched one or more of the TOP N documents (this does not report terms for documents that match the query but did not score high enough to make the top N results). You can compare this set to the terms from the original query to find terms which didn’t occur in any matching documents.

This is only valid if you used terms=True in the search call to record matching terms. Otherwise it will raise an exception.

>>> q = myparser.parse("alfa OR bravo OR charlie")
>>> results = searcher.search(q, terms=True)
>>> results.terms()
set([("content", "alfa"), ("content", "charlie")])
>>> q.all_terms() - results.terms()
set([("content", "bravo")])
score(n)

Returns the score for the document at the Nth position in the list of ranked documents. If the search was not scored, this may return None.

scored_length()

Returns the number of scored documents in the results, equal to or less than the limit keyword argument to the search.

>>> r = mysearcher.search(myquery, limit=20)
>>> len(r)
1246
>>> r.scored_length()
20

This may be fewer than the total number of documents that match the query, which is what len(Results) returns.

upgrade(results, reverse=False)

Re-sorts the results so any hits that are also in ‘results’ appear before hits not in ‘results’, otherwise keeping their current relative positions. This does not add the documents in the other results object to this one.

Parameters:
  • results – another results object.
  • reverse – if True, lower the position of hits in the other results object instead of raising them.
upgrade_and_extend(results)

Combines the effects of extend() and upgrade(): hits that are also in ‘results’ are raised. Then any hits from the other results object that are not in this results object are appended to the end.

Parameters:results – another results object.
class whoosh.searching.Hit(results, docnum, pos=None, score=None)

Represents a single search result (“hit”) in a Results object.

This object acts like a dictionary of the matching document’s stored fields. If for some reason you need an actual dict object, use Hit.fields() to get one.

>>> r = searcher.search(query.Term("content", "render"))
>>> r[0]
< Hit {title = u"Rendering the scene"} >
>>> r[0].rank
0
>>> r[0].docnum == 4592
True
>>> r[0].score
2.52045682
>>> r[0]["title"]
"Rendering the scene"
>>> r[0].keys()
["title"]
Parameters:
  • results – the Results object this hit belongs to.
  • pos – the position in the results list of this hit, for example pos = 0 means this is the first (highest scoring) hit.
  • docnum – the document number of this hit.
  • score – the score of this hit.
fields()

Returns a dictionary of the stored fields of the document this object represents.

highlights(fieldname, text=None, top=3, minscore=1)

Returns highlighted snippets from the given field:

r = searcher.search(myquery)
for hit in r:
    print(hit["title"])
    print(hit.highlights("content"))

See How to create highlighted search result excerpts.

To change the fragmeter, formatter, order, or scorer used in highlighting, you can set attributes on the results object:

from whoosh import highlight

results = searcher.search(myquery, terms=True)
results.fragmenter = highlight.SentenceFragmenter()

...or use a custom whoosh.highlight.Highlighter object:

hl = highlight.Highlighter(fragmenter=sf)
results.highlighter = hl
Parameters:
  • fieldname – the name of the field you want to highlight.
  • text – by default, the method will attempt to load the contents of the field from the stored fields for the document. If the field you want to highlight isn’t stored in the index, but you have access to the text another way (for example, loading from a file or a database), you can supply it using the text parameter.
  • top – the maximum number of fragments to return.
  • minscore – the minimum score for fragments to appear in the highlights.
matched_terms()

Returns the set of ("fieldname", "text") tuples representing terms from the query that matched in this document. You can compare this set to the terms from the original query to find terms which didn’t occur in this document.

This is only valid if you used terms=True in the search call to record matching terms. Otherwise it will raise an exception.

>>> q = myparser.parse("alfa OR bravo OR charlie")
>>> results = searcher.search(q, terms=True)
>>> for hit in results:
...   print(hit["title"])
...   print("Contains:", hit.matched_terms())
...   print("Doesn't contain:", q.all_terms() - hit.matched_terms())
more_like_this(fieldname, text=None, top=10, numterms=5, model=<class 'whoosh.classify.Bo1Model'>, normalize=True, filter=None)

Returns a new Results object containing documents similar to this hit, based on “key terms” in the given field:

r = searcher.search(myquery)
for hit in r:
    print(hit["title"])
    print("Top 3 similar documents:")
    for subhit in hit.more_like_this("content", top=3):
      print("  ", subhit["title"])
Parameters:
  • fieldname – the name of the field to use to test similarity.
  • text – by default, the method will attempt to load the contents of the field from the stored fields for the document, or from a term vector. If the field isn’t stored or vectored in the index, but you have access to the text another way (for example, loading from a file or a database), you can supply it using the text parameter.
  • top – the number of results to return.
  • numterms – the number of “key terms” to extract from the hit and search for. Using more terms is slower but gives potentially more and more accurate results.
  • model – (expert) a whoosh.classify.ExpansionModel to use to compute “key terms”.
  • normalize – whether to normalize term weights.
class whoosh.searching.ResultsPage(results, pagenum, pagelen=10)

Represents a single page out of a longer list of results, as returned by whoosh.searching.Searcher.search_page(). Supports a subset of the interface of the Results object, namely getting stored fields with __getitem__ (square brackets), iterating, and the score() and docnum() methods.

The offset attribute contains the results number this page starts at (numbered from 0). For example, if the page length is 10, the offset attribute on the second page will be 10.

The pagecount attribute contains the number of pages available.

The pagenum attribute contains the page number. This may be less than the page you requested if the results had too few pages. For example, if you do:

ResultsPage(results, 5)

but the results object only contains 3 pages worth of hits, pagenum will be 3.

The pagelen attribute contains the number of results on this page (which may be less than the page length you requested if this is the last page of the results).

The total attribute contains the total number of hits in the results.

>>> mysearcher = myindex.searcher()
>>> pagenum = 2
>>> page = mysearcher.find_page(pagenum, myquery)
>>> print("Page %s of %s, results %s to %s of %s" %
...       (pagenum, page.pagecount, page.offset+1,
...        page.offset+page.pagelen, page.total))
>>> for i, fields in enumerate(page):
...   print("%s. %r" % (page.offset + i + 1, fields))
>>> mysearcher.close()

To set highlighter attributes (for example formatter), access the underlying Results object:

page.results.formatter = highlight.UppercaseFormatter()
Parameters:
  • results – a Results object.
  • pagenum – which page of the results to use, numbered from 1.
  • pagelen – the number of hits per page.
docnum(n)

Returns the document number of the hit at the nth position on this page.

is_last_page()

Returns True if this object represents the last page of results.

score(n)

Returns the score of the hit at the nth position on this page.

Exceptions

exception whoosh.searching.NoTermsException

Exception raised you try to access matched terms on a Results object was created without them. To record which terms matched in which document, you need to call the Searcher.search() method with terms=True.

exception whoosh.searching.TimeLimit

Raised by TimeLimitedCollector if the time limit is reached before the search finishes. If you have a reference to the collector, you can get partial results by calling TimeLimitedCollector.results().