whoosh / src / whoosh / collectors.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
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
# Copyright 2012 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.

"""
This module contains "collector" objects. Collectors provide a way to gather
"raw" results from a :class:`whoosh.matching.Matcher` object, implement
sorting, filtering, collation, etc., and produce a
:class:`whoosh.searching.Results` object.

The basic collectors are:

TopCollector
    Returns the top N matching results sorted by score, using block-quality
    optimizations to skip blocks of documents that can't contribute to the top
    N. The :meth:`whoosh.searching.Searcher.search` method uses this type of
    collector by default or when you specify a ``limit``.

UnlimitedCollector
    Returns all matching results sorted by score. The
    :meth:`whoosh.searching.Searcher.search` method uses this type of collector
    when you specify ``limit=None`` or you specify a limit equal to or greater
    than the number of documents in the searcher.

SortingCollector
    Returns all matching results sorted by a :class:`whoosh.sorting.Facet`
    object. The :meth:`whoosh.searching.Searcher.search` method uses this type
    of collector when you use the ``sortedby`` parameter.

Here's an example of a simple collector that instead of remembering the matched
documents just counts up the number of matches::

    class CountingCollector(Collector):
        def prepare(self, top_searcher, q, context):
            # Always call super method in prepare
            Collector.prepare(self, top_searcher, q, context)

            self.count = 0

        def collect(self, sub_docnum):
            self.count += 1

    c = CountingCollector()
    mysearcher.search_with_collector(myquery, c)
    print(c.count)

There are also several wrapping collectors that extend or modify the
functionality of other collectors. The meth:`whoosh.searching.Searcher.search`
method uses many of these when you specify various parameters.

NOTE: collectors are not designed to be reentrant or thread-safe. It is
generally a good idea to create a new collector for each search.
"""

import os
import threading
from array import array
from bisect import insort
from collections import defaultdict
from heapq import heapify, heappush, heapreplace

from whoosh import sorting
from whoosh.compat import abstractmethod, iteritems, itervalues, xrange
from whoosh.searching import Results, TimeLimit
from whoosh.util import now


# Functions

def ilen(iterator):
    total = 0
    for _ in iterator:
        total += 1
    return total


# Base class

