This module contains classes and functions related to searching the index.
Wraps an IndexReader object and provides methods for searching the index.
Parameters: |
|
---|
Shortcut returns a SearchContext set for unscored (boolean) searching.
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 = TimeLimitedCollector(c, 10.5)
# Search using the custom collector
results = mysearcher.search_with_collector(myquery, c)
Generates a SearchContext for this searcher.
Returns a corrected version of the given user query using a default whoosh.spelling.ReaderCorrector.
The default:
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: |
|
---|---|
Return type: |
Returns the number of UNDELETED documents in the index.
Returns the total number of documents, DELETED OR UNDELETED, in the index.
Returns an iterator of document numbers for documents matching the given whoosh.query.Query object.
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")
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 |
---|
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"))
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'])
Returns the parent of this searcher (if has_parent() is True), or else self.
Calculates the Inverse Document Frequency of the current term (calls idf() on the searcher’s Weighting object).
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: |
|
---|---|
Returns: | a list of (“term”, score) tuples. |
Return the ‘numterms’ most important terms from the given text.
Parameters: |
|
---|
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: |
|
---|
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.
Returns the underlying IndexReader.
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.
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: |
|
---|---|
Return type: |
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: |
|
---|---|
Returns: |
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: |
|
---|
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: |
|
---|
Returns True if this Searcher represents the latest version of the index, for backends that support versioning.
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: |
|
---|
Returns a deep copy of this results object.
Returns the document number of the result at position n in the list of ranked documents.
Returns a set-like object containing the document numbers that matched the query.
The estimated maximum number of matching documents, or the exact number of matching documents if it’s known.
The estimated minimum number of matching documents, or the exact number of matching documents if it’s known.
Appends hits from ‘results’ (that are not already in this results object) to the end of these results.
Parameters: | results – another results object. |
---|
Returns the available facet names, for use with the groups() method.
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.
Removes any hits that are not also in the other results object.
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}
Returns True if this results object already knows the exact number of matching documents.
Returns True if the search recorded which terms matched in which documents.
>>> r = searcher.search(myquery)
>>> r.has_matched_terms()
False
>>>
Returns True if not documents matched the query.
Returns an iterator of (docnum, score) pairs for the scored documents in the results.
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: |
|
---|---|
Returns: | list of unicode strings. |
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")])
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.
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.
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: |
|
---|
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. |
---|
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: |
|
---|
Returns a dictionary of the stored fields of the document this object represents.
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: |
|
---|
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())
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: |
|
---|
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: |
|
---|
Returns the document number of the hit at the nth position on this page.
Returns True if this object represents the last page of results.
Returns the score of the hit at the nth position on this page.
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.
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().