whoosh / src / whoosh / sorting.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
# Copyright 2011 Matt Chaput. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#    1. Redistributions of source code must retain the above copyright notice,
#       this list of conditions and the following disclaimer.
#
#    2. Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY MATT CHAPUT ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
# EVENT SHALL MATT CHAPUT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and documentation are
# those of the authors and should not be interpreted as representing official
# policies, either expressed or implied, of Matt Chaput.

from array import array

from whoosh.compat import string_type, u, xrange
from whoosh.fields import DEFAULT_LONG
from whoosh.support.times import (long_to_datetime, datetime_to_long,
                                  timedelta_to_usecs)


# Faceting objects

class FacetType(object):
    """Base class for "facets", aspects that can be sorted/faceted.
    """

    def categorizer(self, searcher):
        """Returns a :class:`Categorizer` corresponding to this facet.
        """

        raise NotImplementedError


class Categorizer(object):
    """Base class for categorizer objects which compute a key value for a
    document based on certain criteria, for use in sorting/faceting.
    
    Categorizers are created by FacetType objects through the
    :meth:`FacetType.categorizer` method. The
    :class:`whoosh.searching.Searcher` object passed to the ``categorizer``
    method may be a composite searcher (that is, wrapping a multi-reader), but
    categorizers are always run **per-segment**, with segment-relative document
    numbers.
    
    The collector will call a categorizer's ``set_searcher`` method as it
    searches each segment to let the cateogorizer set up whatever segment-
    specific data it needs.
    
    ``Collector.allow_overlap`` should be True if the caller should use the
    ``keys_for_id`` method instead of ``key_for_id`` to group documents into
    potentially overlapping groups.
    """

    allow_overlap = False
    requires_matcher = False

    def set_searcher(self, searcher, docoffset):
        """Called by the collector when the collector moves to a new segment.
        The ``searcher`` will be atomic. The ``docoffset`` is the offset of
        the segment's document numbers relative to the entire index. You can
        use the offset to get absolute index docnums by adding the offset to
        segment-relative docnums.
        """

        pass

    def key_for_matcher(self, matcher):
        """Returns a key for the given matcher. The default implementation
        simply gets the matcher's current document ID and calls ``key_for_id``,
        but a subclass can override this if it needs information from the
        matcher to compute the key.
        """

        return self.key_for_id(matcher.id())

    def key_for_id(self, docid):
        """Returns a key for the given **segment-relative** document number.
        """

        raise NotImplementedError(self.__class__)

    def keys_for_id(self, docid):
        """Yields a series of keys for the given **segment-relative** document
        number. This method will be called instead of ``key_for_id`` if
        ``Categorizer.allow_overlap==True``.
        """

        raise NotImplementedError(self.__class__)

    def key_to_name(self, key):
        """Returns a representation of the key to be used as a dictionary key
        in faceting. For example, the sorting key for date fields is a large
        integer; this method translates it into a ``datetime`` object to make
        the groupings clearer.
        """

        return key