class Collector(object):
    """Base class for collectors.
    """

    def prepare(self, top_searcher, q, context):
        """This method is called before a search.

        Subclasses can override this to perform set-up work, but
        they should still call the superclass's method because it sets several
        necessary attributes on the collector object:

        self.top_searcher
            The top-level searcher.
        self.q
            The query object
        self.context
            ``context.needs_current`` controls whether a wrapping collector
            requires that this collector's matcher be in a valid state at every
            call to ``collect()``. If this is ``False``, the collector is free
            to use faster methods that don't necessarily keep the matcher
            updated, such as ``matcher.all_ids()``.

        :param top_searcher: the top-level :class:`whoosh.searching.Searcher`
            object.
        :param q: the :class:`whoosh.query.Query` object being searched for.
        :param context: a :class:`whoosh.searching.SearchContext` object
            containing information about the search.
        """

        self.top_searcher = top_searcher
        self.q = q
        self.context = context

        self.starttime = now()
        self.runtime = None
        self.docset = set()

    def run(self):
        # Collect matches for each sub-searcher
        try:
            for subsearcher, offset in self.top_searcher.leaf_searchers():
                self.set_subsearcher(subsearcher, offset)
                self.collect_matches()
        finally:
            self.finish()

    def set_subsearcher(self, subsearcher, offset):
        """This method is called each time the collector starts on a new
        sub-searcher.

        Subclasses can override this to perform set-up work, but
        they should still call the superclass's method because it sets several
        necessary attributes on the collector object:

        self.subsearcher
            The current sub-searcher. If the top-level searcher is atomic, this
            is the same as the top-level searcher.
        self.offset
            The document number offset of the current searcher. You must add
            this number to the document number passed to
            :meth:`Collector.collect` to get the top-level document number
            for use in results.
        self.matcher
            A :class:`whoosh.matching.Matcher` object representing the matches
            for the query in the current sub-searcher.
        """

        self.subsearcher = subsearcher
        self.offset = offset
        self.matcher = self.q.matcher(subsearcher, self.context)

    def computes_count(self):
        """Returns True if the collector naturally computes the exact number of
        matching documents. Collectors that use block optimizations will return
        False since they might skip blocks containing matching documents.

        Note that if this method returns False you can still call :meth:`count`,
        but it means that method might have to do more work to calculate the
        number of matching documents.
        """

        return True

    def all_ids(self):
        """Returns a sequence of docnums matched in this collector. (Only valid
        after the collector is run.)

        The default implementation is based on the docset. If a collector does
        not maintain the docset, it will need to override this method.
        """

        return self.docset

    def count(self):
        """Returns the total number of documents matched in this collector.
        (Only valid after the collector is run.)

        The default implementation is based on the docset. If a collector does
        not maintain the docset, it will need to override this method.
        """

        return len(self.docset)

    def collect_matches(self):
        """This method calls :meth:`Collector.matches` and then for each
        matched document calls :meth:`Collector.collect`. Sub-classes that
        want to intervene between finding matches and adding them to the
        collection (for example, to filter out certain documents) can override
        this method.
        """

        collect = self.collect
        for sub_docnum in self.matches():
            collect(sub_docnum)

    @abstractmethod
    def collect(self, sub_docnum):
        """This method is called for every matched document. It should do the
        work of adding a matched document to the results, and it should return
        an object to use as a "sorting key" for the given document (such as the
        document's score, a key generated by a facet, or just None). Subclasses
        must implement this method.

        If you want the score for the current document, use
        ``self.matcher.score()``.

        Overriding methods should add the current document offset
        (``self.offset``) to the ``sub_docnum`` to get the top-level document
        number for the matching document to add to results.

        :param sub_docnum: the document number of the current match within the
            current sub-searcher. You must add ``self.offset`` to this number
            to get the document's top-level document number.
        """

        raise NotImplementedError

    @abstractmethod
    def sort_key(self, sub_docnum):
        """Returns a sorting key for the current match. This should return the
        same value returned by :meth:`Collector.collect`, but without the side
        effect of adding the current document to the results.

        If the collector has been prepared with ``context.needs_current=True``,
        this method can use ``self.matcher`` to get information, for example
        the score. Otherwise, it should only use the provided ``sub_docnum``,
        since the matcher may be in an inconsistent state.

        Subclasses must implement this method.
        """

        raise NotImplementedError

    def remove(self, global_docnum):
        """Removes a document from the collector. Not that this method uses the
        global document number as opposed to :meth:`Collector.collect` which
        takes a segment-relative docnum.
        """

        items = self.items
        for i in xrange(len(items)):
            if items[i][1] == global_docnum:
                items.pop(i)
                return
        raise KeyError(global_docnum)

    def _step_through_matches(self):
        matcher = self.matcher
        while matcher.is_active():
            yield matcher.id()
            matcher.next()

    def matches(self):
        """Yields a series of relative document numbers for matches
        in the current subsearcher.
        """

        # We jump through a lot of hoops to avoid stepping through the matcher
        # "manually" if we can because all_ids() is MUCH faster
        if self.context.needs_current:
            return self._step_through_matches()
        else:
            return self.matcher.all_ids()

    def finish(self):
        """This method is called after a search.

        Subclasses can override this to perform set-up work, but
        they should still call the superclass's method because it sets several
        necessary attributes on the collector object:

        self.runtime
            The time (in seconds) the search took.
        """

        self.runtime = now() - self.starttime

    def _results(self, items, **kwargs):
        # Fills in a Results object with the invariant information and the
        # given "items" (a list of (score, docnum) tuples)
        r = Results(self.top_searcher, self.q, items, **kwargs)
        r.runtime = self.runtime
        r.collector = self
        return r

    @abstractmethod
    def results(self):
        """Returns a :class:`~whoosh.searching.Results` object containing the
        results of the search. Subclasses must implement this method
        """

        raise NotImplementedError


# Scored collectors

