searching.py 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653
  1. # Copyright 2007 Matt Chaput. All rights reserved.
  2. #
  3. # Redistribution and use in source and binary forms, with or without
  4. # modification, are permitted provided that the following conditions are met:
  5. #
  6. # 1. Redistributions of source code must retain the above copyright notice,
  7. # this list of conditions and the following disclaimer.
  8. #
  9. # 2. Redistributions in binary form must reproduce the above copyright
  10. # notice, this list of conditions and the following disclaimer in the
  11. # documentation and/or other materials provided with the distribution.
  12. #
  13. # THIS SOFTWARE IS PROVIDED BY MATT CHAPUT ``AS IS'' AND ANY EXPRESS OR
  14. # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  15. # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  16. # EVENT SHALL MATT CHAPUT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  17. # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  18. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  19. # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  20. # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  21. # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  22. # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  23. #
  24. # The views and conclusions contained in the software and documentation are
  25. # those of the authors and should not be interpreted as representing official
  26. # policies, either expressed or implied, of Matt Chaput.
  27. """This module contains classes and functions related to searching the index.
  28. """
  29. from __future__ import division
  30. import copy
  31. import weakref
  32. from math import ceil
  33. from whoosh import classify, highlight, query, scoring
  34. from whoosh.compat import iteritems, itervalues, iterkeys, xrange
  35. from whoosh.idsets import DocIdSet, BitSet
  36. from whoosh.reading import TermNotFound
  37. from whoosh.util.cache import lru_cache
  38. class NoTermsException(Exception):
  39. """Exception raised you try to access matched terms on a :class:`Results`
  40. object was created without them. To record which terms matched in which
  41. document, you need to call the :meth:`Searcher.search` method with
  42. ``terms=True``.
  43. """
  44. message = "Results were created without recording terms"
  45. class TimeLimit(Exception):
  46. """Raised by :class:`TimeLimitedCollector` if the time limit is reached
  47. before the search finishes. If you have a reference to the collector, you
  48. can get partial results by calling :meth:`TimeLimitedCollector.results`.
  49. """
  50. pass
  51. # Context class
  52. class SearchContext(object):
  53. """A container for information about the current search that may be used
  54. by the collector or the query objects to change how they operate.
  55. """
  56. def __init__(self, needs_current=False, weighting=None, top_query=None,
  57. limit=0):
  58. """
  59. :param needs_current: if True, the search requires that the matcher
  60. tree be "valid" and able to access information about the current
  61. match. For queries during matcher instantiation, this means they
  62. should not instantiate a matcher that doesn't allow access to the
  63. current match's value, weight, and so on. For collectors, this
  64. means they should advanced the matcher doc-by-doc rather than using
  65. shortcut methods such as all_ids().
  66. :param weighting: the Weighting object to use for scoring documents.
  67. :param top_query: a reference to the top-level query object.
  68. :param limit: the number of results requested by the user.
  69. """
  70. self.needs_current = needs_current
  71. self.weighting = weighting
  72. self.top_query = top_query
  73. self.limit = limit
  74. def __repr__(self):
  75. return "%s(%r)" % (self.__class__.__name__, self.__dict__)
  76. def set(self, **kwargs):
  77. ctx = copy.copy(self)
  78. ctx.__dict__.update(kwargs)
  79. return ctx
  80. # Searcher class
  81. class Searcher(object):
  82. """Wraps an :class:`~whoosh.reading.IndexReader` object and provides
  83. methods for searching the index.
  84. """
  85. def __init__(self, reader, weighting=scoring.BM25F, closereader=True,
  86. fromindex=None, parent=None):
  87. """
  88. :param reader: An :class:`~whoosh.reading.IndexReader` object for
  89. the index to search.
  90. :param weighting: A :class:`whoosh.scoring.Weighting` object to use to
  91. score found documents.
  92. :param closereader: Whether the underlying reader will be closed when
  93. the searcher is closed.
  94. :param fromindex: An optional reference to the index of the underlying
  95. reader. This is required for :meth:`Searcher.up_to_date` and
  96. :meth:`Searcher.refresh` to work.
  97. """
  98. self.ixreader = reader
  99. self.is_closed = False
  100. self._closereader = closereader
  101. self._ix = fromindex
  102. self._doccount = self.ixreader.doc_count_all()
  103. # Cache for PostingCategorizer objects (supports fields without columns)
  104. self._field_caches = {}
  105. if parent:
  106. self.parent = weakref.ref(parent)
  107. self.schema = parent.schema
  108. self._idf_cache = parent._idf_cache
  109. self._filter_cache = parent._filter_cache
  110. else:
  111. self.parent = None
  112. self.schema = self.ixreader.schema
  113. self._idf_cache = {}
  114. self._filter_cache = {}
  115. if type(weighting) is type:
  116. self.weighting = weighting()
  117. else:
  118. self.weighting = weighting
  119. self.leafreaders = None
  120. self.subsearchers = None
  121. if not self.ixreader.is_atomic():
  122. self.leafreaders = self.ixreader.leaf_readers()
  123. self.subsearchers = [(self._subsearcher(r), offset) for r, offset
  124. in self.leafreaders]
  125. # Copy attributes/methods from wrapped reader
  126. for name in ("stored_fields", "all_stored_fields", "has_vector",
  127. "vector", "vector_as", "lexicon", "field_terms",
  128. "frequency", "doc_frequency", "term_info",
  129. "doc_field_length", "corrector", "iter_docs"):
  130. setattr(self, name, getattr(self.ixreader, name))
  131. def __enter__(self):
  132. return self
  133. def __exit__(self, *exc_info):
  134. self.close()
  135. def _subsearcher(self, reader):
  136. return self.__class__(reader, fromindex=self._ix,
  137. weighting=self.weighting, parent=self)
  138. def _offset_for_subsearcher(self, subsearcher):
  139. for ss, offset in self.subsearchers:
  140. if ss is subsearcher:
  141. return offset
  142. def leaf_searchers(self):
  143. if self.is_atomic():
  144. return [(self, 0)]
  145. else:
  146. return self.subsearchers
  147. def is_atomic(self):
  148. return self.reader().is_atomic()
  149. def has_parent(self):
  150. return self.parent is not None
  151. def get_parent(self):
  152. """Returns the parent of this searcher (if has_parent() is True), or
  153. else self.
  154. """
  155. if self.has_parent():
  156. # Call the weak reference to get the parent searcher
  157. return self.parent()
  158. else:
  159. return self
  160. def doc_count(self):
  161. """Returns the number of UNDELETED documents in the index.
  162. """
  163. return self.ixreader.doc_count()
  164. def doc_count_all(self):
  165. """Returns the total number of documents, DELETED OR UNDELETED, in
  166. the index.
  167. """
  168. return self._doccount
  169. def field_length(self, fieldname):
  170. if self.has_parent():
  171. return self.get_parent().field_length(fieldname)
  172. else:
  173. return self.reader().field_length(fieldname)
  174. def max_field_length(self, fieldname):
  175. if self.has_parent():
  176. return self.get_parent().max_field_length(fieldname)
  177. else:
  178. return self.reader().max_field_length(fieldname)
  179. def up_to_date(self):
  180. """Returns True if this Searcher represents the latest version of the
  181. index, for backends that support versioning.
  182. """
  183. if not self._ix:
  184. raise Exception("No reference to index")
  185. return self._ix.latest_generation() == self.ixreader.generation()
  186. def refresh(self):
  187. """Returns a fresh searcher for the latest version of the index::
  188. my_searcher = my_searcher.refresh()
  189. If the index has not changed since this searcher was created, this
  190. searcher is simply returned.
  191. This method may CLOSE underlying resources that are no longer needed
  192. by the refreshed searcher, so you CANNOT continue to use the original
  193. searcher after calling ``refresh()`` on it.
  194. """
  195. if not self._ix:
  196. raise Exception("No reference to index")
  197. if self._ix.latest_generation() == self.reader().generation():
  198. return self
  199. # Get a new reader, re-using resources from the current reader if
  200. # possible
  201. self.is_closed = True
  202. newreader = self._ix.reader(reuse=self.ixreader)
  203. return self.__class__(newreader, fromindex=self._ix,
  204. weighting=self.weighting)
  205. def close(self):
  206. if self._closereader:
  207. self.ixreader.close()
  208. self.is_closed = True
  209. def avg_field_length(self, fieldname, default=None):
  210. if not self.schema[fieldname].scorable:
  211. return default
  212. return self.field_length(fieldname) / (self._doccount or 1)
  213. def reader(self):
  214. """Returns the underlying :class:`~whoosh.reading.IndexReader`.
  215. """
  216. return self.ixreader
  217. def context(self, **kwargs):
  218. """Generates a :class:`SearchContext` for this searcher.
  219. """
  220. if "weighting" not in kwargs:
  221. kwargs["weighting"] = self.weighting
  222. return SearchContext(**kwargs)
  223. def boolean_context(self):
  224. """Shortcut returns a SearchContext set for unscored (boolean)
  225. searching.
  226. """
  227. return self.context(needs_current=False, weighting=None)
  228. def postings(self, fieldname, text, weighting=None, qf=1):
  229. """Returns a :class:`whoosh.matching.Matcher` for the postings of the
  230. given term. Unlike the :func:`whoosh.reading.IndexReader.postings`
  231. method, this method automatically sets the scoring functions on the
  232. matcher from the searcher's weighting object.
  233. """
  234. weighting = weighting or self.weighting
  235. globalscorer = weighting.scorer(self, fieldname, text, qf=qf)
  236. if self.is_atomic():
  237. return self.ixreader.postings(fieldname, text, scorer=globalscorer)
  238. else:
  239. from whoosh.matching import MultiMatcher
  240. matchers = []
  241. docoffsets = []
  242. term = (fieldname, text)
  243. for subsearcher, offset in self.subsearchers:
  244. r = subsearcher.reader()
  245. if term in r:
  246. # Make a segment-specific scorer; the scorer should call
  247. # searcher.parent() to get global stats
  248. scorer = weighting.scorer(subsearcher, fieldname, text, qf=qf)
  249. m = r.postings(fieldname, text, scorer=scorer)
  250. matchers.append(m)
  251. docoffsets.append(offset)
  252. if not matchers:
  253. raise TermNotFound(fieldname, text)
  254. return MultiMatcher(matchers, docoffsets, globalscorer)
  255. def idf(self, fieldname, text):
  256. """Calculates the Inverse Document Frequency of the current term (calls
  257. idf() on the searcher's Weighting object).
  258. """
  259. # This method just calls the Weighting object's idf() method, but
  260. # caches the result. So Weighting objects should call *this* method
  261. # which will then call *their own* idf() methods.
  262. cache = self._idf_cache
  263. term = (fieldname, text)
  264. if term in cache:
  265. return cache[term]
  266. idf = self.weighting.idf(self, fieldname, text)
  267. cache[term] = idf
  268. return idf
  269. def document(self, **kw):
  270. """Convenience method returns the stored fields of a document
  271. matching the given keyword arguments, where the keyword keys are
  272. field names and the values are terms that must appear in the field.
  273. This method is equivalent to::
  274. searcher.stored_fields(searcher.document_number(<keyword args>))
  275. Where Searcher.documents() returns a generator, this function returns
  276. either a dictionary or None. Use it when you assume the given keyword
  277. arguments either match zero or one documents (i.e. at least one of the
  278. fields is a unique key).
  279. >>> stored_fields = searcher.document(path=u"/a/b")
  280. >>> if stored_fields:
  281. ... print(stored_fields['title'])
  282. ... else:
  283. ... print("There is no document with the path /a/b")
  284. """
  285. for p in self.documents(**kw):
  286. return p
  287. def documents(self, **kw):
  288. """Convenience method returns the stored fields of a document
  289. matching the given keyword arguments, where the keyword keys are field
  290. names and the values are terms that must appear in the field.
  291. Returns a generator of dictionaries containing the stored fields of any
  292. documents matching the keyword arguments. If you do not specify any
  293. arguments (``Searcher.documents()``), this method will yield **all**
  294. documents.
  295. >>> for stored_fields in searcher.documents(emailto=u"matt@whoosh.ca"):
  296. ... print("Email subject:", stored_fields['subject'])
  297. """
  298. ixreader = self.ixreader
  299. return (ixreader.stored_fields(docnum)
  300. for docnum in self.document_numbers(**kw))
  301. def _kw_to_text(self, kw):
  302. for k, v in iteritems(kw):
  303. field = self.schema[k]
  304. kw[k] = field.to_bytes(v)
  305. def _query_for_kw(self, kw):
  306. subqueries = []
  307. for key, value in iteritems(kw):
  308. subqueries.append(query.Term(key, value))
  309. if subqueries:
  310. q = query.And(subqueries).normalize()
  311. else:
  312. q = query.Every()
  313. return q
  314. def document_number(self, **kw):
  315. """Returns the document number of the document matching the given
  316. keyword arguments, where the keyword keys are field names and the
  317. values are terms that must appear in the field.
  318. >>> docnum = searcher.document_number(path=u"/a/b")
  319. Where Searcher.document_numbers() returns a generator, this function
  320. returns either an int or None. Use it when you assume the given keyword
  321. arguments either match zero or one documents (i.e. at least one of the
  322. fields is a unique key).
  323. :rtype: int
  324. """
  325. # In the common case where only one keyword was given, just use
  326. # first_id() instead of building a query.
  327. self._kw_to_text(kw)
  328. if len(kw) == 1:
  329. k, v = list(kw.items())[0]
  330. try:
  331. return self.reader().first_id(k, v)
  332. except TermNotFound:
  333. return None
  334. else:
  335. m = self._query_for_kw(kw).matcher(self, self.boolean_context())
  336. if m.is_active():
  337. return m.id()
  338. def document_numbers(self, **kw):
  339. """Returns a generator of the document numbers for documents matching
  340. the given keyword arguments, where the keyword keys are field names and
  341. the values are terms that must appear in the field. If you do not
  342. specify any arguments (``Searcher.document_numbers()``), this method
  343. will yield **all** document numbers.
  344. >>> docnums = list(searcher.document_numbers(emailto="matt@whoosh.ca"))
  345. """
  346. self._kw_to_text(kw)
  347. return self.docs_for_query(self._query_for_kw(kw))
  348. def _find_unique(self, uniques):
  349. # uniques is a list of ("unique_field_name", "field_value") tuples
  350. delset = set()
  351. for name, value in uniques:
  352. docnum = self.document_number(**{name: value})
  353. if docnum is not None:
  354. delset.add(docnum)
  355. return delset
  356. def _query_to_comb(self, fq):
  357. return BitSet(self.docs_for_query(fq), size=self.doc_count_all())
  358. def _filter_to_comb(self, obj):
  359. if obj is None:
  360. return None
  361. if isinstance(obj, (set, DocIdSet)):
  362. c = obj
  363. elif isinstance(obj, Results):
  364. c = obj.docs()
  365. elif isinstance(obj, ResultsPage):
  366. c = obj.results.docs()
  367. elif isinstance(obj, query.Query):
  368. c = self._query_to_comb(obj)
  369. else:
  370. raise Exception("Don't know what to do with filter object %r"
  371. % obj)
  372. return c
  373. def suggest(self, fieldname, text, limit=5, maxdist=2, prefix=0):
  374. """Returns a sorted list of suggested corrections for the given
  375. mis-typed word ``text`` based on the contents of the given field::
  376. >>> searcher.suggest("content", "specail")
  377. ["special"]
  378. This is a convenience method. If you are planning to get suggestions
  379. for multiple words in the same field, it is more efficient to get a
  380. :class:`~whoosh.spelling.Corrector` object and use it directly::
  381. corrector = searcher.corrector("fieldname")
  382. for word in words:
  383. print(corrector.suggest(word))
  384. :param limit: only return up to this many suggestions. If there are not
  385. enough terms in the field within ``maxdist`` of the given word, the
  386. returned list will be shorter than this number.
  387. :param maxdist: the largest edit distance from the given word to look
  388. at. Numbers higher than 2 are not very effective or efficient.
  389. :param prefix: require suggestions to share a prefix of this length
  390. with the given word. This is often justifiable since most
  391. misspellings do not involve the first letter of the word. Using a
  392. prefix dramatically decreases the time it takes to generate the
  393. list of words.
  394. """
  395. c = self.reader().corrector(fieldname)
  396. return c.suggest(text, limit=limit, maxdist=maxdist, prefix=prefix)
  397. def key_terms(self, docnums, fieldname, numterms=5,
  398. model=classify.Bo1Model, normalize=True):
  399. """Returns the 'numterms' most important terms from the documents
  400. listed (by number) in 'docnums'. You can get document numbers for the
  401. documents your interested in with the document_number() and
  402. document_numbers() methods.
  403. "Most important" is generally defined as terms that occur frequently in
  404. the top hits but relatively infrequently in the collection as a whole.
  405. >>> docnum = searcher.document_number(path=u"/a/b")
  406. >>> keywords_and_scores = searcher.key_terms([docnum], "content")
  407. This method returns a list of ("term", score) tuples. The score may be
  408. useful if you want to know the "strength" of the key terms, however to
  409. just get the terms themselves you can just do this:
  410. >>> kws = [kw for kw, score in searcher.key_terms([docnum], "content")]
  411. :param fieldname: Look at the terms in this field. This field must
  412. store vectors.
  413. :param docnums: A sequence of document numbers specifying which
  414. documents to extract key terms from.
  415. :param numterms: Return this number of important terms.
  416. :param model: The classify.ExpansionModel to use. See the classify
  417. module.
  418. :param normalize: normalize the scores.
  419. :returns: a list of ("term", score) tuples.
  420. """
  421. expander = classify.Expander(self.ixreader, fieldname, model=model)
  422. for docnum in docnums:
  423. expander.add_document(docnum)
  424. return expander.expanded_terms(numterms, normalize=normalize)
  425. def key_terms_from_text(self, fieldname, text, numterms=5,
  426. model=classify.Bo1Model, normalize=True):
  427. """Return the 'numterms' most important terms from the given text.
  428. :param numterms: Return this number of important terms.
  429. :param model: The classify.ExpansionModel to use. See the classify
  430. module.
  431. """
  432. expander = classify.Expander(self.ixreader, fieldname, model=model)
  433. expander.add_text(text)
  434. return expander.expanded_terms(numterms, normalize=normalize)
  435. def more_like(self, docnum, fieldname, text=None, top=10, numterms=5,
  436. model=classify.Bo1Model, normalize=False, filter=None):
  437. """Returns a :class:`Results` object containing documents similar to
  438. the given document, based on "key terms" in the given field::
  439. # Get the ID for the document you're interested in
  440. docnum = search.document_number(path=u"/a/b/c")
  441. r = searcher.more_like(docnum)
  442. print("Documents like", searcher.stored_fields(docnum)["title"])
  443. for hit in r:
  444. print(hit["title"])
  445. :param fieldname: the name of the field to use to test similarity.
  446. :param text: by default, the method will attempt to load the contents
  447. of the field from the stored fields for the document, or from a
  448. term vector. If the field isn't stored or vectored in the index,
  449. but you have access to the text another way (for example, loading
  450. from a file or a database), you can supply it using the ``text``
  451. parameter.
  452. :param top: the number of results to return.
  453. :param numterms: the number of "key terms" to extract from the hit and
  454. search for. Using more terms is slower but gives potentially more
  455. and more accurate results.
  456. :param model: (expert) a :class:`whoosh.classify.ExpansionModel` to use
  457. to compute "key terms".
  458. :param normalize: whether to normalize term weights.
  459. :param filter: a query, Results object, or set of docnums. The results
  460. will only contain documents that are also in the filter object.
  461. """
  462. if text:
  463. kts = self.key_terms_from_text(fieldname, text, numterms=numterms,
  464. model=model, normalize=normalize)
  465. else:
  466. kts = self.key_terms([docnum], fieldname, numterms=numterms,
  467. model=model, normalize=normalize)
  468. # Create an Or query from the key terms
  469. q = query.Or([query.Term(fieldname, word, boost=weight)
  470. for word, weight in kts])
  471. return self.search(q, limit=top, filter=filter, mask=set([docnum]))
  472. def search_page(self, query, pagenum, pagelen=10, **kwargs):
  473. """This method is Like the :meth:`Searcher.search` method, but returns
  474. a :class:`ResultsPage` object. This is a convenience function for
  475. getting a certain "page" of the results for the given query, which is
  476. often useful in web search interfaces.
  477. For example::
  478. querystring = request.get("q")
  479. query = queryparser.parse("content", querystring)
  480. pagenum = int(request.get("page", 1))
  481. pagelen = int(request.get("perpage", 10))
  482. results = searcher.search_page(query, pagenum, pagelen=pagelen)
  483. print("Page %d of %d" % (results.pagenum, results.pagecount))
  484. print("Showing results %d-%d of %d"
  485. % (results.offset + 1, results.offset + results.pagelen + 1,
  486. len(results)))
  487. for hit in results:
  488. print("%d: %s" % (hit.rank + 1, hit["title"]))
  489. (Note that results.pagelen might be less than the pagelen argument if
  490. there aren't enough results to fill a page.)
  491. Any additional keyword arguments you supply are passed through to
  492. :meth:`Searcher.search`. For example, you can get paged results of a
  493. sorted search::
  494. results = searcher.search_page(q, 2, sortedby="date", reverse=True)
  495. Currently, searching for page 100 with pagelen of 10 takes the same
  496. amount of time as using :meth:`Searcher.search` to find the first 1000
  497. results. That is, this method does not have any special optimizations
  498. or efficiencies for getting a page from the middle of the full results
  499. list. (A future enhancement may allow using previous page results to
  500. improve the efficiency of finding the next page.)
  501. This method will raise a ``ValueError`` if you ask for a page number
  502. higher than the number of pages in the resulting query.
  503. :param query: the :class:`whoosh.query.Query` object to match.
  504. :param pagenum: the page number to retrieve, starting at ``1`` for the
  505. first page.
  506. :param pagelen: the number of results per page.
  507. :returns: :class:`ResultsPage`
  508. """
  509. if pagenum < 1:
  510. raise ValueError("pagenum must be >= 1")
  511. results = self.search(query, limit=pagenum * pagelen, **kwargs)
  512. return ResultsPage(results, pagenum, pagelen)
  513. def find(self, defaultfield, querystring, **kwargs):
  514. from whoosh.qparser import QueryParser
  515. qp = QueryParser(defaultfield, schema=self.ixreader.schema)
  516. q = qp.parse(querystring)
  517. return self.search(q, **kwargs)
  518. def docs_for_query(self, q, for_deletion=False):
  519. """Returns an iterator of document numbers for documents matching the
  520. given :class:`whoosh.query.Query` object.
  521. """
  522. # If we're getting the document numbers so we can delete them, use the
  523. # deletion_docs method instead of docs; this lets special queries
  524. # (e.g. nested queries) override what gets deleted
  525. if for_deletion:
  526. method = q.deletion_docs
  527. else:
  528. method = q.docs
  529. if self.subsearchers:
  530. for s, offset in self.subsearchers:
  531. for docnum in method(s):
  532. yield docnum + offset
  533. else:
  534. for docnum in method(self):
  535. yield docnum
  536. def collector(self, limit=10, sortedby=None, reverse=False, groupedby=None,
  537. collapse=None, collapse_limit=1, collapse_order=None,
  538. optimize=True, filter=None, mask=None, terms=False,
  539. maptype=None, scored=True):
  540. """Low-level method: returns a configured
  541. :class:`whoosh.collectors.Collector` object based on the given
  542. arguments. You can use this object with
  543. :meth:`Searcher.search_with_collector` to search.
  544. See the documentation for the :meth:`Searcher.search` method for a
  545. description of the parameters.
  546. This method may be useful to get a basic collector object and then wrap
  547. it with another collector from ``whoosh.collectors`` or with a custom
  548. collector of your own::
  549. # Equivalent of
  550. # results = mysearcher.search(myquery, limit=10)
  551. # but with a time limt...
  552. # Create a TopCollector
  553. c = mysearcher.collector(limit=10)
  554. # Wrap it with a TimeLimitedCollector with a time limit of
  555. # 10.5 seconds
  556. from whoosh.collectors import TimeLimitedCollector
  557. c = TimeLimitCollector(c, 10.5)
  558. # Search using the custom collector
  559. results = mysearcher.search_with_collector(myquery, c)
  560. """
  561. from whoosh import collectors
  562. if limit is not None and limit < 1:
  563. raise ValueError("limit must be >= 1")
  564. if not scored and not sortedby:
  565. c = collectors.UnsortedCollector()
  566. elif sortedby:
  567. c = collectors.SortingCollector(sortedby, limit=limit,
  568. reverse=reverse)
  569. elif groupedby or reverse or not limit or limit >= self.doc_count():
  570. # A collector that gathers every matching document
  571. c = collectors.UnlimitedCollector(reverse=reverse)
  572. else:
  573. # A collector that uses block quality optimizations and a heap
  574. # queue to only collect the top N documents
  575. c = collectors.TopCollector(limit, usequality=optimize)
  576. if groupedby:
  577. c = collectors.FacetCollector(c, groupedby, maptype=maptype)
  578. if terms:
  579. c = collectors.TermsCollector(c)
  580. if collapse:
  581. c = collectors.CollapseCollector(c, collapse, limit=collapse_limit,
  582. order=collapse_order)
  583. # Filtering wraps last so it sees the docs first
  584. if filter or mask:
  585. c = collectors.FilterCollector(c, filter, mask)
  586. return c
  587. def search(self, q, **kwargs):
  588. """Runs a :class:`whoosh.query.Query` object on this searcher and
  589. returns a :class:`Results` object. See :doc:`/searching` for more
  590. information.
  591. This method takes many keyword arguments (documented below).
  592. See :doc:`/facets` for information on using ``sortedby`` and/or
  593. ``groupedby``. See :ref:`collapsing` for more information on using
  594. ``collapse``, ``collapse_limit``, and ``collapse_order``.
  595. :param query: a :class:`whoosh.query.Query` object to use to match
  596. documents.
  597. :param limit: the maximum number of documents to score. If you're only
  598. interested in the top N documents, you can set limit=N to limit the
  599. scoring for a faster search. Default is 10.
  600. :param scored: whether to score the results. Overriden by ``sortedby``.
  601. If both ``scored=False`` and ``sortedby=None``, the results will be
  602. in arbitrary order, but will usually be computed faster than
  603. scored or sorted results.
  604. :param sortedby: see :doc:`/facets`.
  605. :param reverse: Reverses the direction of the sort. Default is False.
  606. :param groupedby: see :doc:`/facets`.
  607. :param optimize: use optimizations to get faster results when possible.
  608. Default is True.
  609. :param filter: a query, Results object, or set of docnums. The results
  610. will only contain documents that are also in the filter object.
  611. :param mask: a query, Results object, or set of docnums. The results
  612. will not contain any documents that are in the mask object.
  613. :param terms: if True, record which terms were found in each matching
  614. document. See :doc:`/searching` for more information. Default is
  615. False.
  616. :param maptype: by default, the results of faceting with ``groupedby``
  617. is a dictionary mapping group names to ordered lists of document
  618. numbers in the group. You can pass a
  619. :class:`whoosh.sorting.FacetMap` subclass to this keyword argument
  620. to specify a different (usually faster) method for grouping. For
  621. example, ``maptype=sorting.Count`` would store only the count of
  622. documents in each group, instead of the full list of document IDs.
  623. :param collapse: a :doc:`facet </facets>` to use to collapse the
  624. results. See :ref:`collapsing` for more information.
  625. :param collapse_limit: the maximum number of documents to allow with
  626. the same collapse key. See :ref:`collapsing` for more information.
  627. :param collapse_order: an optional ordering :doc:`facet </facets>`
  628. to control which documents are kept when collapsing. The default
  629. (``collapse_order=None``) uses the results order (e.g. the highest
  630. scoring documents in a scored search).
  631. :rtype: :class:`Results`
  632. """
  633. # Call the collector() method to build a collector based on the
  634. # parameters passed to this method
  635. c = self.collector(**kwargs)
  636. # Call the lower-level method to run the collector
  637. self.search_with_collector(q, c)
  638. # Return the results object from the collector
  639. return c.results()
  640. def search_with_collector(self, q, collector, context=None):
  641. """Low-level method: runs a :class:`whoosh.query.Query` object on this
  642. searcher using the given :class:`whoosh.collectors.Collector` object
  643. to collect the results::
  644. myquery = query.Term("content", "cabbage")
  645. uc = collectors.UnlimitedCollector()
  646. tc = TermsCollector(uc)
  647. mysearcher.search_with_collector(myquery, tc)
  648. print(tc.docterms)
  649. print(tc.results())
  650. Note that this method does not return a :class:`Results` object. You
  651. need to access the collector to get a results object or other
  652. information the collector might hold after the search.
  653. :param q: a :class:`whoosh.query.Query` object to use to match
  654. documents.
  655. :param collector: a :class:`whoosh.collectors.Collector` object to feed
  656. the results into.
  657. """
  658. # Get the search context object from the searcher
  659. context = context or self.context()
  660. # Allow collector to set up based on the top-level information
  661. collector.prepare(self, q, context)
  662. collector.run()
  663. def correct_query(self, q, qstring, correctors=None, terms=None, maxdist=2,
  664. prefix=0, aliases=None):
  665. """
  666. Returns a corrected version of the given user query using a default
  667. :class:`whoosh.spelling.ReaderCorrector`.
  668. The default:
  669. * Corrects any words that don't appear in the index.
  670. * Takes suggestions from the words in the index. To make certain fields
  671. use custom correctors, use the ``correctors`` argument to pass a
  672. dictionary mapping field names to :class:`whoosh.spelling.Corrector`
  673. objects.
  674. Expert users who want more sophisticated correction behavior can create
  675. a custom :class:`whoosh.spelling.QueryCorrector` and use that instead
  676. of this method.
  677. Returns a :class:`whoosh.spelling.Correction` object with a ``query``
  678. attribute containing the corrected :class:`whoosh.query.Query` object
  679. and a ``string`` attributes containing the corrected query string.
  680. >>> from whoosh import qparser, highlight
  681. >>> qtext = 'mary "litle lamb"'
  682. >>> q = qparser.QueryParser("text", myindex.schema)
  683. >>> mysearcher = myindex.searcher()
  684. >>> correction = mysearcher().correct_query(q, qtext)
  685. >>> correction.query
  686. <query.And ...>
  687. >>> correction.string
  688. 'mary "little lamb"'
  689. >>> mysearcher.close()
  690. You can use the ``Correction`` object's ``format_string`` method to
  691. format the corrected query string using a
  692. :class:`whoosh.highlight.Formatter` object. For example, you can format
  693. the corrected string as HTML, emphasizing the changed words.
  694. >>> hf = highlight.HtmlFormatter(classname="change")
  695. >>> correction.format_string(hf)
  696. 'mary "<strong class="change term0">little</strong> lamb"'
  697. :param q: the :class:`whoosh.query.Query` object to correct.
  698. :param qstring: the original user query from which the query object was
  699. created. You can pass None instead of a string, in which the
  700. second item in the returned tuple will also be None.
  701. :param correctors: an optional dictionary mapping fieldnames to
  702. :class:`whoosh.spelling.Corrector` objects. By default, this method
  703. uses the contents of the index to spell check the terms in the
  704. query. You can use this argument to "override" some fields with a
  705. different correct, for example a
  706. :class:`whoosh.spelling.GraphCorrector`.
  707. :param terms: a sequence of ``("fieldname", "text")`` tuples to correct
  708. in the query. By default, this method corrects terms that don't
  709. appear in the index. You can use this argument to override that
  710. behavior and explicitly specify the terms that should be corrected.
  711. :param maxdist: the maximum number of "edits" (insertions, deletions,
  712. subsitutions, or transpositions of letters) allowed between the
  713. original word and any suggestion. Values higher than ``2`` may be
  714. slow.
  715. :param prefix: suggested replacement words must share this number of
  716. initial characters with the original word. Increasing this even to
  717. just ``1`` can dramatically speed up suggestions, and may be
  718. justifiable since spellling mistakes rarely involve the first
  719. letter of a word.
  720. :param aliases: an optional dictionary mapping field names in the query
  721. to different field names to use as the source of spelling
  722. suggestions. The mappings in ``correctors`` are applied after this.
  723. :rtype: :class:`whoosh.spelling.Correction`
  724. """
  725. reader = self.reader()
  726. # Dictionary of field name alias mappings
  727. if aliases is None:
  728. aliases = {}
  729. # Dictionary of custom per-field correctors
  730. if correctors is None:
  731. correctors = {}
  732. # Remap correctors dict according to aliases
  733. d = {}
  734. for fieldname, corr in iteritems(correctors):
  735. fieldname = aliases.get(fieldname, fieldname)
  736. d[fieldname] = corr
  737. correctors = d
  738. # Fill in default corrector objects for fields that don't have a custom
  739. # one in the "correctors" dictionary
  740. fieldnames = self.schema.names()
  741. for fieldname in fieldnames:
  742. fieldname = aliases.get(fieldname, fieldname)
  743. if fieldname not in correctors:
  744. correctors[fieldname] = self.reader().corrector(fieldname)
  745. # Get any missing terms in the query in the fields we're correcting
  746. if terms is None:
  747. terms = []
  748. for token in q.all_tokens():
  749. aname = aliases.get(token.fieldname, token.fieldname)
  750. text = token.text
  751. if aname in correctors and (aname, text) not in reader:
  752. # Note that we use the original, not aliases fieldname here
  753. # so if we correct the query we know what it was
  754. terms.append((token.fieldname, token.text))
  755. # Make q query corrector
  756. from whoosh import spelling
  757. sqc = spelling.SimpleQueryCorrector(correctors, terms, aliases)
  758. return sqc.correct_query(q, qstring)
  759. class Results(object):
  760. """This object is returned by a Searcher. This object represents the
  761. results of a search query. You can mostly use it as if it was a list of
  762. dictionaries, where each dictionary is the stored fields of the document at
  763. that position in the results.
  764. Note that a Results object keeps a reference to the Searcher that created
  765. it, so keeping a reference to a Results object keeps the Searcher alive and
  766. so keeps all files used by it open.
  767. """
  768. def __init__(self, searcher, q, top_n, docset=None, facetmaps=None,
  769. runtime=0, highlighter=None):
  770. """
  771. :param searcher: the :class:`Searcher` object that produced these
  772. results.
  773. :param query: the original query that created these results.
  774. :param top_n: a list of (score, docnum) tuples representing the top
  775. N search results.
  776. """
  777. self.searcher = searcher
  778. self.q = q
  779. self.top_n = top_n
  780. self.docset = docset
  781. self._facetmaps = facetmaps or {}
  782. self.runtime = runtime
  783. self.highlighter = highlighter or highlight.Highlighter()
  784. self.collector = None
  785. self._total = None
  786. self._char_cache = {}
  787. def __repr__(self):
  788. return "<Top %s Results for %r runtime=%s>" % (len(self.top_n),
  789. self.q,
  790. self.runtime)
  791. def __len__(self):
  792. """Returns the total number of documents that matched the query. Note
  793. this may be more than the number of scored documents, given the value
  794. of the ``limit`` keyword argument to :meth:`Searcher.search`.
  795. If this Results object was created by searching with a ``limit``
  796. keyword, then computing the exact length of the result set may be
  797. expensive for large indexes or large result sets. You may consider
  798. using :meth:`Results.has_exact_length`,
  799. :meth:`Results.estimated_length`, and
  800. :meth:`Results.estimated_min_length` to display an estimated size of
  801. the result set instead of an exact number.
  802. """
  803. if self._total is None:
  804. self._total = self.collector.count()
  805. return self._total
  806. def __getitem__(self, n):
  807. if isinstance(n, slice):
  808. start, stop, step = n.indices(len(self.top_n))
  809. return [Hit(self, self.top_n[i][1], i, self.top_n[i][0])
  810. for i in xrange(start, stop, step)]
  811. else:
  812. if n >= len(self.top_n):
  813. raise IndexError("results[%r]: Results only has %s hits"
  814. % (n, len(self.top_n)))
  815. return Hit(self, self.top_n[n][1], n, self.top_n[n][0])
  816. def __iter__(self):
  817. """Yields a :class:`Hit` object for each result in ranked order.
  818. """
  819. for i in xrange(len(self.top_n)):
  820. yield Hit(self, self.top_n[i][1], i, self.top_n[i][0])
  821. def __contains__(self, docnum):
  822. """Returns True if the given document number matched the query.
  823. """
  824. return docnum in self.docs()
  825. def __nonzero__(self):
  826. return not self.is_empty()
  827. __bool__ = __nonzero__
  828. def is_empty(self):
  829. """Returns True if not documents matched the query.
  830. """
  831. return self.scored_length() == 0
  832. def items(self):
  833. """Returns an iterator of (docnum, score) pairs for the scored
  834. documents in the results.
  835. """
  836. return ((docnum, score) for score, docnum in self.top_n)
  837. def fields(self, n):
  838. """Returns the stored fields for the document at the ``n`` th position
  839. in the results. Use :meth:`Results.docnum` if you want the raw
  840. document number instead of the stored fields.
  841. """
  842. return self.searcher.stored_fields(self.top_n[n][1])
  843. def facet_names(self):
  844. """Returns the available facet names, for use with the ``groups()``
  845. method.
  846. """
  847. return self._facetmaps.keys()
  848. def groups(self, name=None):
  849. """If you generated facet groupings for the results using the
  850. `groupedby` keyword argument to the ``search()`` method, you can use
  851. this method to retrieve the groups. You can use the ``facet_names()``
  852. method to get the list of available facet names.
  853. >>> results = searcher.search(my_query, groupedby=["tag", "price"])
  854. >>> results.facet_names()
  855. ["tag", "price"]
  856. >>> results.groups("tag")
  857. {"new": [12, 1, 4], "apple": [3, 10, 5], "search": [11]}
  858. If you only used one facet, you can call the method without a facet
  859. name to get the groups for the facet.
  860. >>> results = searcher.search(my_query, groupedby="tag")
  861. >>> results.groups()
  862. {"new": [12, 1, 4], "apple": [3, 10, 5, 0], "search": [11]}
  863. By default, this returns a dictionary mapping category names to a list
  864. of document numbers, in the same relative order as they appear in the
  865. results.
  866. >>> results = mysearcher.search(myquery, groupedby="tag")
  867. >>> docnums = results.groups()
  868. >>> docnums['new']
  869. [12, 1, 4]
  870. You can then use :meth:`Searcher.stored_fields` to get the stored
  871. fields associated with a document ID.
  872. If you specified a different ``maptype`` for the facet when you
  873. searched, the values in the dictionary depend on the
  874. :class:`whoosh.sorting.FacetMap`.
  875. >>> myfacet = sorting.FieldFacet("tag", maptype=sorting.Count)
  876. >>> results = mysearcher.search(myquery, groupedby=myfacet)
  877. >>> counts = results.groups()
  878. {"new": 3, "apple": 4, "search": 1}
  879. """
  880. if (name is None or name == "facet") and len(self._facetmaps) == 1:
  881. # If there's only one facet, just use it; convert keys() to list
  882. # for Python 3
  883. name = list(self._facetmaps.keys())[0]
  884. elif name not in self._facetmaps:
  885. raise KeyError("%r not in facet names %r"
  886. % (name, self.facet_names()))
  887. return self._facetmaps[name].as_dict()
  888. def has_exact_length(self):
  889. """Returns True if this results object already knows the exact number
  890. of matching documents.
  891. """
  892. if self.collector:
  893. return self.collector.computes_count()
  894. else:
  895. return self._total is not None
  896. def estimated_length(self):
  897. """The estimated maximum number of matching documents, or the
  898. exact number of matching documents if it's known.
  899. """
  900. if self.has_exact_length():
  901. return len(self)
  902. else:
  903. return self.q.estimate_size(self.searcher.reader())
  904. def estimated_min_length(self):
  905. """The estimated minimum number of matching documents, or the
  906. exact number of matching documents if it's known.
  907. """
  908. if self.has_exact_length():
  909. return len(self)
  910. else:
  911. return self.q.estimate_min_size(self.searcher.reader())
  912. def scored_length(self):
  913. """Returns the number of scored documents in the results, equal to or
  914. less than the ``limit`` keyword argument to the search.
  915. >>> r = mysearcher.search(myquery, limit=20)
  916. >>> len(r)
  917. 1246
  918. >>> r.scored_length()
  919. 20
  920. This may be fewer than the total number of documents that match the
  921. query, which is what ``len(Results)`` returns.
  922. """
  923. return len(self.top_n)
  924. def docs(self):
  925. """Returns a set-like object containing the document numbers that
  926. matched the query.
  927. """
  928. if self.docset is None:
  929. self.docset = set(self.collector.all_ids())
  930. return self.docset
  931. def copy(self):
  932. """Returns a deep copy of this results object.
  933. """
  934. # Shallow copy self to get attributes
  935. r = copy.copy(self)
  936. # Deep copies of docset and top_n in case they're modified
  937. r.docset = copy.deepcopy(self.docset)
  938. r.top_n = copy.deepcopy(self.top_n)
  939. return r
  940. def score(self, n):
  941. """Returns the score for the document at the Nth position in the list
  942. of ranked documents. If the search was not scored, this may return
  943. None.
  944. """
  945. return self.top_n[n][0]
  946. def docnum(self, n):
  947. """Returns the document number of the result at position n in the list
  948. of ranked documents.
  949. """
  950. return self.top_n[n][1]
  951. def query_terms(self, expand=False, fieldname=None):
  952. return self.q.existing_terms(self.searcher.reader(),
  953. fieldname=fieldname, expand=expand)
  954. def has_matched_terms(self):
  955. """Returns True if the search recorded which terms matched in which
  956. documents.
  957. >>> r = searcher.search(myquery)
  958. >>> r.has_matched_terms()
  959. False
  960. >>>
  961. """
  962. return hasattr(self, "docterms") and hasattr(self, "termdocs")
  963. def matched_terms(self):
  964. """Returns the set of ``("fieldname", "text")`` tuples representing
  965. terms from the query that matched one or more of the TOP N documents
  966. (this does not report terms for documents that match the query but did
  967. not score high enough to make the top N results). You can compare this
  968. set to the terms from the original query to find terms which didn't
  969. occur in any matching documents.
  970. This is only valid if you used ``terms=True`` in the search call to
  971. record matching terms. Otherwise it will raise an exception.
  972. >>> q = myparser.parse("alfa OR bravo OR charlie")
  973. >>> results = searcher.search(q, terms=True)
  974. >>> results.terms()
  975. set([("content", "alfa"), ("content", "charlie")])
  976. >>> q.all_terms() - results.terms()
  977. set([("content", "bravo")])
  978. """
  979. if not self.has_matched_terms():
  980. raise NoTermsException
  981. return set(self.termdocs.keys())
  982. def _get_fragmenter(self):
  983. return self.highlighter.fragmenter
  984. def _set_fragmenter(self, f):
  985. self.highlighter.fragmenter = f
  986. fragmenter = property(_get_fragmenter, _set_fragmenter)
  987. def _get_formatter(self):
  988. return self.highlighter.formatter
  989. def _set_formatter(self, f):
  990. self.highlighter.formatter = f
  991. formatter = property(_get_formatter, _set_formatter)
  992. def _get_scorer(self):
  993. return self.highlighter.scorer
  994. def _set_scorer(self, s):
  995. self.highlighter.scorer = s
  996. scorer = property(_get_scorer, _set_scorer)
  997. def _get_order(self):
  998. return self.highlighter.order
  999. def _set_order(self, o):
  1000. self.highlighter.order = o
  1001. order = property(_get_order, _set_order)
  1002. def key_terms(self, fieldname, docs=10, numterms=5,
  1003. model=classify.Bo1Model, normalize=True):
  1004. """Returns the 'numterms' most important terms from the top 'docs'
  1005. documents in these results. "Most important" is generally defined as
  1006. terms that occur frequently in the top hits but relatively infrequently
  1007. in the collection as a whole.
  1008. :param fieldname: Look at the terms in this field. This field must
  1009. store vectors.
  1010. :param docs: Look at this many of the top documents of the results.
  1011. :param numterms: Return this number of important terms.
  1012. :param model: The classify.ExpansionModel to use. See the classify
  1013. module.
  1014. :returns: list of unicode strings.
  1015. """
  1016. if not len(self):
  1017. return []
  1018. docs = min(docs, len(self))
  1019. reader = self.searcher.reader()
  1020. expander = classify.Expander(reader, fieldname, model=model)
  1021. for _, docnum in self.top_n[:docs]:
  1022. expander.add_document(docnum)
  1023. return expander.expanded_terms(numterms, normalize=normalize)
  1024. def extend(self, results):
  1025. """Appends hits from 'results' (that are not already in this
  1026. results object) to the end of these results.
  1027. :param results: another results object.
  1028. """
  1029. docs = self.docs()
  1030. for item in results.top_n:
  1031. if item[1] not in docs:
  1032. self.top_n.append(item)
  1033. self.docset = docs | results.docs()
  1034. self._total = len(self.docset)
  1035. def filter(self, results):
  1036. """Removes any hits that are not also in the other results object.
  1037. """
  1038. if not len(results):
  1039. return
  1040. otherdocs = results.docs()
  1041. items = [item for item in self.top_n if item[1] in otherdocs]
  1042. self.docset = self.docs() & otherdocs
  1043. self.top_n = items
  1044. def upgrade(self, results, reverse=False):
  1045. """Re-sorts the results so any hits that are also in 'results' appear
  1046. before hits not in 'results', otherwise keeping their current relative
  1047. positions. This does not add the documents in the other results object
  1048. to this one.
  1049. :param results: another results object.
  1050. :param reverse: if True, lower the position of hits in the other
  1051. results object instead of raising them.
  1052. """
  1053. if not len(results):
  1054. return
  1055. otherdocs = results.docs()
  1056. arein = [item for item in self.top_n if item[1] in otherdocs]
  1057. notin = [item for item in self.top_n if item[1] not in otherdocs]
  1058. if reverse:
  1059. items = notin + arein
  1060. else:
  1061. items = arein + notin
  1062. self.top_n = items
  1063. def upgrade_and_extend(self, results):
  1064. """Combines the effects of extend() and upgrade(): hits that are also
  1065. in 'results' are raised. Then any hits from the other results object
  1066. that are not in this results object are appended to the end.
  1067. :param results: another results object.
  1068. """
  1069. if not len(results):
  1070. return
  1071. docs = self.docs()
  1072. otherdocs = results.docs()
  1073. arein = [item for item in self.top_n if item[1] in otherdocs]
  1074. notin = [item for item in self.top_n if item[1] not in otherdocs]
  1075. other = [item for item in results.top_n if item[1] not in docs]
  1076. self.docset = docs | otherdocs
  1077. self.top_n = arein + notin + other
  1078. class Hit(object):
  1079. """Represents a single search result ("hit") in a Results object.
  1080. This object acts like a dictionary of the matching document's stored
  1081. fields. If for some reason you need an actual ``dict`` object, use
  1082. ``Hit.fields()`` to get one.
  1083. >>> r = searcher.search(query.Term("content", "render"))
  1084. >>> r[0]
  1085. < Hit {title = u"Rendering the scene"} >
  1086. >>> r[0].rank
  1087. 0
  1088. >>> r[0].docnum == 4592
  1089. True
  1090. >>> r[0].score
  1091. 2.52045682
  1092. >>> r[0]["title"]
  1093. "Rendering the scene"
  1094. >>> r[0].keys()
  1095. ["title"]
  1096. """
  1097. def __init__(self, results, docnum, pos=None, score=None):
  1098. """
  1099. :param results: the Results object this hit belongs to.
  1100. :param pos: the position in the results list of this hit, for example
  1101. pos = 0 means this is the first (highest scoring) hit.
  1102. :param docnum: the document number of this hit.
  1103. :param score: the score of this hit.
  1104. """
  1105. self.results = results
  1106. self.searcher = results.searcher
  1107. self.reader = self.searcher.reader()
  1108. self.pos = self.rank = pos
  1109. self.docnum = docnum
  1110. self.score = score
  1111. self._fields = None
  1112. def fields(self):
  1113. """Returns a dictionary of the stored fields of the document this
  1114. object represents.
  1115. """
  1116. if self._fields is None:
  1117. self._fields = self.searcher.stored_fields(self.docnum)
  1118. return self._fields
  1119. def matched_terms(self):
  1120. """Returns the set of ``("fieldname", "text")`` tuples representing
  1121. terms from the query that matched in this document. You can
  1122. compare this set to the terms from the original query to find terms
  1123. which didn't occur in this document.
  1124. This is only valid if you used ``terms=True`` in the search call to
  1125. record matching terms. Otherwise it will raise an exception.
  1126. >>> q = myparser.parse("alfa OR bravo OR charlie")
  1127. >>> results = searcher.search(q, terms=True)
  1128. >>> for hit in results:
  1129. ... print(hit["title"])
  1130. ... print("Contains:", hit.matched_terms())
  1131. ... print("Doesn't contain:", q.all_terms() - hit.matched_terms())
  1132. """
  1133. if not self.results.has_matched_terms():
  1134. raise NoTermsException
  1135. return self.results.docterms.get(self.docnum, [])
  1136. def highlights(self, fieldname, text=None, top=3, minscore=1):
  1137. """Returns highlighted snippets from the given field::
  1138. r = searcher.search(myquery)
  1139. for hit in r:
  1140. print(hit["title"])
  1141. print(hit.highlights("content"))
  1142. See :doc:`/highlight`.
  1143. To change the fragmeter, formatter, order, or scorer used in
  1144. highlighting, you can set attributes on the results object::
  1145. from whoosh import highlight
  1146. results = searcher.search(myquery, terms=True)
  1147. results.fragmenter = highlight.SentenceFragmenter()
  1148. ...or use a custom :class:`whoosh.highlight.Highlighter` object::
  1149. hl = highlight.Highlighter(fragmenter=sf)
  1150. results.highlighter = hl
  1151. :param fieldname: the name of the field you want to highlight.
  1152. :param text: by default, the method will attempt to load the contents
  1153. of the field from the stored fields for the document. If the field
  1154. you want to highlight isn't stored in the index, but you have
  1155. access to the text another way (for example, loading from a file or
  1156. a database), you can supply it using the ``text`` parameter.
  1157. :param top: the maximum number of fragments to return.
  1158. :param minscore: the minimum score for fragments to appear in the
  1159. highlights.
  1160. """
  1161. hliter = self.results.highlighter
  1162. return hliter.highlight_hit(self, fieldname, text=text, top=top,
  1163. minscore=minscore)
  1164. def more_like_this(self, fieldname, text=None, top=10, numterms=5,
  1165. model=classify.Bo1Model, normalize=True, filter=None):
  1166. """Returns a new Results object containing documents similar to this
  1167. hit, based on "key terms" in the given field::
  1168. r = searcher.search(myquery)
  1169. for hit in r:
  1170. print(hit["title"])
  1171. print("Top 3 similar documents:")
  1172. for subhit in hit.more_like_this("content", top=3):
  1173. print(" ", subhit["title"])
  1174. :param fieldname: the name of the field to use to test similarity.
  1175. :param text: by default, the method will attempt to load the contents
  1176. of the field from the stored fields for the document, or from a
  1177. term vector. If the field isn't stored or vectored in the index,
  1178. but you have access to the text another way (for example, loading
  1179. from a file or a database), you can supply it using the ``text``
  1180. parameter.
  1181. :param top: the number of results to return.
  1182. :param numterms: the number of "key terms" to extract from the hit and
  1183. search for. Using more terms is slower but gives potentially more
  1184. and more accurate results.
  1185. :param model: (expert) a :class:`whoosh.classify.ExpansionModel` to use
  1186. to compute "key terms".
  1187. :param normalize: whether to normalize term weights.
  1188. """
  1189. return self.searcher.more_like(self.docnum, fieldname, text=text,
  1190. top=top, numterms=numterms, model=model,
  1191. normalize=normalize, filter=filter)
  1192. def __repr__(self):
  1193. return "<%s %r>" % (self.__class__.__name__, self.fields())
  1194. def __eq__(self, other):
  1195. if isinstance(other, Hit):
  1196. return self.fields() == other.fields()
  1197. elif isinstance(other, dict):
  1198. return self.fields() == other
  1199. else:
  1200. return False
  1201. def __len__(self):
  1202. return len(self.fields())
  1203. def __iter__(self):
  1204. return iterkeys(self.fields())
  1205. def __getitem__(self, fieldname):
  1206. if fieldname in self.fields():
  1207. return self._fields[fieldname]
  1208. reader = self.reader
  1209. if reader.has_column(fieldname):
  1210. cr = reader.column_reader(fieldname)
  1211. return cr[self.docnum]
  1212. raise KeyError(fieldname)
  1213. def __contains__(self, key):
  1214. return (key in self.fields()
  1215. or self.reader.has_column(key))
  1216. def items(self):
  1217. return list(self.fields().items())
  1218. def keys(self):
  1219. return list(self.fields().keys())
  1220. def values(self):
  1221. return list(self.fields().values())
  1222. def iteritems(self):
  1223. return iteritems(self.fields())
  1224. def iterkeys(self):
  1225. return iterkeys(self.fields())
  1226. def itervalues(self):
  1227. return itervalues(self.fields())
  1228. def get(self, key, default=None):
  1229. return self.fields().get(key, default)
  1230. def __setitem__(self, key, value):
  1231. raise NotImplementedError("You cannot modify a search result")
  1232. def __delitem__(self, key, value):
  1233. raise NotImplementedError("You cannot modify a search result")
  1234. def clear(self):
  1235. raise NotImplementedError("You cannot modify a search result")
  1236. def update(self, dict=None, **kwargs):
  1237. raise NotImplementedError("You cannot modify a search result")
  1238. class ResultsPage(object):
  1239. """Represents a single page out of a longer list of results, as returned
  1240. by :func:`whoosh.searching.Searcher.search_page`. Supports a subset of the
  1241. interface of the :class:`~whoosh.searching.Results` object, namely getting
  1242. stored fields with __getitem__ (square brackets), iterating, and the
  1243. ``score()`` and ``docnum()`` methods.
  1244. The ``offset`` attribute contains the results number this page starts at
  1245. (numbered from 0). For example, if the page length is 10, the ``offset``
  1246. attribute on the second page will be ``10``.
  1247. The ``pagecount`` attribute contains the number of pages available.
  1248. The ``pagenum`` attribute contains the page number. This may be less than
  1249. the page you requested if the results had too few pages. For example, if
  1250. you do::
  1251. ResultsPage(results, 5)
  1252. but the results object only contains 3 pages worth of hits, ``pagenum``
  1253. will be 3.
  1254. The ``pagelen`` attribute contains the number of results on this page
  1255. (which may be less than the page length you requested if this is the last
  1256. page of the results).
  1257. The ``total`` attribute contains the total number of hits in the results.
  1258. >>> mysearcher = myindex.searcher()
  1259. >>> pagenum = 2
  1260. >>> page = mysearcher.find_page(pagenum, myquery)
  1261. >>> print("Page %s of %s, results %s to %s of %s" %
  1262. ... (pagenum, page.pagecount, page.offset+1,
  1263. ... page.offset+page.pagelen, page.total))
  1264. >>> for i, fields in enumerate(page):
  1265. ... print("%s. %r" % (page.offset + i + 1, fields))
  1266. >>> mysearcher.close()
  1267. To set highlighter attributes (for example ``formatter``), access the
  1268. underlying :class:`Results` object::
  1269. page.results.formatter = highlight.UppercaseFormatter()
  1270. """
  1271. def __init__(self, results, pagenum, pagelen=10):
  1272. """
  1273. :param results: a :class:`~whoosh.searching.Results` object.
  1274. :param pagenum: which page of the results to use, numbered from ``1``.
  1275. :param pagelen: the number of hits per page.
  1276. """
  1277. self.results = results
  1278. self.total = len(results)
  1279. if pagenum < 1:
  1280. raise ValueError("pagenum must be >= 1")
  1281. self.pagecount = int(ceil(self.total / pagelen))
  1282. self.pagenum = min(self.pagecount, pagenum)
  1283. offset = (self.pagenum - 1) * pagelen
  1284. if (offset + pagelen) > self.total:
  1285. pagelen = self.total - offset
  1286. self.offset = offset
  1287. self.pagelen = pagelen
  1288. def __getitem__(self, n):
  1289. offset = self.offset
  1290. if isinstance(n, slice):
  1291. start, stop, step = n.indices(self.pagelen)
  1292. return self.results.__getitem__(slice(start + offset,
  1293. stop + offset, step))
  1294. else:
  1295. return self.results.__getitem__(n + offset)
  1296. def __iter__(self):
  1297. return iter(self.results[self.offset:self.offset + self.pagelen])
  1298. def __len__(self):
  1299. return self.total
  1300. def scored_length(self):
  1301. return self.results.scored_length()
  1302. def score(self, n):
  1303. """Returns the score of the hit at the nth position on this page.
  1304. """
  1305. return self.results.score(n + self.offset)
  1306. def docnum(self, n):
  1307. """Returns the document number of the hit at the nth position on this
  1308. page.
  1309. """
  1310. return self.results.docnum(n + self.offset)
  1311. def is_last_page(self):
  1312. """Returns True if this object represents the last page of results.
  1313. """
  1314. return self.pagecount == 0 or self.pagenum == self.pagecount