class FieldFacet(FacetType):
    """Sorts/facest by the contents of a field.
    
    For example, to sort by the contents of the "path" field in reverse order,
    and facet by the contents of the "tag" field::
    
        paths = FieldFacet("path", reverse=True)
        tags = FieldFacet("tag")
        results = searcher.search(myquery, sortedby=paths, groupedby=tags)
    
    This facet returns different categorizers based on the field type.
    """

    def __init__(self, fieldname, reverse=False, allow_overlap=False):
        """
        :param fieldname: the name of the field to sort/facet on.
        :param reverse: if True, when sorting, reverse the sort order of this
            facet.
        :param allow_overlap: if True, when grouping, allow documents to appear
            in multiple groups when they have multiple terms in the field.
        """

        self.fieldname = fieldname
        self.reverse = reverse
        self.allow_overlap = allow_overlap

    def categorizer(self, searcher):
        from whoosh.fields import NUMERIC, DATETIME

        # The searcher we're passed here may wrap a multireader, but the
        # actual key functions will always be called per-segment following a
        # Categorizer.set_searcher method call
        fieldname = self.fieldname
        field = None
        if fieldname in searcher.schema:
            field = searcher.schema[fieldname]
        hascache = searcher.reader().supports_caches()

        if self.allow_overlap:
            return self.OverlappingFieldCategorizer(fieldname)

        elif hascache and isinstance(field, DATETIME):
            # Return a subclass of NumericFieldCategorizer that formats dates
            return self.DateFieldCategorizer(fieldname, self.reverse)

        elif hascache and isinstance(field, NUMERIC):
            # Numeric fields are naturally reversible
            return self.NumericFieldCategorizer(fieldname, self.reverse)

        elif hascache and not self.reverse:
            # Straightforward: use the field cache to sort/categorize
            return self.FieldCategorizer(fieldname)

        else:
            # If the reader does not support field caches or we need to
            # reverse-sort a string field, we need to do more work
            return self.NoCacheFieldCategorizer(searcher, fieldname,
                                                self.reverse)

    class FieldCategorizer(Categorizer):
        """Categorizer for regular, unreversed fields. Just uses the
        fieldcache to get the keys.
        """

        def __init__(self, fieldname):
            self.fieldname = fieldname

        def set_searcher(self, searcher, docoffset):
            self.fieldcache = searcher.reader().fieldcache(self.fieldname)

        def key_for_id(self, docid):
            return self.fieldcache.key_for(docid)

        def key_to_name(self, key):
            if key == u('\uFFFF'):
                return None
            else:
                return key

    class NumericFieldCategorizer(Categorizer):
        """Categorizer for numeric fields, which are naturally reversible.
        """

        def __init__(self, fieldname, reverse):
            self.fieldname = fieldname
            self.reverse = reverse

        def set_searcher(self, searcher, docoffset):
            self.default = searcher.schema[self.fieldname].sortable_default()
            self.fieldcache = searcher.reader().fieldcache(self.fieldname)

        def key_for_id(self, docid):
            value = self.fieldcache.key_for(docid)
            if self.reverse:
                return 0 - value
            else:
                return value

        def key_to_name(self, key):
            if key == self.default:
                return None
            else:
                return key

    class DateFieldCategorizer(NumericFieldCategorizer):
        """Categorizer for date fields. Same as NumericFieldCategorizer, but
        converts the numeric keys back to dates for better labels.
        """

        def key_to_name(self, key):
            if key == DEFAULT_LONG:
                return None
            else:
                return long_to_datetime(key)

    class NoCacheFieldCategorizer(Categorizer):
        """This object builds an array caching the order of all documents
        according to the field, then uses the cached order as a numeric key.
        This is useful when a field cache is not available, and also for
        reversed fields (since field cache keys for non- numeric fields are
        arbitrary data, it's not possible to "negate" them to reverse the sort
        order).
        """

        def __init__(self, searcher, fieldname, reverse):
            # Cache the relative positions of all docs with the given field
            # across the entire index
            reader = searcher.reader()
            dc = reader.doc_count_all()
            arry = array("i", [dc + 1] * dc)
            field = searcher.schema[fieldname]
            values = field.sortable_values(reader, fieldname)
            for i, (t, _) in enumerate(values):
                if reverse:
                    i = dc - i
                postings = reader.postings(fieldname, t)
                for docid in postings.all_ids():
                    arry[docid] = i
            self.array = arry

        def set_searcher(self, searcher, docoffset):
            self.docoffset = docoffset

        def key_for_id(self, docid):
            return self.array[docid + self.docoffset]

    class OverlappingFieldCategorizer(Categorizer):
        allow_overlap = True

        def __init__(self, fieldname):
            self.fieldname = fieldname
            self.use_vectors = False

        def set_searcher(self, searcher, docoffset):
            fieldname = self.fieldname
            dc = searcher.doc_count_all()
            field = searcher.schema[fieldname]
            reader = searcher.reader()

            if field.vector:
                # If the field was indexed with term vectors, use the vectors
                # to get the list of values in each matched document
                self.use_vectors = True
                self.searcher = searcher
            else:
                # Otherwise, cache the values in each document in a huge list
                # of lists
                self.use_vectors = False
                self.lists = [[] for _ in xrange(dc)]
                for t, _ in field.sortable_values(reader, fieldname):
                    postings = reader.postings(fieldname, t)
                    for docid in postings.all_ids():
                        self.lists[docid].append(t)

        def keys_for_id(self, docid):
            if self.use_vectors:
                try:
                    v = self.searcher.vector(docid, self.fieldname)
                    return list(v.all_ids())
                except KeyError:
                    return None
            else:
                return self.lists[docid] or None

        def key_for_id(self, docid):
            if self.use_vectors:
                try:
                    v = self.searcher.vector(docid, self.fieldname)
                    return v.id()
                except KeyError:
                    return None
            else:
                ls = self.lists[docid]
                if ls:
                    return ls[0]
                else:
                    return None