class ScoredCollector(Collector):
    """Base class for collectors that sort the results based on document score.
    """

    def __init__(self, replace=10):
        """
        :param replace: Number of matches between attempts to replace the
            matcher with a more efficient version.
        """

        Collector.__init__(self)
        self.replace = replace

    def prepare(self, top_searcher, q, context):
        # This collector requires a valid matcher at each step
        Collector.prepare(self, top_searcher, q, context)

        if top_searcher.weighting.use_final:
            self.final_fn = top_searcher.weighting.final
        else:
            self.final_fn = None

        # Heap containing top N (score, 0-docnum) pairs
        self.items = []
        # Minimum score a document must have to make it into the top N. This is
        # used by the block-quality optimizations
        self.minscore = 0
        # Number of times the matcher was replaced (for debugging)
        self.replaced_times = 0
        # Number of blocks skipped by quality optimizations (for debugging)
        self.skipped_times = 0

    def sort_key(self, sub_docnum):
        return 0 - self.matcher.score()

    def _collect(self, global_docnum, score):
        # Concrete subclasses should override this method to collect matching
        # documents

        raise NotImplementedError

    def _use_block_quality(self):
        # Concrete subclasses should override this method to return True if the
        # collector should use block quality optimizations

        return False

    def collect(self, sub_docnum):
        # Do common work to calculate score and top-level document number
        global_docnum = self.offset + sub_docnum

        score = self.matcher.score()
        if self.final_fn:
            score = self.final_fn(self.top_searcher, global_docnum, score)

        # Call specialized method on subclass
        return self._collect(global_docnum, score)

    def matches(self):
        minscore = self.minscore
        matcher = self.matcher
        usequality = self._use_block_quality()
        replace = self.replace
        replacecounter = 0

        # A flag to indicate whether we should check block quality at the start
        # of the next loop
        checkquality = True

        while matcher.is_active():
            # If the replacement counter has reached 0, try replacing the
            # matcher with a more efficient version
            if replace:
                if replacecounter == 0 or self.minscore != minscore:
                    self.matcher = matcher = matcher.replace(minscore or 0)
                    self.replaced_times += 1
                    if not matcher.is_active():
                        break
                    usequality = self._use_block_quality()
                    replacecounter = self.replace

                    if self.minscore != minscore:
                        checkquality = True
                        minscore = self.minscore

                replacecounter -= 1

            # If we're using block quality optimizations, and the checkquality
            # flag is true, try to skip ahead to the next block with the
            # minimum required quality
            if usequality and checkquality and minscore is not None:
                self.skipped_times += matcher.skip_to_quality(minscore)
                # Skipping ahead might have moved the matcher to the end of the
                # posting list
                if not matcher.is_active():
                    break

            yield matcher.id()

            # Move to the next document. This method returns True if the
            # matcher has entered a new block, so we should check block quality
            # again.
            checkquality = matcher.next()


class TopCollector(ScoredCollector):
    """A collector that only returns the top "N" scored results.
    """

    def __init__(self, limit=10, usequality=True, **kwargs):
        """
        :param limit: the maximum number of results to return.
        :param usequality: whether to use block-quality optimizations. This may
            be useful for debugging.
        """

        ScoredCollector.__init__(self, **kwargs)
        self.limit = limit
        self.usequality = usequality
        self.total = 0

    def _use_block_quality(self):
        return (self.usequality
                and not self.top_searcher.weighting.use_final
                and self.matcher.supports_block_quality())

    def computes_count(self):
        return not self._use_block_quality()

    def all_ids(self):
        # Since this collector can skip blocks, it doesn't track the total
        # number of matching documents, so if the user asks for all matched
        # docs we need to re-run the search using docs_for_query

        return self.top_searcher.docs_for_query(self.q)

    def count(self):
        if self.computes_count():
            return self.total
        else:
            return ilen(self.all_ids())

    # ScoredCollector.collect calls this
    def _collect(self, global_docnum, score):
        items = self.items
        self.total += 1

        # Document numbers are negated before putting them in the heap so that
        # higher document numbers have lower "priority" in the queue. Lower
        # document numbers should always come before higher document numbers
        # with the same score to keep the order stable.
        if len(items) < self.limit:
            # The heap isn't full, so add this document
            heappush(items, (score, 0 - global_docnum))
            # Negate score to act as sort key so higher scores appear first
            return 0 - score
        elif score > items[0][0]:
            # The heap is full, but if this document has a high enough
            # score to make the top N, add it to the heap
            heapreplace(items, (score, 0 - global_docnum))
            self.minscore = items[0][0]
            # Negate score to act as sort key so higher scores appear first
            return 0 - score
        else:
            return 0

    def remove(self, global_docnum):
        negated = 0 - global_docnum
        items = self.items

        # Remove the document if it's on the list (it may not be since
        # TopCollector forgets documents that don't make the top N list)
        for i in xrange(len(items)):
            if items[i][1] == negated:
                items.pop(i)
                # Restore the heap invariant
                heapify(items)
                self.minscore = items[0][0] if items else 0
                return

    def results(self):
        # The items are stored (postive score, negative docnum) so the heap
        # keeps the highest scores and lowest docnums, in order from lowest to
        # highest. Since for the results we want the highest scores first,
        # sort the heap in reverse order
        items = self.items
        items.sort(reverse=True)
        # De-negate the docnums for presentation to the user
        items = [(score, 0 - docnum) for score, docnum in items]
        return self._results(items)


