sorting.py 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156
  1. # Copyright 2011 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. from array import array
  28. from collections import defaultdict
  29. from whoosh.compat import string_type
  30. from whoosh.compat import iteritems, izip, xrange
  31. # Faceting objects
  32. class FacetType(object):
  33. """Base class for "facets", aspects that can be sorted/faceted.
  34. """
  35. maptype = None
  36. def categorizer(self, global_searcher):
  37. """Returns a :class:`Categorizer` corresponding to this facet.
  38. :param global_searcher: A parent searcher. You can use this searcher if
  39. you need global document ID references.
  40. """
  41. raise NotImplementedError
  42. def map(self, default=None):
  43. t = self.maptype
  44. if t is None:
  45. t = default
  46. if t is None:
  47. return OrderedList()
  48. elif type(t) is type:
  49. return t()
  50. else:
  51. return t
  52. def default_name(self):
  53. return "facet"
  54. class Categorizer(object):
  55. """Base class for categorizer objects which compute a key value for a
  56. document based on certain criteria, for use in sorting/faceting.
  57. Categorizers are created by FacetType objects through the
  58. :meth:`FacetType.categorizer` method. The
  59. :class:`whoosh.searching.Searcher` object passed to the ``categorizer``
  60. method may be a composite searcher (that is, wrapping a multi-reader), but
  61. categorizers are always run **per-segment**, with segment-relative document
  62. numbers.
  63. The collector will call a categorizer's ``set_searcher`` method as it
  64. searches each segment to let the cateogorizer set up whatever segment-
  65. specific data it needs.
  66. ``Collector.allow_overlap`` should be ``True`` if the caller can use the
  67. ``keys_for`` method instead of ``key_for`` to group documents into
  68. potentially overlapping groups. The default is ``False``.
  69. If a categorizer subclass can categorize the document using only the
  70. document number, it should set ``Collector.needs_current`` to ``False``
  71. (this is the default) and NOT USE the given matcher in the ``key_for`` or
  72. ``keys_for`` methods, since in that case ``segment_docnum`` is not
  73. guaranteed to be consistent with the given matcher. If a categorizer
  74. subclass needs to access information on the matcher, it should set
  75. ``needs_current`` to ``True``. This will prevent the caller from using
  76. optimizations that might leave the matcher in an inconsistent state.
  77. """
  78. allow_overlap = False
  79. needs_current = False
  80. def set_searcher(self, segment_searcher, docoffset):
  81. """Called by the collector when the collector moves to a new segment.
  82. The ``segment_searcher`` will be atomic. The ``docoffset`` is the
  83. offset of the segment's document numbers relative to the entire index.
  84. You can use the offset to get absolute index docnums by adding the
  85. offset to segment-relative docnums.
  86. """
  87. pass
  88. def key_for(self, matcher, segment_docnum):
  89. """Returns a key for the current match.
  90. :param matcher: a :class:`whoosh.matching.Matcher` object. If
  91. ``self.needs_current`` is ``False``, DO NOT use this object,
  92. since it may be inconsistent. Use the given ``segment_docnum``
  93. instead.
  94. :param segment_docnum: the segment-relative document number of the
  95. current match.
  96. """
  97. # Backwards compatibility
  98. if hasattr(self, "key_for_id"):
  99. return self.key_for_id(segment_docnum)
  100. elif hasattr(self, "key_for_matcher"):
  101. return self.key_for_matcher(matcher)
  102. raise NotImplementedError(self.__class__)
  103. def keys_for(self, matcher, segment_docnum):
  104. """Yields a series of keys for the current match.
  105. This method will be called instead of ``key_for`` if
  106. ``self.allow_overlap`` is ``True``.
  107. :param matcher: a :class:`whoosh.matching.Matcher` object. If
  108. ``self.needs_current`` is ``False``, DO NOT use this object,
  109. since it may be inconsistent. Use the given ``segment_docnum``
  110. instead.
  111. :param segment_docnum: the segment-relative document number of the
  112. current match.
  113. """
  114. # Backwards compatibility
  115. if hasattr(self, "keys_for_id"):
  116. return self.keys_for_id(segment_docnum)
  117. raise NotImplementedError(self.__class__)
  118. def key_to_name(self, key):
  119. """Returns a representation of the key to be used as a dictionary key
  120. in faceting. For example, the sorting key for date fields is a large
  121. integer; this method translates it into a ``datetime`` object to make
  122. the groupings clearer.
  123. """
  124. return key
  125. # General field facet
  126. class FieldFacet(FacetType):
  127. """Sorts/facets by the contents of a field.
  128. For example, to sort by the contents of the "path" field in reverse order,
  129. and facet by the contents of the "tag" field::
  130. paths = FieldFacet("path", reverse=True)
  131. tags = FieldFacet("tag")
  132. results = searcher.search(myquery, sortedby=paths, groupedby=tags)
  133. This facet returns different categorizers based on the field type.
  134. """
  135. def __init__(self, fieldname, reverse=False, allow_overlap=False,
  136. maptype=None):
  137. """
  138. :param fieldname: the name of the field to sort/facet on.
  139. :param reverse: if True, when sorting, reverse the sort order of this
  140. facet.
  141. :param allow_overlap: if True, when grouping, allow documents to appear
  142. in multiple groups when they have multiple terms in the field.
  143. """
  144. self.fieldname = fieldname
  145. self.reverse = reverse
  146. self.allow_overlap = allow_overlap
  147. self.maptype = maptype
  148. def default_name(self):
  149. return self.fieldname
  150. def categorizer(self, global_searcher):
  151. # The searcher we're passed here may wrap a multireader, but the
  152. # actual key functions will always be called per-segment following a
  153. # Categorizer.set_searcher method call
  154. fieldname = self.fieldname
  155. fieldobj = global_searcher.schema[fieldname]
  156. # If we're grouping with allow_overlap=True, all we can use is
  157. # OverlappingCategorizer
  158. if self.allow_overlap:
  159. return OverlappingCategorizer(global_searcher, fieldname)
  160. if global_searcher.reader().has_column(fieldname):
  161. coltype = fieldobj.column_type
  162. if coltype.reversible or not self.reverse:
  163. c = ColumnCategorizer(global_searcher, fieldname, self.reverse)
  164. else:
  165. c = ReversedColumnCategorizer(global_searcher, fieldname)
  166. else:
  167. c = PostingCategorizer(global_searcher, fieldname,
  168. self.reverse)
  169. return c
  170. class ColumnCategorizer(Categorizer):
  171. def __init__(self, global_searcher, fieldname, reverse=False):
  172. self._fieldname = fieldname
  173. self._fieldobj = global_searcher.schema[self._fieldname]
  174. self._column_type = self._fieldobj.column_type
  175. self._reverse = reverse
  176. # The column reader is set in set_searcher() as we iterate over the
  177. # sub-searchers
  178. self._creader = None
  179. def __repr__(self):
  180. return "%s(%r, %r, reverse=%r)" % (self.__class__.__name__,
  181. self._fieldobj, self._fieldname,
  182. self._reverse)
  183. def set_searcher(self, segment_searcher, docoffset):
  184. r = segment_searcher.reader()
  185. self._creader = r.column_reader(self._fieldname,
  186. reverse=self._reverse,
  187. translate=False)
  188. def key_for(self, matcher, segment_docnum):
  189. return self._creader.sort_key(segment_docnum)
  190. def key_to_name(self, key):
  191. return self._fieldobj.from_column_value(key)
  192. class ReversedColumnCategorizer(ColumnCategorizer):
  193. """Categorizer that reverses column values for columns that aren't
  194. naturally reversible.
  195. """
  196. def __init__(self, global_searcher, fieldname):
  197. ColumnCategorizer.__init__(self, global_searcher, fieldname)
  198. reader = global_searcher.reader()
  199. self._doccount = reader.doc_count_all()
  200. global_creader = reader.column_reader(fieldname, translate=False)
  201. self._values = sorted(set(global_creader))
  202. def key_for(self, matcher, segment_docnum):
  203. value = self._creader[segment_docnum]
  204. order = self._values.index(value)
  205. # Subtract from 0 to reverse the order
  206. return 0 - order
  207. def key_to_name(self, key):
  208. # Re-reverse the key to get the index into _values
  209. key = self._values[0 - key]
  210. return ColumnCategorizer.key_to_name(self, key)
  211. class OverlappingCategorizer(Categorizer):
  212. allow_overlap = True
  213. def __init__(self, global_searcher, fieldname):
  214. self._fieldname = fieldname
  215. self._fieldobj = global_searcher.schema[fieldname]
  216. field = global_searcher.schema[fieldname]
  217. reader = global_searcher.reader()
  218. self._use_vectors = bool(field.vector)
  219. self._use_column = (reader.has_column(fieldname)
  220. and field.column_type.stores_lists())
  221. # These are set in set_searcher() as we iterate over the sub-searchers
  222. self._segment_searcher = None
  223. self._creader = None
  224. self._lists = None
  225. def set_searcher(self, segment_searcher, docoffset):
  226. fieldname = self._fieldname
  227. self._segment_searcher = segment_searcher
  228. reader = segment_searcher.reader()
  229. if self._use_vectors:
  230. pass
  231. elif self._use_column:
  232. self._creader = reader.column_reader(fieldname, translate=False)
  233. else:
  234. # Otherwise, cache the values in each document in a huge list
  235. # of lists
  236. dc = segment_searcher.doc_count_all()
  237. field = segment_searcher.schema[fieldname]
  238. from_bytes = field.from_bytes
  239. self._lists = [[] for _ in xrange(dc)]
  240. for btext in field.sortable_terms(reader, fieldname):
  241. text = from_bytes(btext)
  242. postings = reader.postings(fieldname, btext)
  243. for docid in postings.all_ids():
  244. self._lists[docid].append(text)
  245. def keys_for(self, matcher, docid):
  246. if self._use_vectors:
  247. try:
  248. v = self._segment_searcher.vector(docid, self._fieldname)
  249. return list(v.all_ids())
  250. except KeyError:
  251. return []
  252. elif self._use_column:
  253. return self._creader[docid]
  254. else:
  255. return self._lists[docid] or [None]
  256. def key_for(self, matcher, docid):
  257. if self._use_vectors:
  258. try:
  259. v = self._segment_searcher.vector(docid, self._fieldname)
  260. return v.id()
  261. except KeyError:
  262. return None
  263. elif self._use_column:
  264. return self._creader.sort_key(docid)
  265. else:
  266. ls = self._lists[docid]
  267. if ls:
  268. return ls[0]
  269. else:
  270. return None
  271. class PostingCategorizer(Categorizer):
  272. """
  273. Categorizer for fields that don't store column values. This is very
  274. inefficient. Instead of relying on this categorizer you should plan for
  275. which fields you'll want to sort on and set ``sortable=True`` in their
  276. field type.
  277. This object builds an array caching the order of all documents according to
  278. the field, then uses the cached order as a numeric key. This is useful when
  279. a field cache is not available, and also for reversed fields (since field
  280. cache keys for non- numeric fields are arbitrary data, it's not possible to
  281. "negate" them to reverse the sort order).
  282. """
  283. def __init__(self, global_searcher, fieldname, reverse):
  284. self.reverse = reverse
  285. if fieldname in global_searcher._field_caches:
  286. self.values, self.array = global_searcher._field_caches[fieldname]
  287. else:
  288. # Cache the relative positions of all docs with the given field
  289. # across the entire index
  290. reader = global_searcher.reader()
  291. dc = reader.doc_count_all()
  292. self._fieldobj = global_searcher.schema[fieldname]
  293. from_bytes = self._fieldobj.from_bytes
  294. self.values = []
  295. self.array = array("i", [dc + 1] * dc)
  296. btexts = self._fieldobj.sortable_terms(reader, fieldname)
  297. for i, btext in enumerate(btexts):
  298. self.values.append(from_bytes(btext))
  299. # Get global docids from global reader
  300. postings = reader.postings(fieldname, btext)
  301. for docid in postings.all_ids():
  302. self.array[docid] = i
  303. global_searcher._field_caches[fieldname] = (self.values, self.array)
  304. def set_searcher(self, segment_searcher, docoffset):
  305. self._searcher = segment_searcher
  306. self.docoffset = docoffset
  307. def key_for(self, matcher, segment_docnum):
  308. global_docnum = self.docoffset + segment_docnum
  309. i = self.array[global_docnum]
  310. if self.reverse:
  311. i = len(self.values) - i
  312. return i
  313. def key_to_name(self, i):
  314. if i >= len(self.values):
  315. return None
  316. if self.reverse:
  317. i = len(self.values) - i
  318. return self.values[i]
  319. # Special facet types
  320. class QueryFacet(FacetType):
  321. """Sorts/facets based on the results of a series of queries.
  322. """
  323. def __init__(self, querydict, other=None, allow_overlap=False,
  324. maptype=None):
  325. """
  326. :param querydict: a dictionary mapping keys to
  327. :class:`whoosh.query.Query` objects.
  328. :param other: the key to use for documents that don't match any of the
  329. queries.
  330. """
  331. self.querydict = querydict
  332. self.other = other
  333. self.maptype = maptype
  334. self.allow_overlap = allow_overlap
  335. def categorizer(self, global_searcher):
  336. return self.QueryCategorizer(self.querydict, self.other, self.allow_overlap)
  337. class QueryCategorizer(Categorizer):
  338. def __init__(self, querydict, other, allow_overlap=False):
  339. self.querydict = querydict
  340. self.other = other
  341. self.allow_overlap = allow_overlap
  342. def set_searcher(self, segment_searcher, offset):
  343. self.docsets = {}
  344. for qname, q in self.querydict.items():
  345. docset = set(q.docs(segment_searcher))
  346. if docset:
  347. self.docsets[qname] = docset
  348. self.offset = offset
  349. def key_for(self, matcher, docid):
  350. for qname in self.docsets:
  351. if docid in self.docsets[qname]:
  352. return qname
  353. return self.other
  354. def keys_for(self, matcher, docid):
  355. found = False
  356. for qname in self.docsets:
  357. if docid in self.docsets[qname]:
  358. yield qname
  359. found = True
  360. if not found:
  361. yield None
  362. class RangeFacet(QueryFacet):
  363. """Sorts/facets based on numeric ranges. For textual ranges, use
  364. :class:`QueryFacet`.
  365. For example, to facet the "price" field into $100 buckets, up to $1000::
  366. prices = RangeFacet("price", 0, 1000, 100)
  367. results = searcher.search(myquery, groupedby=prices)
  368. The ranges/buckets are always **inclusive** at the start and **exclusive**
  369. at the end.
  370. """
  371. def __init__(self, fieldname, start, end, gap, hardend=False,
  372. maptype=None):
  373. """
  374. :param fieldname: the numeric field to sort/facet on.
  375. :param start: the start of the entire range.
  376. :param end: the end of the entire range.
  377. :param gap: the size of each "bucket" in the range. This can be a
  378. sequence of sizes. For example, ``gap=[1,5,10]`` will use 1 as the
  379. size of the first bucket, 5 as the size of the second bucket, and
  380. 10 as the size of all subsequent buckets.
  381. :param hardend: if True, the end of the last bucket is clamped to the
  382. value of ``end``. If False (the default), the last bucket is always
  383. ``gap`` sized, even if that means the end of the last bucket is
  384. after ``end``.
  385. """
  386. self.fieldname = fieldname
  387. self.start = start
  388. self.end = end
  389. self.gap = gap
  390. self.hardend = hardend
  391. self.maptype = maptype
  392. self._queries()
  393. def default_name(self):
  394. return self.fieldname
  395. def _rangetype(self):
  396. from whoosh import query
  397. return query.NumericRange
  398. def _range_name(self, startval, endval):
  399. return (startval, endval)
  400. def _queries(self):
  401. if not self.gap:
  402. raise Exception("No gap secified (%r)" % self.gap)
  403. if isinstance(self.gap, (list, tuple)):
  404. gaps = self.gap
  405. gapindex = 0
  406. else:
  407. gaps = [self.gap]
  408. gapindex = -1
  409. rangetype = self._rangetype()
  410. self.querydict = {}
  411. cstart = self.start
  412. while cstart < self.end:
  413. thisgap = gaps[gapindex]
  414. if gapindex >= 0:
  415. gapindex += 1
  416. if gapindex == len(gaps):
  417. gapindex = -1
  418. cend = cstart + thisgap
  419. if self.hardend:
  420. cend = min(self.end, cend)
  421. rangename = self._range_name(cstart, cend)
  422. q = rangetype(self.fieldname, cstart, cend, endexcl=True)
  423. self.querydict[rangename] = q
  424. cstart = cend
  425. def categorizer(self, global_searcher):
  426. return QueryFacet(self.querydict).categorizer(global_searcher)
  427. class DateRangeFacet(RangeFacet):
  428. """Sorts/facets based on date ranges. This is the same as RangeFacet
  429. except you are expected to use ``daterange`` objects as the start and end
  430. of the range, and ``timedelta`` or ``relativedelta`` objects as the gap(s),
  431. and it generates :class:`~whoosh.query.DateRange` queries instead of
  432. :class:`~whoosh.query.TermRange` queries.
  433. For example, to facet a "birthday" range into 5 year buckets::
  434. from datetime import datetime
  435. from whoosh.support.relativedelta import relativedelta
  436. startdate = datetime(1920, 0, 0)
  437. enddate = datetime.now()
  438. gap = relativedelta(years=5)
  439. bdays = DateRangeFacet("birthday", startdate, enddate, gap)
  440. results = searcher.search(myquery, groupedby=bdays)
  441. The ranges/buckets are always **inclusive** at the start and **exclusive**
  442. at the end.
  443. """
  444. def _rangetype(self):
  445. from whoosh import query
  446. return query.DateRange
  447. class ScoreFacet(FacetType):
  448. """Uses a document's score as a sorting criterion.
  449. For example, to sort by the ``tag`` field, and then within that by relative
  450. score::
  451. tag_score = MultiFacet(["tag", ScoreFacet()])
  452. results = searcher.search(myquery, sortedby=tag_score)
  453. """
  454. def categorizer(self, global_searcher):
  455. return self.ScoreCategorizer(global_searcher)
  456. class ScoreCategorizer(Categorizer):
  457. needs_current = True
  458. def __init__(self, global_searcher):
  459. w = global_searcher.weighting
  460. self.use_final = w.use_final
  461. if w.use_final:
  462. self.final = w.final
  463. def set_searcher(self, segment_searcher, offset):
  464. self.segment_searcher = segment_searcher
  465. def key_for(self, matcher, docid):
  466. score = matcher.score()
  467. if self.use_final:
  468. score = self.final(self.segment_searcher, docid, score)
  469. # Negate the score so higher values sort first
  470. return 0 - score
  471. class FunctionFacet(FacetType):
  472. """This facet type is low-level. In most cases you should use
  473. :class:`TranslateFacet` instead.
  474. This facet type ets you pass an arbitrary function that will compute the
  475. key. This may be easier than subclassing FacetType and Categorizer to set up
  476. the desired behavior.
  477. The function is called with the arguments ``(searcher, docid)``, where the
  478. ``searcher`` may be a composite searcher, and the ``docid`` is an absolute
  479. index document number (not segment-relative).
  480. For example, to use the number of words in the document's "content" field
  481. as the sorting/faceting key::
  482. fn = lambda s, docid: s.doc_field_length(docid, "content")
  483. lengths = FunctionFacet(fn)
  484. """
  485. def __init__(self, fn, maptype=None):
  486. self.fn = fn
  487. self.maptype = maptype
  488. def categorizer(self, global_searcher):
  489. return self.FunctionCategorizer(global_searcher, self.fn)
  490. class FunctionCategorizer(Categorizer):
  491. def __init__(self, global_searcher, fn):
  492. self.global_searcher = global_searcher
  493. self.fn = fn
  494. def set_searcher(self, segment_searcher, docoffset):
  495. self.offset = docoffset
  496. def key_for(self, matcher, docid):
  497. return self.fn(self.global_searcher, docid + self.offset)
  498. class TranslateFacet(FacetType):
  499. """Lets you specify a function to compute the key based on a key generated
  500. by a wrapped facet.
  501. This is useful if you want to use a custom ordering of a sortable field. For
  502. example, if you want to use an implementation of the Unicode Collation
  503. Algorithm (UCA) to sort a field using the rules from a particular language::
  504. from pyuca import Collator
  505. # The Collator object has a sort_key() method which takes a unicode
  506. # string and returns a sort key
  507. c = Collator("allkeys.txt")
  508. # Make a facet object for the field you want to sort on
  509. facet = sorting.FieldFacet("name")
  510. # Wrap the facet in a TranslateFacet with the translation function
  511. # (the Collator object's sort_key method)
  512. facet = sorting.TranslateFacet(c.sort_key, facet)
  513. # Use the facet to sort the search results
  514. results = searcher.search(myquery, sortedby=facet)
  515. You can pass multiple facets to the
  516. """
  517. def __init__(self, fn, *facets):
  518. """
  519. :param fn: The function to apply. For each matching document, this
  520. function will be called with the values of the given facets as
  521. arguments.
  522. :param facets: One or more :class:`FacetType` objects. These facets are
  523. used to compute facet value(s) for a matching document, and then the
  524. value(s) is/are passed to the function.
  525. """
  526. self.fn = fn
  527. self.facets = facets
  528. self.maptype = None
  529. def categorizer(self, global_searcher):
  530. catters = [facet.categorizer(global_searcher) for facet in self.facets]
  531. return self.TranslateCategorizer(self.fn, catters)
  532. class TranslateCategorizer(Categorizer):
  533. def __init__(self, fn, catters):
  534. self.fn = fn
  535. self.catters = catters
  536. def set_searcher(self, segment_searcher, docoffset):
  537. for catter in self.catters:
  538. catter.set_searcher(segment_searcher, docoffset)
  539. def key_for(self, matcher, segment_docnum):
  540. keys = [catter.key_for(matcher, segment_docnum)
  541. for catter in self.catters]
  542. return self.fn(*keys)
  543. class StoredFieldFacet(FacetType):
  544. """Lets you sort/group using the value in an unindexed, stored field (e.g.
  545. :class:`whoosh.fields.STORED`). This is usually slower than using an indexed
  546. field.
  547. For fields where the stored value is a space-separated list of keywords,
  548. (e.g. ``"tag1 tag2 tag3"``), you can use the ``allow_overlap`` keyword
  549. argument to allow overlapped faceting on the result of calling the
  550. ``split()`` method on the field value (or calling a custom split function
  551. if one is supplied).
  552. """
  553. def __init__(self, fieldname, allow_overlap=False, split_fn=None,
  554. maptype=None):
  555. """
  556. :param fieldname: the name of the stored field.
  557. :param allow_overlap: if True, when grouping, allow documents to appear
  558. in multiple groups when they have multiple terms in the field. The
  559. categorizer uses ``string.split()`` or the custom ``split_fn`` to
  560. convert the stored value into a list of facet values.
  561. :param split_fn: a custom function to split a stored field value into
  562. multiple facet values when ``allow_overlap`` is True. If not
  563. supplied, the categorizer simply calls the value's ``split()``
  564. method.
  565. """
  566. self.fieldname = fieldname
  567. self.allow_overlap = allow_overlap
  568. self.split_fn = split_fn
  569. self.maptype = maptype
  570. def default_name(self):
  571. return self.fieldname
  572. def categorizer(self, global_searcher):
  573. return self.StoredFieldCategorizer(self.fieldname, self.allow_overlap,
  574. self.split_fn)
  575. class StoredFieldCategorizer(Categorizer):
  576. def __init__(self, fieldname, allow_overlap, split_fn):
  577. self.fieldname = fieldname
  578. self.allow_overlap = allow_overlap
  579. self.split_fn = split_fn
  580. def set_searcher(self, segment_searcher, docoffset):
  581. self.segment_searcher = segment_searcher
  582. def keys_for(self, matcher, docid):
  583. d = self.segment_searcher.stored_fields(docid)
  584. value = d.get(self.fieldname)
  585. if self.split_fn:
  586. return self.split_fn(value)
  587. else:
  588. return value.split()
  589. def key_for(self, matcher, docid):
  590. d = self.segment_searcher.stored_fields(docid)
  591. return d.get(self.fieldname)
  592. class MultiFacet(FacetType):
  593. """Sorts/facets by the combination of multiple "sub-facets".
  594. For example, to sort by the value of the "tag" field, and then (for
  595. documents where the tag is the same) by the value of the "path" field::
  596. facet = MultiFacet(FieldFacet("tag"), FieldFacet("path")
  597. results = searcher.search(myquery, sortedby=facet)
  598. As a shortcut, you can use strings to refer to field names, and they will
  599. be assumed to be field names and turned into FieldFacet objects::
  600. facet = MultiFacet("tag", "path")
  601. You can also use the ``add_*`` methods to add criteria to the multifacet::
  602. facet = MultiFacet()
  603. facet.add_field("tag")
  604. facet.add_field("path", reverse=True)
  605. facet.add_query({"a-m": TermRange("name", "a", "m"),
  606. "n-z": TermRange("name", "n", "z")})
  607. """
  608. def __init__(self, items=None, maptype=None):
  609. self.facets = []
  610. if items:
  611. for item in items:
  612. self._add(item)
  613. self.maptype = maptype
  614. def __repr__(self):
  615. return "%s(%r, %r)" % (self.__class__.__name__,
  616. self.facets,
  617. self.maptype)
  618. @classmethod
  619. def from_sortedby(cls, sortedby):
  620. multi = cls()
  621. if isinstance(sortedby, string_type):
  622. multi._add(sortedby)
  623. elif (isinstance(sortedby, (list, tuple))
  624. or hasattr(sortedby, "__iter__")):
  625. for item in sortedby:
  626. multi._add(item)
  627. else:
  628. multi._add(sortedby)
  629. return multi
  630. def _add(self, item):
  631. if isinstance(item, FacetType):
  632. self.add_facet(item)
  633. elif isinstance(item, string_type):
  634. self.add_field(item)
  635. else:
  636. raise Exception("Don't know what to do with facet %r" % (item,))
  637. def add_field(self, fieldname, reverse=False):
  638. self.facets.append(FieldFacet(fieldname, reverse=reverse))
  639. return self
  640. def add_query(self, querydict, other=None, allow_overlap=False):
  641. self.facets.append(QueryFacet(querydict, other=other,
  642. allow_overlap=allow_overlap))
  643. return self
  644. def add_score(self):
  645. self.facets.append(ScoreFacet())
  646. return self
  647. def add_facet(self, facet):
  648. if not isinstance(facet, FacetType):
  649. raise TypeError("%r is not a facet object, perhaps you meant "
  650. "add_field()" % (facet,))
  651. self.facets.append(facet)
  652. return self
  653. def categorizer(self, global_searcher):
  654. if not self.facets:
  655. raise Exception("No facets")
  656. elif len(self.facets) == 1:
  657. catter = self.facets[0].categorizer(global_searcher)
  658. else:
  659. catter = self.MultiCategorizer([facet.categorizer(global_searcher)
  660. for facet in self.facets])
  661. return catter
  662. class MultiCategorizer(Categorizer):
  663. def __init__(self, catters):
  664. self.catters = catters
  665. @property
  666. def needs_current(self):
  667. return any(c.needs_current for c in self.catters)
  668. def set_searcher(self, segment_searcher, docoffset):
  669. for catter in self.catters:
  670. catter.set_searcher(segment_searcher, docoffset)
  671. def key_for(self, matcher, docid):
  672. return tuple(catter.key_for(matcher, docid)
  673. for catter in self.catters)
  674. def key_to_name(self, key):
  675. return tuple(catter.key_to_name(keypart)
  676. for catter, keypart
  677. in izip(self.catters, key))
  678. class Facets(object):
  679. """Maps facet names to :class:`FacetType` objects, for creating multiple
  680. groupings of documents.
  681. For example, to group by tag, and **also** group by price range::
  682. facets = Facets()
  683. facets.add_field("tag")
  684. facets.add_facet("price", RangeFacet("price", 0, 1000, 100))
  685. results = searcher.search(myquery, groupedby=facets)
  686. tag_groups = results.groups("tag")
  687. price_groups = results.groups("price")
  688. (To group by the combination of multiple facets, use :class:`MultiFacet`.)
  689. """
  690. def __init__(self, x=None):
  691. self.facets = {}
  692. if x:
  693. self.add_facets(x)
  694. @classmethod
  695. def from_groupedby(cls, groupedby):
  696. facets = cls()
  697. if isinstance(groupedby, (cls, dict)):
  698. facets.add_facets(groupedby)
  699. elif isinstance(groupedby, string_type):
  700. facets.add_field(groupedby)
  701. elif isinstance(groupedby, FacetType):
  702. facets.add_facet(groupedby.default_name(), groupedby)
  703. elif isinstance(groupedby, (list, tuple)):
  704. for item in groupedby:
  705. facets.add_facets(cls.from_groupedby(item))
  706. else:
  707. raise Exception("Don't know what to do with groupedby=%r"
  708. % groupedby)
  709. return facets
  710. def names(self):
  711. """Returns an iterator of the facet names in this object.
  712. """
  713. return iter(self.facets)
  714. def items(self):
  715. """Returns a list of (facetname, facetobject) tuples for the facets in
  716. this object.
  717. """
  718. return self.facets.items()
  719. def add_field(self, fieldname, **kwargs):
  720. """Adds a :class:`FieldFacet` for the given field name (the field name
  721. is automatically used as the facet name).
  722. """
  723. self.facets[fieldname] = FieldFacet(fieldname, **kwargs)
  724. return self
  725. def add_query(self, name, querydict, **kwargs):
  726. """Adds a :class:`QueryFacet` under the given ``name``.
  727. :param name: a name for the facet.
  728. :param querydict: a dictionary mapping keys to
  729. :class:`whoosh.query.Query` objects.
  730. """
  731. self.facets[name] = QueryFacet(querydict, **kwargs)
  732. return self
  733. def add_facet(self, name, facet):
  734. """Adds a :class:`FacetType` object under the given ``name``.
  735. """
  736. if not isinstance(facet, FacetType):
  737. raise Exception("%r:%r is not a facet" % (name, facet))
  738. self.facets[name] = facet
  739. return self
  740. def add_facets(self, facets, replace=True):
  741. """Adds the contents of the given ``Facets`` or ``dict`` object to this
  742. object.
  743. """
  744. if not isinstance(facets, (dict, Facets)):
  745. raise Exception("%r is not a Facets object or dict" % facets)
  746. for name, facet in facets.items():
  747. if replace or name not in self.facets:
  748. self.facets[name] = facet
  749. return self
  750. # Objects for holding facet groups
  751. class FacetMap(object):
  752. """Base class for objects holding the results of grouping search results by
  753. a Facet. Use an object's ``as_dict()`` method to access the results.
  754. You can pass a subclass of this to the ``maptype`` keyword argument when
  755. creating a ``FacetType`` object to specify what information the facet
  756. should record about the group. For example::
  757. # Record each document in each group in its sorted order
  758. myfacet = FieldFacet("size", maptype=OrderedList)
  759. # Record only the count of documents in each group
  760. myfacet = FieldFacet("size", maptype=Count)
  761. """
  762. def add(self, groupname, docid, sortkey):
  763. """Adds a document to the facet results.
  764. :param groupname: the name of the group to add this document to.
  765. :param docid: the document number of the document to add.
  766. :param sortkey: a value representing the sort position of the document
  767. in the full results.
  768. """
  769. raise NotImplementedError
  770. def as_dict(self):
  771. """Returns a dictionary object mapping group names to
  772. implementation-specific values. For example, the value might be a list
  773. of document numbers, or a integer representing the number of documents
  774. in the group.
  775. """
  776. raise NotImplementedError
  777. class OrderedList(FacetMap):
  778. """Stores a list of document numbers for each group, in the same order as
  779. they appear in the search results.
  780. The ``as_dict`` method returns a dictionary mapping group names to lists
  781. of document numbers.
  782. """
  783. def __init__(self):
  784. self.dict = defaultdict(list)
  785. def __repr__(self):
  786. return "<%s %r>" % (self.__class__.__name__, self.dict)
  787. def add(self, groupname, docid, sortkey):
  788. self.dict[groupname].append((sortkey, docid))
  789. def as_dict(self):
  790. d = {}
  791. for key, items in iteritems(self.dict):
  792. d[key] = [docnum for _, docnum in sorted(items)]
  793. return d
  794. class UnorderedList(FacetMap):
  795. """Stores a list of document numbers for each group, in arbitrary order.
  796. This is slightly faster and uses less memory than
  797. :class:`OrderedListResult` if you don't care about the ordering of the
  798. documents within groups.
  799. The ``as_dict`` method returns a dictionary mapping group names to lists
  800. of document numbers.
  801. """
  802. def __init__(self):
  803. self.dict = defaultdict(list)
  804. def __repr__(self):
  805. return "<%s %r>" % (self.__class__.__name__, self.dict)
  806. def add(self, groupname, docid, sortkey):
  807. self.dict[groupname].append(docid)
  808. def as_dict(self):
  809. return dict(self.dict)
  810. class Count(FacetMap):
  811. """Stores the number of documents in each group.
  812. The ``as_dict`` method returns a dictionary mapping group names to
  813. integers.
  814. """
  815. def __init__(self):
  816. self.dict = defaultdict(int)
  817. def __repr__(self):
  818. return "<%s %r>" % (self.__class__.__name__, self.dict)
  819. def add(self, groupname, docid, sortkey):
  820. self.dict[groupname] += 1
  821. def as_dict(self):
  822. return dict(self.dict)
  823. class Best(FacetMap):
  824. """Stores the "best" document in each group (that is, the one with the
  825. highest sort key).
  826. The ``as_dict`` method returns a dictionary mapping group names to
  827. docnument numbers.
  828. """
  829. def __init__(self):
  830. self.bestids = {}
  831. self.bestkeys = {}
  832. def __repr__(self):
  833. return "<%s %r>" % (self.__class__.__name__, self.bestids)
  834. def add(self, groupname, docid, sortkey):
  835. if groupname not in self.bestids or sortkey < self.bestkeys[groupname]:
  836. self.bestids[groupname] = docid
  837. self.bestkeys[groupname] = sortkey
  838. def as_dict(self):
  839. return self.bestids
  840. # Helper functions
  841. def add_sortable(writer, fieldname, facet, column=None):
  842. """Adds a per-document value column to an existing field which was created
  843. without the ``sortable`` keyword argument.
  844. >>> from whoosh import index, sorting
  845. >>> ix = index.open_dir("indexdir")
  846. >>> with ix.writer() as w:
  847. ... facet = sorting.FieldFacet("price")
  848. ... sorting.add_sortable(w, "price", facet)
  849. ...
  850. :param writer: a :class:`whoosh.writing.IndexWriter` object.
  851. :param fieldname: the name of the field to add the per-document sortable
  852. values to. If this field doesn't exist in the writer's schema, the
  853. function will add a :class:`whoosh.fields.COLUMN` field to the schema,
  854. and you must specify the column object to using the ``column`` keyword
  855. argument.
  856. :param facet: a :class:`FacetType` object to use to generate the
  857. per-document values.
  858. :param column: a :class:`whosh.columns.ColumnType` object to use to store
  859. the per-document values. If you don't specify a column object, the
  860. function will use the default column type for the given field.
  861. """
  862. storage = writer.storage
  863. schema = writer.schema
  864. field = None
  865. if fieldname in schema:
  866. field = schema[fieldname]
  867. if field.column_type:
  868. raise Exception("%r field is already sortable" % fieldname)
  869. if column:
  870. if fieldname not in schema:
  871. from whoosh.fields import COLUMN
  872. field = COLUMN(column)
  873. schema.add(fieldname, field)
  874. else:
  875. if fieldname in schema:
  876. column = field.default_column()
  877. else:
  878. raise Exception("Field %r does not exist" % fieldname)
  879. searcher = writer.searcher()
  880. catter = facet.categorizer(searcher)
  881. for subsearcher, docoffset in searcher.leaf_searchers():
  882. catter.set_searcher(subsearcher, docoffset)
  883. reader = subsearcher.reader()
  884. if reader.has_column(fieldname):
  885. raise Exception("%r field already has a column" % fieldname)
  886. codec = reader.codec()
  887. segment = reader.segment()
  888. colname = codec.column_filename(segment, fieldname)
  889. colfile = storage.create_file(colname)
  890. try:
  891. colwriter = column.writer(colfile)
  892. for docnum in reader.all_doc_ids():
  893. v = catter.key_to_name(catter.key_for(None, docnum))
  894. cv = field.to_column_value(v)
  895. colwriter.add(docnum, cv)
  896. colwriter.finish(reader.doc_count_all())
  897. finally:
  898. colfile.close()
  899. field.column_type = column