class QueryFacet(FacetType):
    """Sorts/facets based on the results of a series of queries.
    """

    def __init__(self, querydict, other=None, allow_overlap=False):
        """
        :param querydict: a dictionary mapping keys to
            :class:`whoosh.query.Query` objects.
        :param other: the key to use for documents that don't match any of the
            queries.
        """

        self.querydict = querydict
        self.other = other

    def categorizer(self, searcher):
        return self.QueryCategorizer(self.querydict, self.other)

    class QueryCategorizer(Categorizer):
        def __init__(self, querydict, other, allow_overlap=False):
            self.querydict = querydict
            self.other = other
            self.allow_overlap = allow_overlap

        def set_searcher(self, searcher, offset):
            self.docsets = {}
            for qname, q in self.querydict.items():
                docset = set(q.docs(searcher))
                if docset:
                    self.docsets[qname] = docset
            self.offset = offset

        def key_for_id(self, docid):
            for qname in self.docsets:
                if docid in self.docsets[qname]:
                    return qname
            return self.other

        def keys_for_id(self, docid):
            found = False
            for qname in self.docsets:
                if docid in self.docsets[qname]:
                    yield qname
                    found = True
            if not found:
                yield None


class RangeFacet(QueryFacet):
    """Sorts/facets based on numeric ranges. For textual ranges, use
    :class:`QueryFacet`.
    
    For example, to facet the "price" field into $100 buckets, up to $1000::
    
        prices = RangeFacet("price", 0, 1000, 100)
        results = searcher.search(myquery, groupedby=prices)
        
    The ranges/buckets are always **inclusive** at the start and **exclusive**
    at the end.
    """

    def __init__(self, fieldname, start, end, gap, hardend=False):
        """
        :param fieldname: the numeric field to sort/facet on.
        :param start: the start of the entire range.
        :param end: the end of the entire range.
        :param gap: the size of each "bucket" in the range. This can be a
            sequence of sizes. For example, ``gap=[1,5,10]`` will use 1 as the
            size of the first bucket, 5 as the size of the second bucket, and
            10 as the size of all subsequent buckets.
        :param hardend: if True, the end of the last bucket is clamped to the
            value of ``end``. If False (the default), the last bucket is always
            ``gap`` sized, even if that means the end of the last bucket is
            after ``end``.
        """

        self.fieldname = fieldname
        self.start = start
        self.end = end
        self.gap = gap
        self.hardend = hardend
        self._queries()

    def _rangetype(self):
        from whoosh import query

        return query.NumericRange

    def _range_name(self, startval, endval):
        return (startval, endval)

    def _queries(self):
        if not self.gap:
            raise Exception("No gap secified (%r)" % self.gap)
        if isinstance(self.gap, (list, tuple)):
            gaps = self.gap
            gapindex = 0
        else:
            gaps = [self.gap]
            gapindex = -1

        rangetype = self._rangetype()
        self.querydict = {}
        cstart = self.start
        while cstart < self.end:
            thisgap = gaps[gapindex]
            if gapindex >= 0:
                gapindex += 1
                if gapindex == len(gaps):
                    gapindex = -1

            cend = cstart + thisgap
            if self.hardend:
                cend = min(self.end, cend)

            rangename = self._range_name(cstart, cend)
            q = rangetype(self.fieldname, cstart, cend, endexcl=True)
            self.querydict[rangename] = q

            cstart = cend

    def categorizer(self, searcher):
        return QueryFacet(self.querydict).categorizer(searcher)