class UnlimitedCollector(ScoredCollector):
    """A collector that returns **all** scored results.
    """

    def __init__(self, reverse=False):
        ScoredCollector.__init__(self)
        self.reverse = reverse

    # ScoredCollector.collect calls this
    def _collect(self, global_docnum, score):
        self.items.append((score, global_docnum))
        self.docset.add(global_docnum)
        # Negate score to act as sort key so higher scores appear first
        return 0 - score

    def results(self):
        # Sort by negated scores so that higher scores go first, then by
        # document number to keep the order stable when documents have the
        # same score
        self.items.sort(key=lambda x: (0 - x[0], x[1]), reverse=self.reverse)
        return self._results(self.items, docset=self.docset)


# Sorting collector

class SortingCollector(Collector):
    """A collector that returns results sorted by a given
    :class:`whoosh.sorting.Facet` object. See :doc:`/facets` for more
    information.
    """

    def __init__(self, sortedby, limit=10, reverse=False):
        """
        :param sortedby: see :doc:`/facets`.
        :param reverse: If True, reverse the overall results. Note that you
            can reverse individual facets in a multi-facet sort key as well.
        """

        Collector.__init__(self)
        self.sortfacet = sorting.MultiFacet.from_sortedby(sortedby)
        self.limit = limit
        self.reverse = reverse

    def prepare(self, top_searcher, q, context):
        self.categorizer = self.sortfacet.categorizer(top_searcher)
        # If the categorizer requires a valid matcher, then tell the child
        # collector that we need it
        rm = context.needs_current or self.categorizer.needs_current
        Collector.prepare(self, top_searcher, q, context.set(needs_current=rm))

        # List of (sortkey, docnum) pairs
        self.items = []

    def set_subsearcher(self, subsearcher, offset):
        Collector.set_subsearcher(self, subsearcher, offset)
        self.categorizer.set_searcher(subsearcher, offset)

    def sort_key(self, sub_docnum):
        return self.categorizer.key_for(self.matcher, sub_docnum)

    def collect(self, sub_docnum):
        global_docnum = self.offset + sub_docnum
        sortkey = self.sort_key(sub_docnum)
        self.items.append((sortkey, global_docnum))
        self.docset.add(global_docnum)
        return sortkey

    def results(self):
        items = self.items
        items.sort(reverse=self.reverse)
        if self.limit:
            items = items[:self.limit]
        return self._results(items, docset=self.docset)


class UnsortedCollector(Collector):
    def prepare(self, top_searcher, q, context):
        Collector.prepare(self, top_searcher, q,
                          top_searcher.boolean_context())
        self.items = []

    def collect(self, sub_docnum):
        global_docnum = self.offset + sub_docnum
        self.items.append((None, global_docnum))
        self.docset.add(global_docnum)

    def results(self):
        items = self.items
        return self._results(items, docset=self.docset)


# Wrapping collectors

