Source

whoosh / src / whoosh / matching / mcore.py

The branch 'logging' does not exist.
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
# Copyright 2010 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 "matcher" classes. Matchers deal with posting lists. The
most basic matcher, which reads the list of postings for a term, will be
provided by the backend implementation (for example,
:class:`whoosh.filedb.filepostings.FilePostingReader`). The classes in this
module provide additional functionality, such as combining the results of two
matchers, or modifying the results of a matcher.

You do not need to deal with the classes in this module unless you need to
write your own Matcher implementation to provide some new functionality. These
classes are not instantiated by the user. They are usually created by a
:class:`~whoosh.query.Query` object's :meth:`~whoosh.query.Query.matcher()`
method, which returns the appropriate matcher to implement the query (for
example, the :class:`~whoosh.query.Or` query's
:meth:`~whoosh.query.Or.matcher()` method returns a
:py:class:`~whoosh.matching.UnionMatcher` object).

Certain backends support "quality" optimizations. These backends have the
ability to skip ahead if it knows the current block of postings can't
contribute to the top N documents. If the matcher tree and backend support
these optimizations, the matcher's :meth:`Matcher.supports_block_quality()`
method will return ``True``.
"""

import logging, sys
from itertools import repeat

from whoosh.compat import izip, xrange
from whoosh.compat import abstractmethod


log = logging.getLogger(__name__)


# Exceptions

class ReadTooFar(Exception):
    """Raised when :meth:`~whoosh.matching.Matcher.next()` or
    :meth:`~whoosh.matching.Matcher.skip_to()` are called on an inactive
    matcher.
    """


class NoQualityAvailable(Exception):
    """Raised when quality methods are called on a matcher that does not
    support block quality optimizations.
    """


# Classes

class Matcher(object):
    """Base class for all matchers.
    """

    @abstractmethod
    def is_active(self):
        """Returns True if this matcher is still "active", that is, it has not
        yet reached the end of the posting list.
        """

        raise NotImplementedError

    @abstractmethod
    def reset(self):
        """Returns to the start of the posting list.

        Note that reset() may not do what you expect after you call
        :meth:`Matcher.replace()`, since this can mean calling reset() not on
        the original matcher, but on an optimized replacement.
        """

        raise NotImplementedError

    def term(self):
        """Returns a ``("fieldname", "termtext")`` tuple for the term this
        matcher matches, or None if this matcher is not a term matcher.
        """

        return None

    def term_matchers(self):
        """Returns an iterator of term matchers in this tree.
        """

        if self.term() is not None:
            yield self
        else:
            for cm in self.children():
                for m in cm.term_matchers():
                    yield m

    def matching_terms(self, id=None):
        """Returns an iterator of ``("fieldname", "termtext")`` tuples for the
        **currently matching** term matchers in this tree.
        """

        if not self.is_active():
            return

        if id is None:
            id = self.id()
        elif id != self.id():
            return

        t = self.term()
        if t is None:
            for c in self.children():
                for t in c.matching_terms(id):
                    yield t
        else:
            yield t

    def children(self):
        """Returns an (possibly empty) list of the submatchers of this
        matcher.
        """

        return []

    def replace(self, minquality=0):
        """Returns a possibly-simplified version of this matcher. For example,
        if one of the children of a UnionMatcher is no longer active, calling
        this method on the UnionMatcher will return the other child.
        """

        return self

    @abstractmethod
    def copy(self):
        """Returns a copy of this matcher.
        """

        raise NotImplementedError

    def depth(self):
        """Returns the depth of the tree under this matcher, or 0 if this
        matcher does not have any children.
        """

        return 0

    def supports_block_quality(self):
        """Returns True if this matcher supports the use of ``quality`` and
        ``block_quality``.
        """

        return False

    def block_quality(self):
        """Returns a quality measurement of the current block of postings,
        according to the current weighting algorithm. Raises
        ``NoQualityAvailable`` if the matcher or weighting do not support
        quality measurements.
        """

        raise NoQualityAvailable(self.__class__)

    @abstractmethod
    def id(self):
        """Returns the ID of the current posting.
        """

        raise NotImplementedError

    def all_ids(self):
        """Returns a generator of all IDs in the matcher.

        What this method returns for a matcher that has already read some
        postings (whether it only yields the remaining postings or all postings
        from the beginning) is undefined, so it's best to only use this method
        on fresh matchers.
        """

        i = 0
        while self.is_active():
            yield self.id()
            self.next()
            i += 1
            if i == 10:
                self = self.replace()
                i = 0

    def all_items(self):
        """Returns a generator of all (ID, encoded value) pairs in the matcher.

        What this method returns for a matcher that has already read some
        postings (whether it only yields the remaining postings or all postings
        from the beginning) is undefined, so it's best to only use this method
        on fresh matchers.
        """

        i = 0
        while self.is_active():
            yield (self.id(), self.value())
            self.next()
            i += 1
            if i == 10:
                self = self.replace()
                i = 0

    def items_as(self, astype):
        """Returns a generator of all (ID, decoded value) pairs in the matcher.

        What this method returns for a matcher that has already read some
        postings (whether it only yields the remaining postings or all postings
        from the beginning) is undefined, so it's best to only use this method
        on fresh matchers.
        """

        while self.is_active():
            yield (self.id(), self.value_as(astype))
            self.next()

    @abstractmethod
    def value(self):
        """Returns the encoded value of the current posting.
        """

        raise NotImplementedError

    @abstractmethod
    def supports(self, astype):
        """Returns True if the field's format supports the named data type,
        for example 'frequency' or 'characters'.
        """

        raise NotImplementedError("supports not implemented in %s"
                                  % self.__class__)

    @abstractmethod
    def value_as(self, astype):
        """Returns the value(s) of the current posting as the given type.
        """

        raise NotImplementedError("value_as not implemented in %s"
                                  % self.__class__)

    def spans(self):
        """Returns a list of :class:`whoosh.spans.Span` objects for the matches
        in this document. Raises an exception if the field being searched does
        not store positions.
        """

        from whoosh.spans import Span
        if self.supports("characters"):
            return [Span(pos, startchar=startchar, endchar=endchar)
                    for pos, startchar, endchar in self.value_as("characters")]
        elif self.supports("positions"):
            return [Span(pos) for pos in self.value_as("positions")]
        else:
            raise Exception("Field does not support spans")

    def skip_to(self, id):
        """Moves this matcher to the first posting with an ID equal to or
        greater than the given ID.
        """

        while self.is_active() and self.id() < id:
            self.next()

    def skip_to_quality(self, minquality):
        """Moves this matcher to the next block with greater than the given
        minimum quality value.
        """

        raise NotImplementedError(self.__class__.__name__)

    @abstractmethod
    def next(self):
        """Moves this matcher to the next posting.
        """

        raise NotImplementedError(self.__class__.__name__)

    def weight(self):
        """Returns the weight of the current posting.
        """

        return self.value_as("weight")

    @abstractmethod
    def score(self):
        """Returns the score of the current posting.
        """

        raise NotImplementedError(self.__class__.__name__)

    def __eq__(self, other):
        return self.__class__ is type(other)

    def __lt__(self, other):
        return type(other) is self.__class__

    def __ne__(self, other):
        return not self.__eq__(other)

    def __gt__(self, other):
        return not (self.__lt__(other) or self.__eq__(other))

    def __le__(self, other):
        return self.__eq__(other) or self.__lt__(other)

    def __ge__(self, other):
        return self.__eq__(other) or self.__gt__(other)


class NullMatcherClass(Matcher):
    """Matcher with no postings which is never active.
    """

    def __call__(self):
        return self

    def supports_block_quality(self):
        return True

    def block_quality(self):
        return 0

    def skip_to_quality(self, minquality):
        return 0

    def is_active(self):
        return False

    def reset(self):
        pass

    def all_ids(self):
        return []

    def copy(self):
        return self

    def max_quality(self):
        return 0


# Singleton instance
NullMatcher = NullMatcherClass()


class ListMatcher(Matcher):
    """Synthetic matcher backed by a list of IDs.
    """

    def __init__(self, ids, weights=None, values=None, format=None,
                 scorer=None, position=0, all_weights=None, term=None,
                 terminfo=None):
        """
        :param ids: a list of doc IDs.
        :param weights: a list of weights corresponding to the list of IDs.
            If this argument is not supplied, a list of 1.0 values is used.
        :param values: a list of encoded values corresponding to the list of
            IDs.
        :param format: a :class:`whoosh.formats.Format` object representing the
            format of the field.
        :param scorer: a :class:`whoosh.scoring.BaseScorer` object for scoring
            the postings.
        :param term: a ``("fieldname", "text")`` tuple, or None if this is not
            a term matcher.
        """

        self._ids = ids
        self._weights = weights
        self._all_weights = all_weights
        self._values = values
        self._i = position
        self._format = format
        self._scorer = scorer
        self._term = term
        self._terminfo = terminfo

    def __repr__(self):
        return "<%s>" % self.__class__.__name__

    def is_active(self):
        return self._i < len(self._ids)

    def reset(self):
        self._i = 0

    def term(self):
        return self._term

    def copy(self):
        return self.__class__(self._ids, self._weights, self._values,
                              self._format, self._scorer, self._i,
                              self._all_weights)

    def replace(self, minquality=0):
        if not self.is_active() or (minquality
                                    and self.max_quality() < minquality):
            return NullMatcher()
        else:
            return self

    def max_quality(self):
        return self.block_max_weight()

    def supports_block_quality(self):
        return (self._scorer is not None
                and self._scorer.supports_block_quality())

    def block_quality(self):
        return self._scorer.block_quality(self)

    def skip_to_quality(self, minquality):
        self._i += 1
        while self._i < len(self._ids) and self.quality() <= minquality:
            self._i += 1
        return 0

    def id(self):
        return self._ids[self._i]

    def all_ids(self):
        return iter(self._ids)

    def all_items(self):
        values = self._values
        if values is None:
            values = repeat('')

        return izip(self._ids, values)

    def value(self):
        if self._values:
            v = self._values[self._i]

            if isinstance(v, list):
                # This object supports "values" that are actually lists of
                # value strings. This is to support combining the results of
                # several different matchers into a single ListMatcher (see the
                # TOO_MANY_CLAUSES functionality of MultiTerm). We combine the
                # values here instead of combining them first and then making
                # the ListMatcher to avoid wasting time combining values if the
                # consumer never asks for them.
                assert len(v) > 0
                if len(v) == 1:
                    v = v[0]
                else:
                    v = self._format.combine(v)
                # Replace the list with the computed value string
                self._values[self._i] = v

            return v
        else:
            return ''

    def value_as(self, astype):
        decoder = self._format.decoder(astype)
        return decoder(self.value())

    def supports(self, astype):
        return self._format.supports(astype)

    def next(self):
        self._i += 1

    def weight(self):
        if self._all_weights:
            return self._all_weights
        elif self._weights:
            return self._weights[self._i]
        else:
            return 1.0

    def block_min_length(self):
        return self._terminfo.min_length()

    def block_max_length(self):
        return self._terminfo.max_length()

    def block_max_weight(self):
        if self._all_weights:
            return self._all_weights
        elif self._weights:
            return max(self._weights)
        elif self._terminfo is not None:
            return self._terminfo.max_weight()
        else:
            return 1.0

    def score(self):
        if self._scorer:
            return self._scorer.score(self)
        else:
            return self.weight()