Source

whoosh / src / whoosh / searching.py

Full commit
   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
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
# Copyright 2007 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 classes and functions related to searching the index.
"""


from __future__ import division
import copy
import threading
from collections import defaultdict, deque
from heapq import heappush, heapreplace
from math import ceil

from whoosh import classify, highlight, query, scoring
from whoosh.reading import TermNotFound
from whoosh.support.bitvector import BitSet, BitVector
from whoosh.util import now, lru_cache


class TimeLimit(Exception):
    pass


# Searcher class

class Searcher(object):
    """Wraps an :class:`~whoosh.reading.IndexReader` object and provides
    methods for searching the index.
    """

    def __init__(self, reader, weighting=scoring.BM25F, closereader=True,
                 fromindex=None, parent=None):
        """
        :param reader: An :class:`~whoosh.reading.IndexReader` object for
            the index to search.
        :param weighting: A :class:`whoosh.scoring.Weighting` object to use to
            score found documents.
        :param closereader: Whether the underlying reader will be closed when
            the searcher is closed.
        :param fromindex: An optional reference to the index of the underlying
            reader. This is required for :meth:`Searcher.up_to_date` and
            :meth:`Searcher.refresh` to work.
        """

        self.ixreader = reader
        self.is_closed = False
        self._closereader = closereader
        self._ix = fromindex
        
        if parent:
            self.schema = parent.schema
            self._doccount = parent._doccount
            self._idf_cache = parent._idf_cache
            self._filter_cache = parent._filter_cache
        else:
            self.schema = self.ixreader.schema
            self._doccount = self.ixreader.doc_count_all()
            self._idf_cache = {}
            self._filter_cache = {}

        if type(weighting) is type:
            self.weighting = weighting()
        else:
            self.weighting = weighting

        self.leafreaders = None
        self.subsearchers = None
        if not self.ixreader.is_atomic():
            self.leafreaders = self.ixreader.leaf_readers()
            self.subsearchers = [(self._subsearcher(r), offset) for r, offset
                                 in self.leafreaders]

        # Copy attributes/methods from wrapped reader
        for name in ("stored_fields", "all_stored_fields", "vector", "vector_as",
                     "lexicon", "frequency", "doc_frequency", 
                     "field_length", "doc_field_length", "max_field_length",
                     ):
            setattr(self, name, getattr(self.ixreader, name))

    def __enter__(self):
        return self
    
    def __exit__(self, *exc_info):
        self.close()

    def _subsearcher(self, reader):
        return self.__class__(reader, fromindex=self._ix,
                              weighting=self.weighting, parent=self)

    def is_atomic(self):
        return self.reader().is_atomic()

    def doc_count(self):
        """Returns the number of UNDELETED documents in the index.
        """
        
        return self.ixreader.doc_count()

    def doc_count_all(self):
        """Returns the total number of documents, DELETED OR UNDELETED, in
        the index.
        """
        
        return self._doccount

    def up_to_date(self):
        """Returns True if this Searcher represents the latest version of the
        index, for backends that support versioning.
        """
        
        if not self._ix:
            raise Exception("This searcher was not created with a reference to its index")
        return self._ix.latest_generation() == self.ixreader.generation()

    def refresh(self):
        """Returns a fresh searcher for the latest version of the index::
        
            my_searcher = my_searcher.refresh()
        
        If the index has not changed since this searcher was created, this
        searcher is simply returned.
        
        This method may CLOSE underlying resources that are no longer needed
        by the refreshed searcher, so you CANNOT continue to use the original
        searcher after calling ``refresh()`` on it.
        """
        
        if not self._ix:
            raise Exception("This searcher was not created with a reference to its index")
        if self._ix.latest_generation() == self.reader().generation():
            return self
        
        # Get a new reader, re-using resources from the current reader if
        # possible
        self.is_closed = True
        newreader = self._ix.reader(reuse=self.ixreader)
        return self.__class__(newreader, fromindex=self._ix,
                              weighting=self.weighting)

    def close(self):
        if self._closereader:
            self.ixreader.close()
        self.is_closed = True

    def avg_field_length(self, fieldname, default=None):
        if not self.ixreader.schema[fieldname].scorable:
            return default
        return self.ixreader.field_length(fieldname) / (self._doccount or 1)

    def reader(self):
        """Returns the underlying :class:`~whoosh.reading.IndexReader`.
        """
        return self.ixreader

    def set_caching_policy(self, *args, **kwargs):
        self.ixreader.set_caching_policy(*args, **kwargs)

    def scorer(self, fieldname, text, qf=1):
        if self._doccount:
            scorer = self.weighting.scorer(self, fieldname, text, qf=qf)
        else:
            # Scoring functions tend to cache information that isn't available
            # on an empty index.
            scorer = None
            
        return scorer

    def postings(self, fieldname, text, qf=1):
        """Returns a :class:`whoosh.matching.Matcher` for the postings of the
        given term. Unlike the :func:`whoosh.reading.IndexReader.postings`
        method, this method automatically sets the scoring functions on the
        matcher from the searcher's weighting object.
        """
        
        scorer = self.scorer(fieldname, text, qf=qf)
        return self.ixreader.postings(fieldname, text, scorer=scorer)

    def idf(self, fieldname, text):
        """Calculates the Inverse Document Frequency of the current term (calls
        idf() on the searcher's Weighting object).
        """

        # This method just calls the Weighting object's idf() method, but
        # caches the result. So Weighting objects should call *this* method
        # which will then call *their own* idf() methods.
        
        cache = self._idf_cache
        term = (fieldname, text)
        if term in cache:
            return cache[term]

        idf = self.weighting.idf(self, fieldname, text)
        cache[term] = idf
        return idf

    def document(self, **kw):
        """Convenience method returns the stored fields of a document
        matching the given keyword arguments, where the keyword keys are
        field names and the values are terms that must appear in the field.
        
        This method is equivalent to::
        
            searcher.stored_fields(searcher.document_number(<keyword args>))
        
        Where Searcher.documents() returns a generator, this function returns
        either a dictionary or None. Use it when you assume the given keyword
        arguments either match zero or one documents (i.e. at least one of the
        fields is a unique key).
        
        >>> stored_fields = searcher.document(path=u"/a/b")
        >>> if stored_fields:
        ...   print stored_fields['title']
        ... else:
        ...   print "There is no document with the path /a/b"
        """

        for p in self.documents(**kw):
            return p

    def documents(self, **kw):
        """Convenience method returns the stored fields of a document
        matching the given keyword arguments, where the keyword keys are
        field names and the values are terms that must appear in the field.
        
        Returns a generator of dictionaries containing the
        stored fields of any documents matching the keyword arguments.
        
        >>> for stored_fields in searcher.documents(emailto=u"matt@whoosh.ca"):
        ...   print "Email subject:", stored_fields['subject']
        """

        ixreader = self.ixreader
        return (ixreader.stored_fields(docnum)
                for docnum in self.document_numbers(**kw))

    def _kw_to_text(self, kw):
        for k, v in kw.iteritems():
            field = self.schema[k]
            kw[k] = field.to_text(v)

    def _query_for_kw(self, kw):
        subqueries = []
        for key, value in kw.iteritems():
            subqueries.append(query.Term(key, value))
        return query.And(subqueries).normalize()

    def document_number(self, **kw):
        """Returns the document number of the document matching the given
        keyword arguments, where the keyword keys are field names and the
        values are terms that must appear in the field.
        
        >>> docnum = searcher.document_number(path=u"/a/b")
        
        Where Searcher.document_numbers() returns a generator, this function
        returns either an int or None. Use it when you assume the given keyword
        arguments either match zero or one documents (i.e. at least one of the
        fields is a unique key).
        
        :rtype: int
        """

        # In the common case where only one keyword was given, just use
        # first_id() instead of building a query.
        
        self._kw_to_text(kw)
        if len(kw) == 1:
            k, v = kw.items()[0]
            try:
                return self.reader().first_id(k, v)
            except TermNotFound:
                return None
        else:
            m = self._query_for_kw(kw).matcher(self)
            if m.is_active():
                return m.id()

    def document_numbers(self, **kw):
        """Returns a generator of the document numbers for documents matching
        the given keyword arguments, where the keyword keys are field names and
        the values are terms that must appear in the field.
        
        >>> docnums = list(searcher.document_numbers(emailto=u"matt@whoosh.ca"))
        """

        if len(kw) == 0:
            return []
        
        self._kw_to_text(kw)
        return self.docs_for_query(self._query_for_kw(kw))

    def _find_unique(self, uniques):
        # uniques is a list of ("unique_field_name", "field_value") tuples
        delset = set()
        for name, value in uniques:
            docnum = self.document_number(**{name: value})
            if docnum is not None:
                delset.add(docnum)
        return delset

    @lru_cache(20)
    def _query_to_comb(self, fq):
        return BitSet(self.doc_count_all(), source=self.docs_for_query(fq))

    def _filter_to_comb(self, obj):
        if obj is None:
            return None
        if isinstance(obj, (set, BitVector, BitSet)):
            c = obj
        elif isinstance(obj, Results):
            c = obj.docset
        elif isinstance(obj, ResultsPage):
            c = obj.results.docset
        elif isinstance(obj, query.Query):
            c = self._query_to_comb(obj)
        else:
            raise Exception("Don't know what to do with filter object %r" % obj)
        
        return c
    
    def docs_for_query(self, q, leafs=True):
        if self.subsearchers and leafs:
            for s, offset in self.subsearchers:
                for docnum in q.docs(s):
                    yield docnum + offset
        else:
            for docnum in q.docs(self):
                yield docnum

    def key_terms(self, docnums, fieldname, numterms=5,
                  model=classify.Bo1Model, normalize=True):
        """Returns the 'numterms' most important terms from the documents
        listed (by number) in 'docnums'. You can get document numbers for the
        documents your interested in with the document_number() and
        document_numbers() methods.
        
        "Most important" is generally defined as terms that occur frequently in
        the top hits but relatively infrequently in the collection as a whole.
        
        >>> docnum = searcher.document_number(path=u"/a/b")
        >>> keywords_and_scores = searcher.key_terms([docnum], "content")
        
        This method returns a list of ("term", score) tuples. The score may be
        useful if you want to know the "strength" of the key terms, however to
        just get the terms themselves you can just do this:
        
        >>> kws = [kw for kw, score in searcher.key_terms([docnum], "content")]
        
        :param fieldname: Look at the terms in this field. This field must
            store vectors.
        :param docnums: A sequence of document numbers specifying which
            documents to extract key terms from.
        :param numterms: Return this number of important terms.
        :param model: The classify.ExpansionModel to use. See the classify
            module.
        :param normalize: normalize the scores.
        :returns: a list of ("term", score) tuples.
        """

        expander = classify.Expander(self.ixreader, fieldname, model=model)
        for docnum in docnums:
            expander.add_document(docnum)
        return expander.expanded_terms(numterms, normalize=normalize)

    def key_terms_from_text(self, fieldname, text, numterms=5,
                            model=classify.Bo1Model, normalize=True):
        """Return the 'numterms' most important terms from the given text.
        
        :param numterms: Return this number of important terms.
        :param model: The classify.ExpansionModel to use. See the classify
            module.
        """
        
        expander = classify.Expander(self.ixreader, fieldname, model=model)
        expander.add_text(text)
        return expander.expanded_terms(numterms, normalize=normalize)

    def more_like(self, docnum, fieldname, text=None, top=10, numterms=5,
                  model=classify.Bo1Model, normalize=False):
        """Returns a :class:`Results` object containing documents similar to
        the given document, based on "key terms" in the given field::
        
            # Get the ID for the document you're interested in
            docnum = search.document_number(path=u"/a/b/c")
            
            r = searcher.more_like(docnum)
        
            print "Documents like", searcher.stored_fields(docnum)["title"]
            for hit in r:
                print hit["title"]
        
        :param fieldname: the name of the field to use to test similarity.
        :param text: by default, the method will attempt to load the contents
            of the field from the stored fields for the document, or from a
            term vector. If the field isn't stored or vectored in the index,
            but you have access to the text another way (for example, loading
            from a file or a database), you can supply it using the ``text``
            parameter.
        :param top: the number of results to return.
        :param numterms: the number of "key terms" to extract from the hit and
            search for. Using more terms is slower but gives potentially more
            and more accurate results.
        :param model: (expert) a :class:`whoosh.classify.ExpansionModel` to use
            to compute "key terms".
        :param normalize: whether to normalize term weights.
        """
        
        if text:
            kts = self.key_terms_from_text(fieldname, text, numterms=numterms,
                                           model=model, normalize=normalize)
        else:
            kts = self.key_terms([docnum], fieldname, numterms=numterms,
                                 model=model, normalize=normalize)
        # Create an Or query from the key terms
        q = query.Or([query.Term(fieldname, word, boost=weight)
                      for word, weight in kts])
        
        # Filter the original document out of the results using a bit vector
        # with every bit set except the one for this document
        size = self.doc_count_all()
        comb = BitVector(size, [n for n in xrange(self.doc_count_all())
                                if n != docnum])
        return self.search(q, limit=top, filter=comb)

    def search_page(self, query, pagenum, pagelen=10, **kwargs):
        """This method is Like the :meth:`Searcher.search` method, but returns
        a :class:`ResultsPage` object. This is a convenience function for
        getting a certain "page" of the results for the given query, which is
        often useful in web search interfaces.
        
        For example::
        
            querystring = request.get("q")
            query = queryparser.parse("content", querystring)
            
            pagenum = int(request.get("page", 1))
            pagelen = int(request.get("perpage", 10))
            
            results = searcher.search_page(query, pagenum, pagelen=pagelen)
            print "Page %d of %d" % (results.pagenum, results.pagecount)
            print ("Showing results %d-%d of %d" 
                   % (results.offset + 1, results.offset + results.pagelen + 1,
                      len(results)))
            for hit in results:
                print "%d: %s" % (hit.rank + 1, hit["title"])
        
        (Note that results.pagelen might be less than the pagelen argument if
        there aren't enough results to fill a page.)
        
        Any additional keyword arguments you supply are passed through to
        :meth:`Searcher.search`. For example, you can get paged results of a
        sorted search::
        
            results = searcher.search_page(q, 2, sortedby="date", reverse=True)
        
        Currently, searching for page 100 with pagelen of 10 takes the same
        amount of time as using :meth:`Searcher.search` to find the first 1000
        results. That is, this method does not have any special optimizations
        or efficiencies for getting a page from the middle of the full results
        list. (A future enhancement may allow using previous page results to
        improve the efficiency of finding the next page.)
        
        This method will raise a ``ValueError`` if you ask for a page number
        higher than the number of pages in the resulting query.
        
        :param query: the :class:`whoosh.query.Query` object to match.
        :param pagenum: the page number to retrieve, starting at ``1`` for the
            first page.
        :param pagelen: the number of results per page.
        :returns: :class:`ResultsPage`
        """
        
        if pagenum < 1:
            raise ValueError("pagenum must be >= 1")
        
        # Turn off optimized to prevent items from jumping around in the order
        # as the limit is increased (optimized results are not stable)
        if "optimized" in kwargs:
            del kwargs["optimized"]
        results = self.search(query, limit=pagenum * pagelen, optimize=False,
                              **kwargs)
        return ResultsPage(results, pagenum, pagelen)

    def find(self, defaultfield, querystring, **kwargs):
        from whoosh.qparser import QueryParser
        qp = QueryParser(defaultfield, schema=self.ixreader.schema)
        q = qp.parse(querystring)
        return self.search(q, **kwargs)

    def sorter(self, *args, **kwargs):
        """Returns a :class:`whoosh.sorting.Sorter` object for this searcher.
        See the documentation for ``Sorter`` for how to use the sorter object
        to get sorted search results.
        """
        
        from whoosh.sorting import Sorter
        
        return Sorter(self, *args, **kwargs)

    def sort_query_using(self, q, fn, filter=None):
        """Returns a :class:`Results` object with the documents matching the
        given query ordered according score returned by the given function.
        
        The function is called for each matching document with two arguments:
        this searcher and the document number. The function can usually only
        work with information that can be accessed based on the document
        number, such as stored fields, term vectors, and field caches.
        
        For example, assume an index where the "text" field was indexed with
        term vectors. The following function loads the term vector for each
        document and ranks documents containing equal occurrences of the terms
        "love" and "hate" highest::
        
            def fn(searcher, docnum):
                # Create a dictionary of term text to frequency
                v = dict(searcher.vector_as("frequency", docnum, "text"))
                # Give highest scores to documents that have equal numbers
                # of the two terms
                return 1.0 / (abs(v["love"] - v["hate"]) + 1.0)
            
            with myindex.searcher() as s:
                q = And([Term("text", u"love"), Term("text", u"hate")])
                results = s.sort_query_using(q, fn)
        
        (Note that the "function" can be an object with a ``__call__`` method.
        This may be useful for sharing information between calls.)
        
        :param q: the query to run.
        :param fn: a function to run on each document number to determine the
            document's "score". Higher values appear earlier in the results.
        :param filter: a query, Results object, or set of docnums. The results
            will only contain documents that are also in the filter object.
        """
        
        t = now()
        comb = self._filter_to_comb(filter)
        ls = [(fn(self, docnum), docnum) for docnum in self.docs_for_query(q)
              if (not comb) or docnum in comb]
        docset = set(docnum for _, docnum in ls)
        ls.sort(key=lambda x: (0 - x[0], x[1]))
        return Results(self, q, ls, docset, runtime=now() - t)

    def define_facets(self, name, qs, save=False):
        def doclists_for_searcher(s):
            return dict((key, q.docs(s)) for key, q in qs.iteritems())
        
        if self.subsearchers:
            for s in self.subsearchers:
                dls = doclists_for_searcher(s)
                s.reader().define_facets(name, dls, save=save)
        else:
            dls = doclists_for_searcher(self)
            self.ixreader.define_facets(name, dls, save=save)
    
    def categorize_query(self, q, fieldname, counts=False):
        groups = {}
        if isinstance(fieldname, basestring):
            fieldname = (fieldname, )
        
        if self.subsearchers:
            for s, offset in self.subsearchers:
                r = s.reader()
                r.group_docs_by(fieldname, q.docs(s), groups, counts=counts,
                                offset=offset)
        else:
            self.ixreader.group_docs_by(fieldname, q.docs(self), groups,
                                        counts=counts)
        return groups
    
    def search(self, q, limit=10, sortedby=None, reverse=False, groupedby=None,
               optimize=True, scored=True, filter=None, collector=None):
        """Runs the query represented by the ``query`` object and returns a
        Results object.
        
        When using optimizations, the order of results with very similar scores
        can change as the limit changes. To ensure a stable ordering of
        documents no matter what the value of ``limit``, use
        ``optimize=False``.
        
        :param query: a :class:`whoosh.query.Query` object.
        :param limit: the maximum number of documents to score. If you're only
            interested in the top N documents, you can set limit=N to limit the
            scoring for a faster search.
        :param sortedby: the name of a field to sort by, or a tuple of field
            names to sort by multiple fields. This is a shortcut for using a
            :class:`whoosh.sorting.Sorter` object to do a simple sort. To do
            complex sorts (where different fields are sorted in different
            directions), use :meth:`Searcher.sorter` to get a sorter and use it
            to perform the sorted search.
        :param reverse: Reverses the direction of the sort.
        :param groupedby: a list of field names or facet names. If this
            argument is not None, you can use the :meth:`Results.groups` method
            on the results object to retrieve a dictionary mapping field/facet
            values to document numbers.
        :param optimize: use optimizations to get faster results when possible.
        :param scored: if False, the results are not scored and are returned in
            "natural" order.
        :param collector: (expert) an instance of :class:`Collector` to use to
            collect the found documents.
        :param filter: a query, Results object, or set of docnums. The results
            will only contain documents that are also in the filter object.
        :rtype: :class:`Results`
        """

        if limit is not None and limit < 1:
            raise ValueError("limit must be >= 1")

        if sortedby is not None:
            sorter = self.sorter(sortedby=sortedby)
            return sorter.sort_query(q, limit=limit, reverse=reverse,
                                     filter=filter)
        
        if isinstance(groupedby, basestring):
            groupedby = (groupedby, )
        
        if collector is None:
            collector = Collector(limit=limit, usequality=optimize,
                                  groupedby=groupedby, scored=scored,
                                  reverse=reverse)
        else:
            collector.limit = limit
            collector.usequality = optimize
            collector.groupedby = groupedby
            collector.scored = scored
            collector.reverse = reverse
        
        return collector.search(self, q, filter=filter)
        

class Collector(object):
    def __init__(self, limit=10, usequality=True, replace=10, groupedby=None,
                 scored=True, timelimit=None, greedy=False, reverse=False):
        """A Collector finds the matching documents, scores them, collects them
        into a list, and produces a Results object from them.
        
        Normally you do not need to instantiate an instance of the base
        Collector class, the :meth:`Searcher.search` method does that for you.
        
        If you create a custom Collector instance or subclass you can pass it
        to the :meth:`Searcher.search` method using the ``collector`` keyword
        argument::
        
            mycollector = MyCollector()
            results = searcher.search(myquery, collector=mycollector)
        
        Note that when you call :meth:`Searcher.search` with a custom collector
        the method will overwrite several attributes on the collector instance
        with the values of keyword arguments to :meth:`Searcher.search`. To
        avoid this, start the search from the collector instead::
        
            mycollector = MyCollector()
            results = mycollector.search(searcher, myquery)
        
        **Do not** re-use or share Collector instances between searches. You
        should create a new Collector instance for each search.
        
        To limit the amount of time a search can take, pass the number of
        seconds to the ``timelimit`` keyword argument::
        
            # Limit the search to 4.5 seconds
            col = Collector(timelimit=4.5, greedy=False)
            # If this call takes more than 4.5 seconds, it will raise a
            # whoosh.searching.TimeLimit exception
            try:
                r = searcher.search(myquery, collector=col)
            except TimeLimit:
                # You can still retrieve partial results from the collector
                # after a time limit exception
                r = col.results()
            
        If the ``greedy`` keyword is ``True``, the collector will finish adding
        the most recent hit before raising the ``TimeLimit`` exception.
        """
        
        self.limit = limit
        self.usequality = usequality
        self.replace = replace
        self.groupedby = groupedby
        self.scored = scored
        self.timelimit = timelimit
        self.greedy = greedy
        self.reverse = reverse
        
        self.reset()
        
    def reset(self):
        if self.should_add_all():
            self._items = deque()
        else:
            self._items = []
        self.groups = {}
        self.docset = set()
        self.done = False
        self.minquality = None
        self.doc_offset = 0
        self.timesup = False
        self.timer = None
    
    def search(self, searcher, q, filter=None):
        """Top-level method call which uses the given :class:`Searcher` and
        :class:`whoosh.query.Query` objects to return a :class:`Results`
        object.
        
        This method takes care of calling :meth:`Collector.add_searcher`
        for each sub-searcher in a collective searcher. You should only call
        this method on a top-level searcher.
        """
        
        self.reset()
        self._searcher = searcher
        self._q = q
        
        w = searcher.weighting
        self.final = w.final if w.use_final else None
        
        if self.limit and self.limit > searcher.doc_count_all():
            self.limit = None
        
        self._comb = None
        if filter:
            self.add_filter(filter)
        
        if self.timelimit:
            self.timer = threading.Timer(self.timelimit, self._timestop)
            self.timer.start()
        
        t = now()
        if not searcher.is_atomic():
            for s, offset in searcher.subsearchers:
                if self.timesup:
                    raise TimeLimit
                self.doc_offset = offset
                done = self.add_searcher(s, q)
                if done:
                    break
        else:
            self.add_searcher(searcher, q)
            
        if self.timer:
            self.timer.cancel()
        
        runtime = now() - t
        return self.results(runtime=runtime)
    
    def _timestop(self):
        # Called by the Timer when the time limit expires. We could raise the
        # TimeLimit exception here, but that would probably leave the collector
        # in an inconsistent state. Instead, we'll set a flag, and check the
        # flag inside the add_(all|top)_matches loops.
        self.timesup = True
    
    def add_filter(self, obj):
        c = self._searcher._filter_to_comb(obj)
        if self._comb is None:
            self._comb = set()
        self._comb |= c
    
    def add_searcher(self, searcher, q):
        """Adds the documents from the given searcher with the given query to
        the collector. This is called by the :meth:`Collector.search` method.
        """
        
        return self.add_matches(searcher, q.matcher(searcher))
    
    def score(self, searcher, matcher):
        """Called to compute the score for the current document in the given
        :class:`whoosh.matching.Matcher`.
        """
        
        s = matcher.score()
        if self.final:
            s = self.final(searcher, matcher.id(), s)
        return s
    
    def collect(self, score, id):
        """This method is called for each found document. This method is only
        called by :meth:`Collector.add_all_matches`.
        
        :param score: the  score for this document. This may be None if the
            collector is not set up to compute scores.
        :param id: the document number of the document.
        """
        
        # This method is only called by add_all_matches. Note: the document
        # number is negated to match the output of add_top_matches
        self._items.append((score, 0 - id))
        self.docset.add(id)
    
    def should_add_all(self):
        """Returns True if this collector needs to add all found documents (for
        example, if ``limit=None``), or alse if this collector should only
        add the top N found documents.
        """
        
        return not self.scored or not self.limit or self.groupedby
    
    def add_matches(self, searcher, matcher):
        """Calls either :meth:Collector.add_top_matches` or
        :meth:`Collector.add_all_matches` depending on whether this collector
        needs to examine all documents.
        """
        
        if self.should_add_all():
            return self.add_all_matches(searcher, matcher)
        else:
            return self.add_top_matches(searcher, matcher)
    
    def add_top_matches(self, searcher, matcher):
        """Adds the matched documents from the given matcher to the collector's
        priority queue.
        """
        
        offset = self.doc_offset
        limit = self.limit
        items = self._items
        usequality = self.usequality
        score = self.score
        comb = self._comb
        timelimited = bool(self.timelimit)
        greedy = self.greedy
        
        # Note that 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.
        for id, quality in self.pull_matches(matcher, usequality):
            if timelimited and not greedy and self.timesup:
                raise TimeLimit
            
            offsetid = id + offset
            if comb and offsetid not in comb:
                continue
            
            if len(items) < limit:
                # The heap isn't full, so just add this document
                heappush(items, (score(searcher, matcher), 0 - offsetid, quality))
            
            elif not usequality or quality > self.minquality:
                # The heap is full, but the posting quality indicates
                # this document is good enough to make the top N, so
                # calculate its true score and add it to the heap
                
                s = score(searcher, matcher)
                if s > items[0][0]:
                    heapreplace(items, (s, 0 - offsetid, quality))
                    self.minquality = items[0][2]
                    
            if timelimited and self.timesup:
                raise TimeLimit
    
    def add_all_matches(self, searcher, matcher):
        """Adds the matched documents from the given matcher to the collector's
        list of matched documents.
        """
        
        offset = self.doc_offset
        limit = self.limit
        items = self._items
        scored = self.scored
        score = self.score
        comb = self._comb
        timelimited = bool(self.timelimit)
        greedy = self.greedy
        reverse = self.reverse
        
        keyfns = None
        if self.groupedby:
            limit = None
            keyfns = {}
            for name in self.groupedby:
                keyfns[name] = searcher.reader().key_fn(name)
        
        for id, _ in self.pull_matches(matcher, False):
            if timelimited and not greedy and self.timesup:
                raise TimeLimit
            
            offsetid = id + offset
            if comb and offsetid not in comb:
                continue
            
            if keyfns:
                for name, keyfn in keyfns.iteritems():
                    if name not in self.groups:
                        self.groups[name] = defaultdict(list)
                    key = keyfn(id)
                    self.groups[name][key].append(id)
            
            scr = 0
            if scored:
                scr = score(searcher, matcher)
            self.collect(scr, offsetid)
            
            if limit:
                if reverse and len(items) > limit:
                    items.popleft()
                elif (not reverse) and len(items) >= limit:
                    return True
            
            if timelimited and self.timesup:
                raise TimeLimit
            
    def pull_matches(self, matcher, usequality):
        """Low-level method yields (docid, quality) pairs from the given
        matcher. Called by :meth:`Collector.add_top_matches` and
        :meth:`Collector.add_all_matches`. If ``usequality`` is False or the
        matcher doesn't support quality, the second item in each pair will be
        ``None``.
        """
        
        docset = self.docset
        
        # Can't use quality optimizations if the matcher doesn't support them
        usequality = usequality and matcher.supports_quality()
        replace = self.replace
        
        # A flag to indicate whether we should check block quality at the start
        # of the next loop
        checkquality = True
        replacecounter = 0
        
        while matcher.is_active():
            # If we're using 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 self.minquality is not None:
                matcher.skip_to_quality(self.minquality)
                # Skipping ahead might have moved the matcher to the end of the
                # posting list
                if not matcher.is_active():
                    break
            
            # The current document ID 
            id = matcher.id()
            
            if not usequality:
                docset.add(id)
            
            # If we're using quality optimizations, check whether the current
            # posting has higher quality than the minimum before yielding it.
            if usequality:
                postingquality = matcher.quality()
                if postingquality > self.minquality:
                    yield (id, postingquality)
            else:
                yield (id, None)
            
            # 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()
            
            # Ask the matcher to replace itself with a more efficient version
            # if possible
            if replace and matcher.is_active():
                replacecounter += 1
                if replacecounter >= replace:
                    matcher = matcher.replace()

    def items(self):
        """Returns the collected hits as a list of (score, docid) pairs.
        """
        
        # Docnums are stored as negative for reasons too obscure to go into
        # here, re-negate them before returning
        items = [(x[0], 0 - x[1]) for x in self._items]
        
        # 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
        if self.scored or self.reverse:
            items.sort(key=lambda x: (0 - x[0], x[1]), reverse=self.reverse)
        
        return items
    
    def results(self, runtime=None):
        """Returns the collected hits as a :class:`Results` object.
        """
        
        docset = self.docset or None
        return Results(self._searcher, self._q, self.items(), docset,
                       groups=self.groups, runtime=runtime)


class TermTrackingCollector(Collector):
    """This collector records which parts of the query matched which documents
    in the final results. The results for each part of the query are available
    as a dictionary in the ``catalog`` attribute of the collector after the
    search, where the keys are representations of the parts of the query and
    the values are sets of document numbers that matched that part of the
    query.
    
    How to choose a key to represent query objects in the ``catalog``
    dictionary was not entirely clear. The current implementation uses the
    unicode representation of the query object, which usually returns something
    at least recognizable (for example, ``unicode(Term("f", u"a")) == u"f:a"``
    and ``unicode(Prefix("f", "b")) == u"f:b*"``).
    
    >>> myparser = qparser.QueryParser("content", myindex.schema)
    >>> myquery = myparser.parse(u"apple OR bear NOT camel")
    >>> col = TermTrackingCollector()
    >>> results = searcher.search(myquery, collector=col)
    >>> # The docnums in the results that contained "apple"
    >>> col.catalog["content:apple"]
    set([1, 2, 3])
    >>> for hit in results:
    ...     print hit.rank, ":", hit["title"]
    ...     for key, docset in col.catalog.keys():
    ...         if hit.docnum in docset:
    ...             print "   - Contains", key
    """
    
    # This collector works by rewriting the query with "TaggedQuery" wrappers
    # around the leaf nodes before it searches. When base collector generates
    # a matcher tree from the query tree, these wrappers "phone home" to this
    # collector and register the leaf matchers. Then, when collecting hits, the
    # collector checks with the leaf matchers at each hit to see if they are
    # matching the current document.
    
    def __init__(self, *args, **kwargs):
        super(TermTrackingCollector, self).__init__(*args, **kwargs)
        self.matchers = []
        self.catalog = {}
    
    def add_searcher(self, searcher, q):
        # For each searcher added to the collector, reset the list of matchers
        # and re-tag the query
        self.matchers = []
        q = self._tag(q)
        return super(TermTrackingCollector, self).add_searcher(searcher, q)
    
    def should_add_all(self):
        # If you're using this collector, you need to examine all documents
        return True
    
    def collect(self, score, id):
        # The id passed to this method is rebased for the top-level searcher,
        # so we need to subtract the doc offset from it before we can compare
        # it to a matcher's id()
        offset = self.doc_offset
        
        # Check the registered matchers, and if they're contributing to the
        # current match, add the current match to the set of documents
        # containing them
        for q, m in self.matchers:
            if m.is_active() and m.id() == id - offset:
                key = unicode(q)
                if key not in self.catalog:
                    self.catalog[key] = set()
                self.catalog[key].add(id)
        
        super(TermTrackingCollector, self).collect(score, id)
    
    def _tag(self, q):
        # Takes a query and returns a copy of the query with a TaggedQuery
        # wrapper around any leaf nodes in the query tree
        if isinstance(q, query.Not):
            return q
        elif q.is_leaf():
            return TermTrackingCollector.TaggedQuery(q, self)
        else:
            return q.apply(self._tag)
        
    def _tag_matcher(self, q, m):
        # This method is called from the TaggedQuery wrappers that the _tag
        # method added to the query
        self.matchers.append((q, m))
        
    class TaggedQuery(query.WrappingQuery):
        # The only purpose of this query wrapper is to "call home" to the
        # TrackingCollector instance when the child query generates a matcher
        # so the TrackingCollector can register it
        
        def __init__(self, child, tracker):
            self.child = child
            self.tracker = tracker
        
        def matcher(self, searcher):
            m = self.child.matcher(searcher)
            self.tracker._tag_matcher(self.child, m)
            return m


class Results(object):
    """This object is returned by a Searcher. This object represents the
    results of a search query. You can mostly use it as if it was a list of
    dictionaries, where each dictionary is the stored fields of the document at
    that position in the results.
    """

    def __init__(self, searcher, q, top_n, docset, groups=None, runtime=-1):
        """
        :param searcher: the :class:`Searcher` object that produced these
            results.
        :param query: the original query that created these results.
        :param top_n: a list of (score, docnum) tuples representing the top
            N search results.
        :param scores: a list of scores corresponding to the document
            numbers in top_n, or None if the results do not have scores.
        :param runtime: the time it took to run this search.
        """

        self.searcher = searcher
        self.q = q
        self.top_n = top_n
        self.docset = docset
        self._groups = groups or {}
        self.runtime = runtime
        self._terms = None
        
        self.fragmenter = highlight.ContextFragmenter()
        self.fragment_scorer = highlight.BasicFragmentScorer()
        self.formatter = highlight.HtmlFormatter(tagname="b")
    
    def __repr__(self):
        return "<Top %s Results for %r runtime=%s>" % (len(self.top_n),
                                                       self.q,
                                                       self.runtime)

    def __len__(self):
        """Returns the total number of documents that matched the query. Note
        this may be more than the number of scored documents, given the value
        of the ``limit`` keyword argument to :meth:`Searcher.search`.
        
        If this Results object was created by searching with a ``limit``
        keyword, then computing the exact length of the result set may be
        expensive for large indexes or large result sets. You may consider
        using :meth:`Results.has_exact_length`,
        :meth:`Results.estimated_length`, and
        :meth:`Results.estimated_min_length` to display an estimated size of
        the result set instead of an exact number.
        """
        
        if self.docset is None:
            self._load_docs()
        return len(self.docset)

    def __getitem__(self, n):
        if isinstance(n, slice):
            start, stop, step = n.indices(len(self.top_n))
            return [Hit(self, self.top_n[i][1], i, self.top_n[i][0])
                    for i in xrange(start, stop, step)]
        else:
            return Hit(self, self.top_n[n][1], n, self.top_n[n][0])

    def __iter__(self):
        """Yields a :class:`Hit` object for each result in ranked order.
        """
        
        for i in xrange(len(self.top_n)):
            yield Hit(self, self.top_n[i][1], i, self.top_n[i][0])
    
    def __contains__(self, docnum):
        """Returns True if the given document number matched the query.
        """
        
        if self.docset is None:
            self._load_docs()
        return docnum in self.docset

    def items(self):
        """Returns an iterator of (docnum, score) pairs for the scored
        documents in the results.
        """
        
        return ((docnum, score) for score, docnum in self.top_n)

    def terms(self):
        if self._terms is  None:
            self._terms = self.q.existing_terms(self.searcher.reader())
        return self._terms

    def fields(self, n):
        """Returns the stored fields for the document at the ``n`` th position
        in the results. Use :meth:`Results.docnum` if you want the raw
        document number instead of the stored fields.
        """
        
        return self.searcher.stored_fields(self.top_n[n][1])
    
    def groups(self, name):
        """If you generating groupings for the results by using the `groups`
        keyword to the `search()` method, you can use this method to retrieve
        the groups.
        
        >>> results = searcher.search(my_query, groups=["tag"])
        >>> results.groups("tag")
        
        Returns a dictionary mapping category names to lists of document IDs.
        """
        
        return self._groups[name]
    
    def _load_docs(self):
        self.docset = set(self.searcher.docs_for_query(self.q))

    def has_exact_length(self):
        """True if this results object already knows the exact number of
        matching documents.
        """
        
        return self.docset is not None

    def estimated_length(self):
        """The estimated maximum number of matching documents, or the
        exact number of matching documents if it's known.
        """
        
        if self.docset is not None:
            return len(self.docset)
        return self.q.estimate_size(self.searcher.reader())
    
    def estimated_min_length(self):
        """The estimated minimum number of matching documents, or the
        exact number of matching documents if it's known.
        """
        
        if self.docset is not None:
            return len(self.docset)
        return self.q.estimate_min_size(self.searcher.reader())
    
    def scored_length(self):
        """Returns the number of scored documents in the results, equal to or
        less than the ``limit`` keyword argument to the search.
        
        >>> r = mysearcher.search(myquery, limit=20)
        >>> len(r)
        1246
        >>> r.scored_length()
        20
        
        This may be fewer than the total number of documents that match the
        query, which is what ``len(Results)`` returns.
        """
        
        return len(self.top_n)

    def docs(self):
        """Returns a set-like object containing the document numbers that
        matched the query.
        """
        
        if self.docset is None:
            self._load_docs()
        return self.docset

    def copy(self):
        """Returns a copy of this results object.
        """
        
        return self.__class__(self.searcher, self.q, self.top_n[:],
                              copy.copy(self.docset), runtime=self.runtime)

    def score(self, n):
        """Returns the score for the document at the Nth position in the list
        of ranked documents. If the search was not scored, this may return None.
        """

        return self.top_n[n][0]

    def docnum(self, n):
        """Returns the document number of the result at position n in the list
        of ranked documents.
        """
        return self.top_n[n][1]

    def highlights(self, n, fieldname, text=None, top=3, fragmenter=None,
                   formatter=None, order=highlight.FIRST):
        """Returns highlighted snippets for the document in the Nth position
        in the results. It is usually more convenient to call this method on a
        Hit object instead of the Results.
        
        See the docs for the :meth:`Hit.highlights` method.
        """
        
        if text is None:
            d = self.fields(n)
            if fieldname not in d:
                raise KeyError("Field %r is not in the stored fields.")
            text = d[fieldname]
        
        analyzer = self.searcher.schema[fieldname].format.analyzer
        fragmenter = fragmenter or self.fragmenter
        formatter = formatter or self.formatter
        
        terms = set(ttext for fname, ttext in self.terms() if fname == fieldname)
        return highlight.highlight(text, terms, analyzer, fragmenter,
                                   formatter, top=top,
                                   scorer=self.fragment_scorer, order=order)

    def key_terms(self, fieldname, docs=10, numterms=5,
                  model=classify.Bo1Model, normalize=True):
        """Returns the 'numterms' most important terms from the top 'numdocs'
        documents in these results. "Most important" is generally defined as
        terms that occur frequently in the top hits but relatively infrequently
        in the collection as a whole.
        
        :param fieldname: Look at the terms in this field. This field must
            store vectors.
        :param docs: Look at this many of the top documents of the results.
        :param terms: Return this number of important terms.
        :param model: The classify.ExpansionModel to use. See the classify
            module.
        :returns: list of unicode strings.
        """

        if not len(self):
            return
        docs = min(docs, len(self))

        reader = self.searcher.reader()

        expander = classify.Expander(reader, fieldname, model=model)
        for _, docnum in self.top_n[:docs]:
            expander.add_document(docnum)

        return expander.expanded_terms(numterms, normalize=normalize)
    
    def extend(self, results):
        """Appends hits from 'results' (that are not already in this
        results object) to the end of these results.
        
        :param results: another results object.
        """
        
        docs = self.docs()
        for item in results.top_n:
            if item[1] not in docs:
                self.top_n.append(item)
        self.docset = docs | results.docs()
    
    def filter(self, results):
        """Removes any hits that are not also in the other results object.
        """

        if not len(results):
            return

        otherdocs = results.docs()
        items = [item for item in self.top_n if item[1] in otherdocs]
        self.docset = self.docs() & otherdocs
        self.top_n = items
        
    def upgrade(self, results, reverse=False):
        """Re-sorts the results so any hits that are also in 'results' appear
        before hits not in 'results', otherwise keeping their current relative
        positions. This does not add the documents in the other results object
        to this one.
        
        :param results: another results object.
        :param reverse: if True, lower the position of hits in the other
            results object instead of raising them.
        """

        if not len(results):
            return

        otherdocs = results.docs()
        arein = [item for item in self.top_n if item[1] in otherdocs]
        notin = [item for item in self.top_n if item[1] not in otherdocs]

        if reverse:
            items = notin + arein
        else:
            items = arein + notin
        
        self.top_n = items
        
    def upgrade_and_extend(self, results):
        """Combines the effects of extend() and increase(): hits that are also
        in 'results' are raised. Then any hits from the other results object
        that are not in this results object are appended to the end.
        
        :param results: another results object.
        """

        if not len(results):
            return

        docs = self.docs()
        otherdocs = results.docs()

        arein = [item for item in self.top_n if item[1] in otherdocs]
        notin = [item for item in self.top_n if item[1] not in otherdocs]
        other = [item for item in results.top_n if item[1] not in docs]

        self.docset = docs | otherdocs
        self.top_n = arein + notin + other


class Hit(object):
    """Represents a single search result ("hit") in a Results object.
    
    This object acts like a dictionary of the matching document's stored
    fields. If for some reason you need an actual ``dict`` object, use
    ``Hit.fields()`` to get one.
    
    >>> r = searcher.search(query.Term("content", "render"))
    >>> r[0]
    <Hit {title=u"Rendering the scene"}>
    >>> r[0].rank
    0
    >>> r[0].docnum
    4592L
    >>> r[0].score
    2.52045682
    >>> r[0]["title"]
    "Rendering the scene"
    >>> r[0].keys()
    ["title"]
    """
    
    def __init__(self, results, docnum, pos=None, score=None):
        """
        :param results: the Results object this hit belongs to.
        :param pos: the position in the results list of this hit, for example
            pos=0 means this is the first (highest scoring) hit.
        :param docnum: the document number of this hit.
        :param score: the score of this hit.
        """
        
        self.results = results
        self.searcher = results.searcher
        self.pos = self.rank = pos
        self.docnum = docnum
        self.score = score
        self._fields = None
    
    def fields(self):
        """Returns a dictionary of the stored fields of the document this
        object represents.
        """
        
        if self._fields is None:
            self._fields = self.searcher.stored_fields(self.docnum)
        return self._fields
    
    def highlights(self, fieldname, text=None, top=3, fragmenter=None,
                   formatter=None, order=highlight.FIRST):
        """Returns highlighted snippets from the given field::
        
            r = searcher.search(myquery)
            for hit in r:
                print hit["title"]
                print hit.highlights("content")
        
        See :doc:`how to highlight terms in search results </highlight>` for
        more information.
        
        You can set the ``fragmenter`` and ``formatter`` attributes on the
        ``Results`` object instead of specifying the ``fragmenter`` and
        ``formatter`` arguments to this method. For example, to return larger
        fragments and highlight them by converting to upper-case instead of
        with HTML tags::
        
            from whoosh import highlight
        
            r = searcher.search(myquery)
            r.fragmenter = highlight.ContextFragmenter(surround=40)
            r.formatter = highlight.UppercaseFormatter()
            for hit in r:
                print hit["title"]
                print hit.highlights("content")
        
        :param fieldname: the name of the field you want to highlight.
        :param text: by default, the method will attempt to load the contents
            of the field from the stored fields for the document. If the field
            you want to highlight isn't stored in the index, but you have
            access to the text another way (for example, loading from a file or
            a database), you can supply it using the ``text`` parameter.
        :param top: the maximum number of fragments to return.
        :param fragmenter: A :class:`whoosh.highlight.Fragmenter` object. This
            controls how the text is broken in fragments. The default is
            :class:`whoosh.highlight.ContextFragmenter`. For some applications
            you may find that a different fragmenting algorithm, such as
            :class:`whoosh.highlight.SentenceFragmenter` gives better results.
            For short fields you could use
            :class:`whoosh.highlight.WholeFragmenter` which returns the entire
            field as a single fragment.
        :param formatter: A :class:`whoosh.highlight.Formatter` object. This
            controls how the search terms are highlighted in the snippets. The
            default is :class:`whoosh.highlight.HtmlFormatter` with
            ``tagname='b'``.
            
            Note that different formatters may return different objects, e.g.
            plain text, HTML, a Genshi event stream, a SAX event generator,
            etc.
        :param order: the order of the fragments. This should be one of
            :func:`whoosh.highlight.SCORE`, :func:`whoosh.highlight.FIRST`,
            :func:`whoosh.highlight.LONGER`,
            :func:`whoosh.highlight.SHORTER`, or a custom sorting function. The
            default is ``highlight.FIRST``.
        """
        
        return self.results.highlights(self.rank, fieldname, text=text,
                                       top=top, fragmenter=fragmenter,
                                       formatter=formatter, order=order)
    
    def more_like_this(self, fieldname, text=None, top=10, numterms=5,
                       model=classify.Bo1Model, normalize=True):
        """Returns a new Results object containing documents similar to this
        hit, based on "key terms" in the given field::
        
            r = searcher.search(myquery)
            for hit in r:
                print hit["title"]
                print "Top 3 similar documents:"
                for subhit in hit.more_like_this("content", top=3):
                  print "  ", subhit["title"]
                  
        :param fieldname: the name of the field to use to test similarity.
        :param text: by default, the method will attempt to load the contents
            of the field from the stored fields for the document, or from a
            term vector. If the field isn't stored or vectored in the index,
            but you have access to the text another way (for example, loading
            from a file or a database), you can supply it using the ``text``
            parameter.
        :param top: the number of results to return.
        :param numterms: the number of "key terms" to extract from the hit and
            search for. Using more terms is slower but gives potentially more
            and more accurate results.
        :param model: (expert) a :class:`whoosh.classify.ExpansionModel` to use
            to compute "key terms".
        :param normalize: whether to normalize term weights.
        """
        
        return self.searcher.more_like(self.docnum, fieldname, text=text,
                                       top=top, numterms=numterms, model=model,
                                       normalize=normalize)
    
    def __repr__(self):
        return "<%s %r>" % (self.__class__.__name__, self.fields())
    
    def __eq__(self, other):
        if isinstance(other, Hit):
            return self.fields() == other.fields()
        elif isinstance(other, dict):
            return self.fields() == other
        else:
            return False
    
    def __len__(self):
        return len(self.fields())
    
    def __iter__(self):
        return self.fields().iterkeys()
    
    def __getitem__(self, key):
        return self.fields().__getitem__(key)
    
    def __contains__(self, key):
        return key in self.fields()
    
    def items(self):
        return self.fields().items()
    
    def keys(self):
        return self.fields().keys()
    
    def values(self):
        return self.fields().values()
    
    def iteritems(self):
        return self.fields().iteritems()
    
    def iterkeys(self):
        return self.fields().iterkeys()
    
    def itervalues(self):
        return self.fields().itervalues()
    
    def get(self, key, default=None):
        return self.fields().get(key, default)
    
    def __setitem__(self, key, value):
        raise NotImplementedError("You cannot modify a search result")
    
    def __delitem__(self, key, value):
        raise NotImplementedError("You cannot modify a search result")
    
    def clear(self):
        raise NotImplementedError("You cannot modify a search result")
    
    def update(self, dict=None, **kwargs):
        raise NotImplementedError("You cannot modify a search result")
    

class ResultsPage(object):
    """Represents a single page out of a longer list of results, as returned
    by :func:`whoosh.searching.Searcher.search_page`. Supports a subset of the
    interface of the :class:`~whoosh.searching.Results` object, namely getting
    stored fields with __getitem__ (square brackets), iterating, and the
    ``score()`` and ``docnum()`` methods.
    
    The ``offset`` attribute contains the results number this page starts at
    (numbered from 0). For example, if the page length is 10, the ``offset``
    attribute on the second page will be ``10``.
    
    The ``pagecount`` attribute contains the number of pages available.
    
    The ``pagenum`` attribute contains the page number. This may be less than
    the page you requested if the results had too few pages. For example, if
    you do::
    
        ResultsPage(results, 5)
        
    but the results object only contains 3 pages worth of hits, ``pagenum``
    will be 3.
    
    The ``pagelen`` attribute contains the number of results on this page
    (which may be less than the page length you requested if this is the last
    page of the results).
    
    The ``total`` attribute contains the total number of hits in the results.
    
    >>> mysearcher = myindex.searcher()
    >>> pagenum = 2
    >>> page = mysearcher.find_page(pagenum, myquery)
    >>> print("Page %s of %s, results %s to %s of %s" %
    ...       (pagenum, page.pagecount, page.offset+1,
    ...        page.offset+page.pagelen, page.total))
    >>> for i, fields in enumerate(page):
    ...   print("%s. %r" % (page.offset + i + 1, fields))
    >>> mysearcher.close()
    """

    def __init__(self, results, pagenum, pagelen=10):
        """
        :param results: a :class:`~whoosh.searching.Results` object.
        :param pagenum: which page of the results to use, numbered from ``1``.
        :param pagelen: the number of hits per page.
        """
        
        self.results = results
        self.total = len(results)
        
        if pagenum < 1:
            raise ValueError("pagenum must be >= 1")
        
        self.pagecount = int(ceil(self.total / pagelen))
        if pagenum > 1 and pagenum > self.pagecount:
            raise ValueError("Asked for page %s of %s" % (pagenum, self.pagecount))
        
        self.pagenum = pagenum

        offset = (pagenum - 1) * pagelen
        if (offset + pagelen) > self.total:
            pagelen = self.total - offset
        self.offset = offset
        self.pagelen = pagelen

    def __getitem__(self, n):
        offset = self.offset
        if isinstance(n, slice):
            start, stop, step = n.indices(self.pagelen)
            return self.results.__getitem__(slice(start + offset, stop + offset, step))
        else:
            return self.results.__getitem__(n + offset)

    def __iter__(self):
        return iter(self.results[self.offset:self.offset + self.pagelen])

    def __len__(self):
        return self.total

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

    def score(self, n):
        """Returns the score of the hit at the nth position on this page.
        """
        return self.results.score(n + self.offset)

    def docnum(self, n):
        """Returns the document number of the hit at the nth position on this
        page.
        """
        return self.results.docnum(n + self.offset)
    
    def is_last_page(self):
        """Returns True if this object represents the last page of results.
        """
        
        return self.pagecount == 0 or self.pagenum == self.pagecount