class WrappingCollector(Collector):
    """Base class for collectors that wrap other collectors.
    """

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

    @property
    def top_searcher(self):
        return self.child.top_searcher

    def prepare(self, top_searcher, q, context):
        self.child.prepare(top_searcher, q, context)

    def set_subsearcher(self, subsearcher, offset):
        self.child.set_subsearcher(subsearcher, offset)
        self.subsearcher = subsearcher
        self.matcher = self.child.matcher
        self.offset = self.child.offset

    def all_ids(self):
        return self.child.all_ids()

    def count(self):
        return self.child.count()

    def collect_matches(self):
        for sub_docnum in self.matches():
            self.collect(sub_docnum)

    def sort_key(self, sub_docnum):
        return self.child.sort_key(sub_docnum)

    def collect(self, sub_docnum):
        return self.child.collect(sub_docnum)

    def matches(self):
        return self.child.matches()

    def finish(self):
        self.child.finish()

    def results(self):
        return self.child.results()


# Allow and disallow collector

class FilterCollector(WrappingCollector):
    """A collector that lets you allow and/or restrict certain document numbers
    in the results::

        uc = collectors.UnlimitedCollector()

        ins = query.Term("chapter", "rendering")
        outs = query.Term("status", "restricted")
        fc = FilterCollector(uc, allow=ins, restrict=outs)

        mysearcher.search_with_collector(myquery, fc)
        print(fc.results())

    This collector discards a document if:

    * The allowed set is not None and a document number is not in the set, or
    * The restrict set is not None and a document number is in the set.

    (So, if the same document number is in both sets, that document will be
    discarded.)

    If you have a reference to the collector, you can use
    ``FilterCollector.filtered_count`` to get the number of matching documents
    filtered out of the results by the collector.
    """

    def __init__(self, child, allow=None, restrict=None):
        """
        :param child: the collector to wrap.
        :param allow: a query, Results object, or set-like object containing
            docnument numbers that are allowed in the results, or None (meaning
            everything is allowed).
        :param restrict: a query, Results object, or set-like object containing
            document numbers to disallow from the results, or None (meaning
            nothing is disallowed).
        """

        self.child = child
        self.allow = allow
        self.restrict = restrict

    def prepare(self, top_searcher, q, context):
        self.child.prepare(top_searcher, q, context)

        allow = self.allow
        restrict = self.restrict
        ftc = top_searcher._filter_to_comb

        self._allow = ftc(allow) if allow else None
        self._restrict = ftc(restrict) if restrict else None
        self.filtered_count = 0

    def all_ids(self):
        child = self.child

        _allow = self._allow
        _restrict = self._restrict

        for global_docnum in child.all_ids():
            if ((_allow and global_docnum not in _allow)
                or (_restrict and global_docnum in _restrict)):
                    continue
            yield global_docnum

    def count(self):
        child = self.child
        if child.computes_count():
            return child.count() - self.filtered_count
        else:
            return ilen(self.all_ids())

    def collect_matches(self):
        child = self.child
        _allow = self._allow
        _restrict = self._restrict

        if _allow is not None or _restrict is not None:
            filtered_count = self.filtered_count
            for sub_docnum in child.matches():
                global_docnum = self.offset + sub_docnum
                if ((_allow is not None and global_docnum not in _allow)
                    or (_restrict is not None and global_docnum in _restrict)):
                    filtered_count += 1
                    continue
                child.collect(sub_docnum)
            self.filtered_count = filtered_count
        else:
            # If there was no allow or restrict set, don't do anything special,
            # just forward the call to the child collector
            child.collect_matches()

    def results(self):
        r = self.child.results()
        r.filtered_count = self.filtered_count
        r.allowed = self.allow
        r.restricted = self.restrict
        return r


# Facet grouping collector