class DateRangeFacet(RangeFacet):
    """Sorts/facets based on date ranges. This is the same as RangeFacet
    except you are expected to use ``daterange`` objects as the start and end
    of the range, and ``timedelta`` or ``relativedelta`` objects as the gap(s),
    and it generates :class:`~whoosh.query.DateRange` queries instead of
    :class:`~whoosh.query.TermRange` queries.
    
    For example, to facet a "birthday" range into 5 year buckets::
    
        from datetime import datetime
        from whoosh.support.relativedelta import relativedelta
        
        startdate = datetime(1920, 0, 0)
        enddate = datetime.now()
        gap = relativedelta(years=5)
        bdays = RangeFacet("birthday", startdate, enddate, gap)
        results = searcher.search(myquery, groupedby=bdays)
        
    The ranges/buckets are always **inclusive** at the start and **exclusive**
    at the end.
    """

    def _rangetype(self):
        from whoosh import query

        return query.DateRange


class ScoreFacet(FacetType):
    """Uses a document's score as a sorting criterion.
    
    For example, to sort by the ``tag`` field, and then within that by relative
    score::
    
        tag_score = MultiFacet(["tag", ScoreFacet()])
        results = searcher.search(myquery, sortedby=tag_score)
    """

    def categorizer(self, searcher):
        return self.ScoreCategorizer(searcher)

    class ScoreCategorizer(Categorizer):
        requires_matcher = True

        def __init__(self, searcher):
            w = searcher.weighting
            self.use_final = w.use_final
            if w.use_final:
                self.final = w.final

        def set_searcher(self, searcher, offset):
            self.searcher = searcher

        def key_for_matcher(self, matcher):
            score = matcher.score()
            if self.use_final:
                score = self.final(self.searcher, matcher.id(), score)
            # Negate the score so higher values sort first
            return 0 - score


class FunctionFacet(FacetType):
    """Lets you pass an arbitrary function that will compute the key. This may
    be easier than subclassing FacetType and Categorizer to set up the desired
    behavior.
    
    The function is called with the arguments ``(searcher, docid)``, where the
    ``searcher`` may be a composite searcher, and the ``docid`` is an absolute
    index document number (not segment-relative).
    
    For example, to use the number of words in the document's "content" field
    as the sorting/faceting key::
    
        fn = lambda s, docid: s.doc_field_length(docid, "content")
        lengths = FunctionFacet(fn)
    """

    def __init__(self, fn):
        self.fn = fn

    def categorizer(self, searcher):
        return self.FunctionCategorizer(searcher, self.fn)

    class FunctionCategorizer(Categorizer):
        def __init__(self, searcher, fn):
            self.searcher = searcher
            self.fn = fn

        def set_searcher(self, searcher, docoffset):
            self.offset = docoffset

        def key_for_id(self, docid):
            return self.fn(self.searcher, docid + self.offset)


