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.
add_facet_field(name, facet, save=False)

This is an experimental feature which may change in future versions.

Adds a field cache for a computed field defined by a whoosh.sorting.FacetType object, for example a QueryFacet or RangeFacet.

This creates a field cache from the facet, so once you define the “facet field”, sorting/grouping by it will be faster than using the original facet object.

For example, sorting using a QueryFacet recomputes the queries at sort time, which may be slow:

qfacet = sorting.QueryFacet({"a-z": TermRange(...
results = searcher.search(myquery, sortedby=qfacet)

You can cache the results of the query facet in a field cache:

searcher.define_facets("nameranges", qfacet, save=True)

..then use the pseudo-field for sorting:

results = searcher.search(myquery, sortedby="nameranges")

See Sorting and faceting.

Parameters:
  • name – a name for the pseudo-field to cache the query results in.
  • qs – a FacetType object.
  • save – if True, saves the field cache to disk so it is persistent across searchers. The default is False, which only creates the field cache in memory.
correct_query(q, qstring, correctors=None, allfields=False, terms=None, prefix=0, maxdist=2)

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.
  • ONLY CORRECTS FIELDS THAT HAVE THE spelling ATTRIBUTE in the schema (or for which you pass a custom corrector). To automatically check all fields, use allfields=True. Spell checking fields without spelling is slower.

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"'

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.
  • allfields – if True, automatically spell check all fields, not just fields with the spelling attribute.
  • 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.
  • 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.
  • 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.
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)

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, 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, limit=10, sortedby=None, reverse=False, groupedby=None, optimize=True, filter=None, mask=None, terms=False, maptype=None)

Runs the query represented by the query object and returns a Results object.

See Sorting and faceting for information on using sortedby and/or groupedby.

Parameters:
  • query – a whoosh.query.Query object.
  • 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.
  • sortedby – see Sorting and faceting.
  • reverse – Reverses the direction of the sort.
  • groupedby – see Sorting and faceting.
  • optimize – use optimizations to get faster results when possible.
  • 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 documents that are also in the mask object.
  • terms – if True, record which terms were found in each matching document. You can use Results.contains_term() or Hit.contains_term() to check whether a hit contains a particular term.
  • 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.
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

sorter(*args, **kwargs)

This method is deprecated. Instead of using a Sorter, configure a whoosh.sorting.FieldFacet or whoosh.sorting.MultiFacet and pass it to the Searcher.search() method’s sortedby keyword argument.

See Sorting and faceting.

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.

class whoosh.searching.Collector(limit=10, usequality=True, groupedby=None, timelimit=None, greedy=False, terms=False, replace=10, maptype=None)

A Collector finds the matching documents, scores them, collects them into a list, and produces a Results object from them.

Normally you do not need to instantiate an instance of the base Collector class, the Searcher.search() method does that for you.

If you create a custom Collector instance or subclass you can use its search() method instead of Searcher.search():

mycollector = MyCollector()
results = mycollector.search(mysearcher, myquery)

Do not re-use or share Collector instances between searches. You should create a new Collector instance for each search.

To limit the amount of time a search can take, pass the number of seconds to the timelimit keyword argument:

# Limit the search to 4.5 seconds
col = Collector(timelimit=4.5, greedy=False)
# If this call takes more than 4.5 seconds, it will raise a
# whoosh.searching.TimeLimit exception
try:
    r = searcher.search(myquery, collector=col)
except TimeLimit, tl:
    # You can still retrieve partial results from the collector
    r = col.results()

If the greedy keyword is True, the collector will finish adding the most recent hit before raising the TimeLimit exception.

Parameters:
  • limit – the maximum number of hits to collect. If this is None, collect all hits.
  • usequality – whether to use block quality optimizations when available. This is mostly useful for debugging purposes.
  • groupedby – see Sorting and faceting for information.
  • timelimit – the maximum amount of time (in possibly fractional seconds) to allow for searching. If the search takes longer than this, it will raise a TimeLimit exception.
  • greedy – if True, the collector will finish adding the most recent hit before raising the TimeLimit exception.
  • terms – if True, record which terms matched in each document.
  • maptype – a whoosh.sorting.FacetMap type to use for all facets that don’t specify their own.
pull_matches(q, offset, scorefn)

Low-level method yields (docid, score) pairs from the given matcher. Called by Collector.add_matches().

results(scores=True, reverse=False)

Returns the current results from the collector. This is useful for getting the results out of a collector that was stopped by a time limit exception.

search(searcher, q, allow=None, restrict=None)

Top-level method call which uses the given Searcher and whoosh.query.Query objects to return a Results object.

>>> # This is the equivalent of calling searcher.search(q)
>>> col = Collector()
>>> results = col.search(searcher, q)

This method takes care of calling Collector.add_searcher() for each sub-searcher in a collective searcher. You should only call this method on a top-level searcher.

should_add_all()

Returns True if this collector needs to add all found documents (for example, if limit=None), or False if this collector should only add the top N found documents.

use_block_quality(searcher, matcher=None)

Returns True if this collector can use block quality optimizations (usequality is True, the matcher supports block quality, the weighting does not use the final() method, etc.).

Results classes

class whoosh.searching.Results(searcher, q, top_n, docset, facetmaps=None, runtime=-1, filter=None, mask=None, termlists=None, 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 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 ‘numdocs’ 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.
  • terms – 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 increase(): 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.
contains_term(fieldname, text)

Returns True if the given query term exists in this document. This only works for terms that were in the original query.

fields()

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

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

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.
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()
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.

Table Of Contents

Previous topic

scoring module

Next topic

sorting module

This Page