class FacetCollector(WrappingCollector):
    """A collector that creates groups of documents based on
    :class:`whoosh.sorting.Facet` objects. See :doc:`/facets` for more
    information.

    This collector is used if you specify a ``groupedby`` parameter in the
    :meth:`whoosh.searching.Searcher.search` method. You can use the
    :meth:`whoosh.searching.Results.groups` method to access the facet groups.

    If you have a reference to the collector can also use
    ``FacetedCollector.facetmaps`` to access the groups directly::

        uc = collectors.UnlimitedCollector()
        fc = FacetedCollector(uc, sorting.FieldFacet("category"))
        mysearcher.search_with_collector(myquery, fc)
        print(fc.facetmaps)
    """

    def __init__(self, child, groupedby, maptype=None):
        """
        :param groupedby: see :doc:`/facets`.
        :param maptype: a :class:`whoosh.sorting.FacetMap` type to use for any
            facets that don't specify their own.
        """

        self.child = child
        self.facets = sorting.Facets.from_groupedby(groupedby)
        self.maptype = maptype

    def prepare(self, top_searcher, q, context):
        facets = self.facets

        # For each facet we're grouping by:
        # - Create a facetmap (to hold the groups)
        # - Create a categorizer (to generate document keys)
        self.facetmaps = {}
        self.categorizers = {}

        # Set needs_current to True if any of the categorizers require the
        # current document to work
        needs_current = context.needs_current
        for facetname, facet in facets.items():
            self.facetmaps[facetname] = facet.map(self.maptype)

            ctr = facet.categorizer(top_searcher)
            self.categorizers[facetname] = ctr
            needs_current = needs_current or ctr.needs_current
        context = context.set(needs_current=needs_current)

        self.child.prepare(top_searcher, q, context)

    def set_subsearcher(self, subsearcher, offset):
        WrappingCollector.set_subsearcher(self, subsearcher, offset)

        # Tell each categorizer about the new subsearcher and offset
        for categorizer in itervalues(self.categorizers):
            categorizer.set_searcher(self.child.subsearcher, self.child.offset)

    def collect(self, sub_docnum):
        matcher = self.child.matcher
        global_docnum = sub_docnum + self.child.offset

        # We want the sort key for the document so we can (by default) sort
        # the facet groups
        sortkey = self.child.collect(sub_docnum)

        # For each facet we're grouping by
        for name, categorizer in iteritems(self.categorizers):
            add = self.facetmaps[name].add

            # We have to do more work if the facet allows overlapping groups
            if categorizer.allow_overlap:
                for key in categorizer.keys_for(matcher, sub_docnum):
                    add(categorizer.key_to_name(key), global_docnum, sortkey)
            else:
                key = categorizer.key_for(matcher, sub_docnum)
                key = categorizer.key_to_name(key)
                add(key, global_docnum, sortkey)

        return sortkey

    def results(self):
        r = self.child.results()
        r._facetmaps = self.facetmaps
        return r


# Collapsing collector