class StoredFieldFacet(FacetType):
    """Lets you sort/group using the value in an unindexed, stored field (e.g.
    STORED). This is usually slower than using an indexed field.
    
    For fields where the stored value is a space-separated list of keywords,
    (e.g. ``"tag1 tag2 tag3"``), you can use the ``allow_overlap`` keyword
    argument to allow overlapped faceting on the result of calling the
    ``split()`` method on the field value (or calling a custom split function
    if one is supplied).
    """

    def __init__(self, fieldname, allow_overlap=False, split_fn=None):
        """
        :param fieldname: the name of the stored field.
        :param allow_overlap: if True, when grouping, allow documents to appear
            in multiple groups when they have multiple terms in the field. The
            categorizer uses ``string.split()`` or the custom ``split_fn`` to
            convert the stored value into a list of facet values.
        :param split_fn: a custom function to split a stored field value into
            facet values. If not supplied, the categorizer simply calls the
            value's ``split()`` method.
        """

        self.fieldname = fieldname
        self.allow_overlap = allow_overlap
        self.split_fn = None

    def categorizer(self, searcher):
        return self.StoredFieldCategorizer(self.fieldname, self.allow_overlap,
                                           self.split_fn)

    class StoredFieldCategorizer(Categorizer):
        def __init__(self, fieldname, allow_overlap, split_fn):
            self.fieldname = fieldname
            self.allow_overlap = allow_overlap
            self.split_fn = split_fn

        def set_searcher(self, searcher, docoffset):
            self.searcher = searcher

        def keys_for_id(self, docid):
            value = self.searcher.stored_fields(docid).get(self.fieldname)
            if self.split_fn:
                return self.split_fn(value)
            else:
                return value.split()

        def key_for_id(self, docid):
            fields = self.searcher.stored_fields(docid)
            return fields.get(self.fieldname)


class MultiFacet(FacetType):
    """Sorts/facets by the combination of multiple "sub-facets".
    
    For example, to sort by the value of the "tag" field, and then (for
    documents where the tag is the same) by the value of the "path" field::
    
        facet = MultiFacet(FieldFacet("tag"), FieldFacet("path")
        results = searcher.search(myquery, sortedby=facet)
        
    As a shortcut, you can use strings to refer to field names, and they will
    be assumed to be field names and turned into FieldFacet objects::
    
        facet = MultiFacet("tag", "path")
        
    You can also use the ``add_*`` methods to add criteria to the multifacet::
    
        facet = MultiFacet()
        facet.add_field("tag")
        facet.add_field("path", reverse=True)
        facet.add_query({"a-m": TermRange("name", "a", "m"),
                         "n-z": TermRange("name", "n", "z")})
    """

    def __init__(self, items=None):
        self.facets = []
        if items:
            for item in items:
                self._add(item)

    @classmethod
    def from_sortedby(cls, sortedby):
        multi = cls()
        if (isinstance(sortedby, (list, tuple))
            or hasattr(sortedby, "__iter__")):
            for item in sortedby:
                multi._add(item)
        else:
            multi._add(sortedby)
        return multi

    def _add(self, item):
        if isinstance(item, FacetType):
            self.add_facet(item)
        elif isinstance(item, string_type):
            self.add_field(item)
        else:
            raise Exception("Don't know what to do with facet %r" % (item,))

    def add_field(self, fieldname, reverse=False):
        self.facets.append(FieldFacet(fieldname, reverse=reverse))
        return self

    def add_query(self, querydict, other=None, allow_overlap=False):
        self.facets.append(QueryFacet(querydict, other=other,
                                      allow_overlap=allow_overlap))
        return self

    def add_score(self):
        self.facets.append(ScoreFacet())
        return self

    def add_facet(self, facet):
        if not isinstance(facet, FacetType):
            raise Exception()
        self.facets.append(facet)
        return self

    def categorizer(self, searcher):
        if not self.facets:
            raise Exception("No facets")
        elif len(self.facets) == 1:
            catter = self.facets[0].categorizer(searcher)
        else:
            catter = self.MultiCategorizer([facet.categorizer(searcher)
                                            for facet in self.facets])
        return catter

    class MultiCategorizer(Categorizer):
        def __init__(self, catters):
            self.catters = catters

        @property
        def requires_matcher(self):
            return any(c.requires_matcher for c in self.catters)

        def set_searcher(self, searcher, docoffset):
            for catter in self.catters:
                catter.set_searcher(searcher, docoffset)

        def key_for_matcher(self, matcher):
            return tuple(catter.key_for_matcher(matcher)
                         for catter in self.catters)

        def key_for_id(self, docid):
            return tuple(catter.key_for_id(docid) for catter in self.catters)


class Facets(object):
    """Maps facet names to :class:`FacetType` objects, for creating multiple
    groupings of documents.
    
    For example, to group by tag, and **also** group by price range::
    
        facets = Facets()
        facets.add_field("tag")
        facets.add_facet("price", RangeFacet("price", 0, 1000, 100))
        results = searcher.search(myquery, groupedby=facets)
        
        tag_groups = results.groups("tag")
        price_groups = results.groups("price")
    
    (To group by the combination of multiple facets, use :class:`MultiFacet`.)
    """

    def __init__(self, x=None):
        self.facets = {}
        if x:
            self.add_facets(x)

    @classmethod
    def from_groupedby(cls, groupedby):
        facets = cls()
        if isinstance(groupedby, (cls, dict)):
            facets.add_facets(groupedby)
        elif isinstance(groupedby, string_type):
            facets.add_field(groupedby)
        elif isinstance(groupedby, FacetType):
            facets.add_facet("facet", groupedby)
        elif isinstance(groupedby, (list, tuple)):
            for item in groupedby:
                facets.add_facets(cls.from_groupedby(item))
        else:
            raise Exception("Don't know what to do with groupedby=%r"
                            % groupedby)

        return facets

    def items(self):
        """Returns a list of (facetname, facetobject) tuples for the facets in
        this object.
        """

        return self.facets.items()

    def add_field(self, fieldname, allow_overlap=False):
        """Adds a :class:`FieldFacet` for the given field name (the field name
        is automatically used as the facet name).
        """

        self.facets[fieldname] = FieldFacet(fieldname,
                                            allow_overlap=allow_overlap)
        return self

    def add_query(self, name, querydict, other=None, allow_overlap=False):
        """Adds a :class:`QueryFacet` under the given ``name``.
        
        :param name: a name for the facet.
        :param querydict: a dictionary mapping keys to
            :class:`whoosh.query.Query` objects.
        """

        self.facets[name] = QueryFacet(querydict, other=other,
                                       allow_overlap=allow_overlap)
        return self

    def add_facet(self, name, facet):
        """Adds a :class:`FacetType` object under the given ``name``.
        """

        if not isinstance(facet, FacetType):
            raise Exception("%r:%r is not a facet" % (name, facet))
        self.facets[name] = facet
        return self

    def add_facets(self, facets, replace=True):
        """Adds the contents of the given ``Facets`` or ``dict`` object to this
        object.
        """

        if not isinstance(facets, (dict, Facets)):
            raise Exception("%r is not a Facets object or dict" % facets)
        for name, facet in facets.items():
            if replace or name not in self.facets:
                self.facets[name] = facet
        return self


#
#
#
#
# Legacy sorting object

class Sorter(object):
    """This is a legacy interface. The functionality of the Sorter object was
    moved into the :class:`FacetType` classes and the
    :class:`whoosh.searching.Collector` in Whoosh 2.0. The old Sorter API is
    still supported for backwards-compatibility, but it simply forwards to the
    new API.
    
    See :doc:`/facets` for information on the new API.
    """

    def __init__(self, searcher):
        self.searcher = searcher
        self.multi = MultiFacet()

    def add_field(self, fieldname, reverse=False):
        self.multi.add_field(fieldname, reverse=reverse)

    def sort_query(self, q, limit=None, reverse=False, filter=None, mask=None,
                   groupedby=None):
        from whoosh.searching import Collector

        collector = Collector(limit=limit, groupedby=groupedby)
        return collector.sort(self.searcher, q, self.multi, reverse=reverse,
                              allow=filter, restrict=mask)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.