class CollapseCollector(WrappingCollector):
    """A collector that collapses results based on a facet. That is, it
    eliminates all but the top N results that share the same facet key.
    Documents with an empty key for the facet are never eliminated.

    The "top" results within each group is determined by the result ordering
    (e.g. highest score in a scored search) or an optional second "ordering"
    facet.

    If you have a reference to the collector you can use
    ``CollapseCollector.collapsed_counts`` to access the number of documents
    eliminated based on each key::

        tc = TopCollector(limit=20)
        cc = CollapseCollector(tc, "group", limit=3)
        mysearcher.search_with_collector(myquery, cc)
        print(cc.collapsed_counts)

    See :ref:`collapsing` for more information.
    """

    def __init__(self, child, keyfacet, limit=1, order=None):
        """
        :param child: the collector to wrap.
        :param keyfacet: a :class:`whoosh.sorting.Facet` to use for collapsing.
            All but the top N documents that share a key will be eliminated
            from the results.
        :param limit: the maximum number of documents to keep for each key.
        :param order: an optional :class:`whoosh.sorting.Facet` to use
            to determine the "top" document(s) to keep when collapsing. The
            default (``orderfaceet=None``) uses the results order (e.g. the
            highest score in a scored search).
        """

        self.child = child
        self.keyfacet = sorting.MultiFacet.from_sortedby(keyfacet)

        self.limit = limit
        if order:
            self.orderfacet = sorting.MultiFacet.from_sortedby(order)
        else:
            self.orderfacet = None

    def prepare(self, top_searcher, q, context):
        # Categorizer for getting the collapse key of a document
        self.keyer = self.keyfacet.categorizer(top_searcher)
        # Categorizer for getting the collapse order of a document
        self.orderer = None
        if self.orderfacet:
            self.orderer = self.orderfacet.categorizer(top_searcher)

        # Dictionary mapping keys to lists of (sortkey, global_docnum) pairs
        # representing the best docs for that key
        self.lists = defaultdict(list)
        # Dictionary mapping keys to the number of documents that have been
        # filtered out with that key
        self.collapsed_counts = defaultdict(int)
        # Total number of documents filtered out by collapsing
        self.collapsed_total = 0

        # If the keyer or orderer require a valid matcher, tell the child
        # collector we need it
        needs_current = (context.needs_current
                     or self.keyer.needs_current
                     or (self.orderer and self.orderer.needs_current))
        self.child.prepare(top_searcher, q,
                           context.set(needs_current=needs_current))

    def set_subsearcher(self, subsearcher, offset):
        WrappingCollector.set_subsearcher(self, subsearcher, offset)

        # Tell the keyer and (optional) orderer about the new subsearcher
        self.keyer.set_searcher(subsearcher, offset)
        if self.orderer:
            self.orderer.set_searcher(subsearcher, offset)

    def all_ids(self):
        child = self.child
        limit = self.limit
        counters = defaultdict(int)

        for subsearcher, offset in child.subsearchers():
            self.set_subsearcher(subsearcher, offset)
            matcher = child.matcher
            keyer = self.keyer
            for sub_docnum in child.matches():
                ckey = keyer.key_for(matcher, sub_docnum)
                if ckey is not None:
                    if ckey in counters and counters[ckey] >= limit:
                        continue
                    else:
                        counters[ckey] += 1
                yield offset + sub_docnum

    def count(self):
        if self.child.computes_count():
            return self.child.count() - self.collapsed_total
        else:
            return ilen(self.all_ids())

    def collect_matches(self):
        lists = self.lists
        limit = self.limit
        keyer = self.keyer
        orderer = self.orderer
        collapsed_counts = self.collapsed_counts

        child = self.child
        matcher = child.matcher
        offset = child.offset
        for sub_docnum in child.matches():
            # Collapsing category key
            ckey = keyer.key_to_name(keyer.key_for(matcher, sub_docnum))
            if not ckey:
                # If the document isn't in a collapsing category, just add it
                child.collect(sub_docnum)
            else:
                global_docnum = offset + sub_docnum

                if orderer:
                    # If user specified a collapse order, use it
                    sortkey = orderer.key_for(child.matcher, sub_docnum)
                else:
                    # Otherwise, use the results order
                    sortkey = child.sort_key(sub_docnum)

                # Current list of best docs for this collapse key
                best = lists[ckey]
                add = False
                if len(best) < limit:
                    # If the heap is not full yet, just add this document
                    add = True
                elif sortkey < best[-1][0]:
                    # If the heap is full but this document has a lower sort
                    # key than the highest key currently on the heap, replace
                    # the "least-best" document
                    # Tell the child collector to remove the document
                    child.remove(best.pop()[1])
                    add = True

                if add:
                    insort(best, (sortkey, global_docnum))
                    child.collect(sub_docnum)
                else:
                    # Remember that a document was filtered
                    collapsed_counts[ckey] += 1
                    self.collapsed_total += 1

    def results(self):
        r = self.child.results()
        r.collapsed_counts = self.collapsed_counts
        return r


# Time limit collector

class TimeLimitCollector(WrappingCollector):
    """A collector that raises a :class:`TimeLimit` exception if the search
    does not complete within a certain number of seconds::

        uc = collectors.UnlimitedCollector()
        tlc = TimeLimitedCollector(uc, timelimit=5.8)
        try:
            mysearcher.search_with_collector(myquery, tlc)
        except collectors.TimeLimit:
            print("The search ran out of time!")

        # We can still get partial results from the collector
        print(tlc.results())

    IMPORTANT: On Unix systems (systems where signal.SIGALRM is defined), the
    code uses signals to stop searching immediately when the time limit is
    reached. On Windows, the OS does not support this functionality, so the
    search only checks the time between each found document, so if a matcher
    is slow the search could exceed the time limit.
    """

    def __init__(self, child, timelimit, greedy=False, use_alarm=True):
        """
        :param child: the collector to wrap.
        :param timelimit: the maximum amount of time (in seconds) to
            allow for searching. If the search takes longer than this, it will
            raise a ``TimeLimit`` exception.
        :param greedy: if ``True``, the collector will finish adding the most
            recent hit before raising the ``TimeLimit`` exception.
        :param use_alarm: if ``True`` (the default), the collector will try to
            use signal.SIGALRM (on UNIX).
        """
        self.child = child
        self.timelimit = timelimit
        self.greedy = greedy

        if use_alarm:
            import signal
            self.use_alarm = use_alarm and hasattr(signal, "SIGALRM")
        else:
            self.use_alarm = False

        self.timer = None
        self.timedout = False

    def prepare(self, top_searcher, q, context):
        self.child.prepare(top_searcher, q, context)

        self.timedout = False
        if self.use_alarm:
            import signal
            signal.signal(signal.SIGALRM, self._was_signaled)

        # Start a timer thread. If the timer fires, it will call this object's
        # _timestop() method
        self.timer = threading.Timer(self.timelimit, self._timestop)
        self.timer.start()

    def _timestop(self):
        # Called when the timer expires
        self.timer = None
        # Set an attribute that will be noticed in the collect_matches() loop
        self.timedout = True

        if self.use_alarm:
            import signal
            os.kill(os.getpid(), signal.SIGALRM)

    def _was_signaled(self, signum, frame):
        raise TimeLimit

    def collect_matches(self):
        child = self.child
        greedy = self.greedy

        for sub_docnum in child.matches():
            # If the timer fired since the last loop and we're not greedy,
            # raise the exception
            if self.timedout and not greedy:
                raise TimeLimit

            child.collect(sub_docnum)

            # If the timer fired since we entered the loop or it fired earlier
            # but we were greedy, raise now
            if self.timedout:
                raise TimeLimit

    def finish(self):
        if self.timer:
            self.timer.cancel()
        self.timer = None
        self.child.finish()


# Matched terms collector

class TermsCollector(WrappingCollector):
    """A collector that remembers which terms appeared in which terms appeared
    in each matched document.

    This collector is used if you specify ``terms=True`` in the
    :meth:`whoosh.searching.Searcher.search` method.

    If you have a reference to the collector can also use
    ``TermsCollector.termslist`` to access the term lists directly::

        uc = collectors.UnlimitedCollector()
        tc = TermsCollector(uc)
        mysearcher.search_with_collector(myquery, tc)
        # tc.termdocs is a dictionary mapping (fieldname, text) tuples to
        # sets of document numbers
        print(tc.termdocs)
        # tc.docterms is a dictionary mapping docnums to lists of
        # (fieldname, text) tuples
        print(tc.docterms)
    """

    def __init__(self, child, settype=set):
        self.child = child
        self.settype = settype

    def prepare(self, top_searcher, q, context):
        # This collector requires a valid matcher at each step
        self.child.prepare(top_searcher, q, context.set(needs_current=True))

        # A dictionary mapping (fieldname, text) pairs to arrays of docnums
        self.termdocs = defaultdict(lambda: array("I"))
        # A dictionary mapping docnums to lists of (fieldname, text) pairs
        self.docterms = defaultdict(list)

    def set_subsearcher(self, subsearcher, offset):
        WrappingCollector.set_subsearcher(self, subsearcher, offset)

        # Store a list of all the term matchers in the matcher tree
        self.termmatchers = list(self.child.matcher.term_matchers())

    def collect(self, sub_docnum):
        child = self.child
        termdocs = self.termdocs
        docterms = self.docterms

        child.collect(sub_docnum)

        global_docnum = child.offset + sub_docnum
        # For each term matcher...
        for tm in self.termmatchers:
            # If the term matcher is matching the current document...
            if tm.is_active() and tm.id() == sub_docnum:
                # Add it to the list of matching documents for the term
                term = tm.term()
                termdocs[term].append(global_docnum)
                docterms[global_docnum].append(term)

    def results(self):
        r = self.child.results()
        r.termdocs = dict(self.termdocs)
        r.docterms = dict(self.docterms)
        return r
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.