Source

whoosh / tests / test_matching.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
from __future__ import with_statement
from random import randint, choice, sample

from whoosh import fields, matching, qparser, query
from whoosh.compat import b, u, xrange, permutations
from whoosh.formats import Posting
from whoosh.query import And, Term
from whoosh.scoring import WeightScorer
from whoosh.util import make_binary_tree
from whoosh.util.testing import TempIndex


def _keys(searcher, docnums):
    return sorted([searcher.stored_fields(docnum)['key']
                   for docnum in docnums])


def test_nullmatcher():
    nm = matching.NullMatcher()
    assert not nm.is_active()
    assert list(nm.all_ids()) == []


def make_matcher(docids, **kwargs):
    return matching.ListMatcher([Posting(id=n) for n in docids], **kwargs)


def test_listmatcher():
    lm = make_matcher([1, 2, 5, 9, 10])
    ls = []
    while lm.is_active():
        ls.append((lm.id(), lm.score()))
        lm.next()
    assert ls == [(1, 1.0), (2, 1.0), (5, 1.0), (9, 1.0), (10, 1.0)]

    lm = make_matcher([1, 2, 5, 9, 10])
    assert list(lm.all_ids()) == [1, 2, 5, 9, 10]

    lm = make_matcher([1, 2, 5, 9, 10], position=3)
    ls = []
    while lm.is_active():
        ls.append(lm.id())
        lm.next()
    assert ls == [9, 10]

    lm = make_matcher([1, 2, 5, 9, 10])
    for _ in xrange(3):
        lm.next()
    lm = lm.copy()
    ls = []
    while lm.is_active():
        ls.append(lm.id())
        lm.next()
    assert ls == [9, 10]


def test_listmatcher_skip_to_quality_identical_scores():
    lm = make_matcher([1, 2, 5, 9, 10], scorer=WeightScorer(1.0))
    lm.skip_to_quality(0.3)
    ls = []
    while lm.is_active():
        ls.append((lm.id(), lm.score()))
        lm.next()
    assert ls == [(1, 1.0), (2, 1.0), (5, 1.0), (9, 1.0), (10, 1.0)]


def test_wrapper():
    wm = matching.WrappingMatcher(make_matcher([1, 2, 5, 9, 10]),
                                  boost=2.0)
    ls = []
    while wm.is_active():
        ls.append((wm.id(), wm.score()))
        wm.next()
    assert ls == [(1, 2.0), (2, 2.0), (5, 2.0), (9, 2.0), (10, 2.0)]

    wm = matching.WrappingMatcher(make_matcher([1, 2, 5, 9, 10]), boost=2.0)
    assert list(wm.all_ids()) == [1, 2, 5, 9, 10]


def test_filter():

    fm = matching.FilterMatcher(make_matcher(xrange(2, 10)),
                                frozenset([3, 9]))
    assert list(fm.all_ids()) == [3, 9]

    fm = matching.FilterMatcher(make_matcher(xrange(2, 10)),
                                frozenset([1, 5, 9, 13]))
    assert list(fm.all_ids()) == [5, 9]


def test_exclude():
    em = matching.FilterMatcher(make_matcher([1, 2, 5, 9, 10]),
                                frozenset([2, 9]), exclude=True)
    assert list(em.all_ids()) == [1, 5, 10]

    em = matching.FilterMatcher(make_matcher([1, 2, 5, 9, 10]),
                                frozenset([2, 9]), exclude=True)
    assert list(em.all_ids()) == [1, 5, 10]

    em = matching.FilterMatcher(make_matcher([1, 2, 5, 9, 10]),
                                frozenset([2, 9]), exclude=True)
    em.next()
    em.next()
    em = em.copy()
    ls = []
    while em.is_active():
        ls.append(em.id())
        em.next()
    assert ls == [10]


def test_simple_union():
    lm1 = make_matcher([1, 4, 10, 20, 90])
    lm2 = make_matcher([0, 4, 20])
    um = matching.UnionMatcher(lm1, lm2)
    ls = []
    while um.is_active():
        ls.append((um.id(), um.score()))
        um.next()
    assert ls == [(0, 1.0), (1, 1.0), (4, 2.0), (10, 1.0), (20, 2.0), (90, 1.0)]

    lm1 = make_matcher([1, 4, 10, 20, 90])
    lm2 = make_matcher([0, 4, 20])
    um = matching.UnionMatcher(lm1, lm2)
    assert list(um.all_ids()) == [0, 1, 4, 10, 20, 90]

    lm1 = make_matcher([1, 4, 10, 20, 90])
    lm2 = make_matcher([0, 4, 20])
    um = matching.UnionMatcher(lm1, lm2)
    um.next()
    um.next()
    um = um.copy()
    ls = []
    while um.is_active():
        ls.append(um.id())
        um.next()
    assert ls == [4, 10, 20, 90]


def test_simple_intersection():
    lm1 = make_matcher([1, 4, 10, 20, 90])
    lm2 = make_matcher([0, 4, 20])
    im = matching.IntersectionMatcher(lm1, lm2)
    ls = []
    while im.is_active():
        ls.append((im.id(), im.score()))
        im.next()
    assert ls == [(4, 2.0), (20, 2.0)]

    lm1 = make_matcher([1, 4, 10, 20, 90])
    lm2 = make_matcher([0, 4, 20])
    im = matching.IntersectionMatcher(lm1, lm2)
    assert list(im.all_ids()) == [4, 20]

    lm1 = make_matcher([1, 4, 10, 20, 90])
    lm2 = make_matcher([0, 4, 20])
    im = matching.IntersectionMatcher(lm1, lm2)
    im.next()
    im.next()
    im = im.copy()
    ls = []
    while im.is_active():
        ls.append(im.id())
        im.next()
    assert not ls


def test_andnot():
    lm1 = make_matcher([1, 4, 10, 20, 90])
    lm2 = make_matcher([0, 4, 20])
    anm = matching.AndNotMatcher(lm1, lm2)
    ls = []
    while anm.is_active():
        ls.append((anm.id(), anm.score()))
        anm.next()
    assert ls == [(1, 1.0), (10, 1.0), (90, 1.0)]

    echo_lm = make_matcher([0, 1, 2, 3, 4])
    bravo_lm = make_matcher([0, 1])
    anm = matching.AndNotMatcher(echo_lm, bravo_lm)
    assert list(anm.all_ids()) == [2, 3, 4]

    lm1 = make_matcher([1, 4, 10, 20, 90])
    lm2 = make_matcher([0, 4, 20])
    anm = matching.AndNotMatcher(lm1, lm2)
    assert list(anm.all_ids()) == [1, 10, 90]

    lm1 = make_matcher([1, 4, 10, 20, 90])
    lm2 = make_matcher([0, 4, 20])
    anm = matching.AndNotMatcher(lm1, lm2)
    anm.next()
    anm.next()
    anm = anm.copy()
    ls = []
    while anm.is_active():
        ls.append(anm.id())
        anm.next()
    assert ls == [90]


def test_require():
    lm1 = make_matcher([1, 4, 10, 20, 90])
    lm2 = make_matcher([0, 4, 20])
    rm = matching.RequireMatcher(lm1, lm2)
    ls = []
    while rm.is_active():
        ls.append((rm.id(), rm.score()))
        rm.next()
    assert ls == [(4, 1.0), (20, 1.0)]

    lm1 = make_matcher([1, 4, 10, 20, 90])
    lm2 = make_matcher([0, 4, 20])
    rm = matching.RequireMatcher(lm1, lm2)
    assert list(rm.all_ids()) == [4, 20]

    lm1 = make_matcher([1, 4, 10, 20, 90])
    lm2 = make_matcher([0, 4, 20])
    rm = matching.RequireMatcher(lm1, lm2)
    rm.next()
    rm.next()
    rm = rm.copy()
    ls = []
    while rm.is_active():
        ls.append(rm.id())
        rm.next()
    assert not ls


def test_andmaybe():
    lm1 = make_matcher([1, 4, 10, 20, 90])
    lm2 = make_matcher([0, 4, 20])
    amm = matching.AndMaybeMatcher(lm1, lm2)
    ls = []
    while amm.is_active():
        ls.append((amm.id(), amm.score()))
        amm.next()
    assert ls == [(1, 1.0), (4, 2.0), (10, 1.0), (20, 2.0), (90, 1.0)]

    lm1 = make_matcher([1, 4, 10, 20, 90])
    lm2 = make_matcher([0, 4, 20])
    amm = matching.AndMaybeMatcher(lm1, lm2)
    assert list(amm.all_ids()) == [1, 4, 10, 20, 90]

    lm1 = make_matcher([1, 4, 10, 20, 90])
    lm2 = make_matcher([0, 4, 20])
    amm = matching.AndMaybeMatcher(lm1, lm2)
    amm.next()
    amm.next()
    amm = amm.copy()
    ls = []
    while amm.is_active():
        ls.append(amm.id())
        amm.next()
    assert ls == [10, 20, 90]


def test_intersection():
    schema = fields.Schema(key=fields.ID(stored=True),
                           value=fields.TEXT(stored=True))
    with TempIndex(schema, "intersect") as ix:
        with ix.writer() as w:
            w.add_document(key=u"a", value=u"alpha bravo charlie delta")
            w.add_document(key=u"b", value=u"echo foxtrot alpha bravo")
            w.add_document(key=u"c", value=u"charlie delta golf hotel")

        with ix.writer() as w:
            w.add_document(key=u"d", value=u"india alpha bravo charlie")
            w.add_document(key=u"e", value=u"delta bravo india bravo")

        with ix.searcher() as s:
            q = And([Term("value", u"bravo"), Term("value", u"delta")])
            m = q.matcher(s)
            assert _keys(s, m.all_ids()) == ["a", "e"]

            q = And([Term("value", u"bravo"), Term("value", u"alpha")])
            m = q.matcher(s)
            assert _keys(s, m.all_ids()) == ["a", "b", "d"]


def test_random_intersections():
    domain = [u"alpha", u"bravo", u"charlie", u"delta", u"echo",
              u"foxtrot", u"golf", u"hotel", u"india", u"juliet",
              u"kilo", u"lima", u"mike"]
    docsperseg = 50
    fieldlimits = (3, 10)
    docs = []

    schema = fields.Schema(key=fields.NUMERIC(stored=True),
                           value=fields.TEXT(stored=True))
    with TempIndex(schema, "randintersect") as ix:
        # Create docsperseg * segments documents containing random words from
        # the domain list. Add the documents to the index, but also keep them
        # in the "documents" list for the sanity check
        with ix.writer() as w:
            for i in xrange(docsperseg):
                # Create a string of random words
                doc = u" ".join(choice(domain)
                                  for _ in xrange(randint(*fieldlimits)))
                # Add the string to the index
                docid = w.add_document(key=i, value=doc)
                # Add a (docnum, string) tuple to the documents list
                docs.append((i, doc))

        testcount = 20
        testlimits = (2, 5)

        with ix.searcher() as s:
            for _ in xrange(testcount):
                # Create a random list of words and manually do an intersection
                # of items in "documents" that contain the words ("target")
                words = sample(domain, randint(*testlimits))
                keys = []
                for key, doc in docs:
                    if all((doc.find(w) > -1) for w in words):
                        keys.append(key)
                target = [s.document_number(key=key) for key in keys]
                target.sort()

                # Create a query from the list of words and get two matchers
                # from it
                q = And([Term("value", w) for w in words])
                m1 = q.matcher(s)
                m2 = q.matcher(s)

                # Try getting the list of IDs from all_ids()
                ids1 = list(m1.all_ids())

                # Try getting the list of IDs using id()/next()
                ids2 = []
                while m2.is_active():
                    ids2.append(m2.id())
                    m2.next()

                # Check that the two methods return the same list
                assert ids1 == ids2

                # Check that the IDs match the ones we manually calculated
                assert _keys(s, ids1) == target


def test_union():
    s1 = make_matcher([1, 2, 3, 4, 5, 6, 7, 8])
    s2 = make_matcher([2, 4, 8, 10, 20, 30])
    s3 = make_matcher([10, 100, 200])
    target = [1, 2, 3, 4, 5, 6, 7, 8, 10, 20, 30, 100, 200]
    um = matching.UnionMatcher(s1, matching.UnionMatcher(s2, s3))
    assert target == list(um.all_ids())


def test_union_scores():
    s1 = make_matcher([1, 2, 3])
    s2 = make_matcher([2, 4, 8])
    s3 = make_matcher([2, 3, 8])
    target = [(1, 1.0), (2, 3.0), (3, 2.0), (4, 1.0), (8, 2.0)]
    um = matching.UnionMatcher(s1, matching.UnionMatcher(s2, s3))
    result = []
    while um.is_active():
        result.append((um.id(), um.score()))
        um.next()
    assert target == result


def test_random_union():
    testcount = 100
    rangelimits = (2, 10)
    clauselimits = (2, 10)

    vals = list(range(100))

    for _ in xrange(testcount):
        target = set()
        matchers = []
        for _ in xrange(randint(*clauselimits)):
            nums = sample(vals, randint(*rangelimits))
            target = target.union(nums)
            matchers.append(make_matcher(sorted(nums)))
        target = sorted(target)
        um = make_binary_tree(matching.UnionMatcher, matchers)
        assert list(um.all_ids()) == target


def test_inverse():
    s = make_matcher([1, 5, 10, 11, 13])
    inv = matching.InverseMatcher(s, 15)
    ids = []
    while inv.is_active():
        ids.append(inv.id())
        inv.next()
    assert ids == [0, 2, 3, 4, 6, 7, 8, 9, 12, 14]


def test_inverse_skip():
    s = make_matcher([1, 5, 10, 11, 13])
    inv = matching.InverseMatcher(s, 15)
    inv.skip_to(8)

    ids = []
    while inv.is_active():
        ids.append(inv.id())
        inv.next()
    assert ids == [8, 9, 12, 14]


def test_empty_andnot():
    pos = matching.NullMatcher()
    neg = matching.NullMatcher()
    anm = matching.AndNotMatcher(pos, neg)
    assert not anm.is_active()
    assert not list(anm.all_ids())

    pos = make_matcher([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
    neg = matching.NullMatcher()
    ans = matching.AndNotMatcher(pos, neg)
    ids = list(ans.all_ids())
    assert ids == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


def test_random_andnot():
    testcount = 100
    rangesize = 100

    rng = list(range(rangesize))

    for _ in xrange(testcount):
        negs = sorted(sample(rng, randint(0, rangesize - 1)))
        negset = frozenset(negs)
        matched = [n for n in rng if n not in negset]

        pos = make_matcher(rng)
        neg = make_matcher(negs)

        anm = matching.AndNotMatcher(pos, neg)
        ids = list(anm.all_ids())
        assert ids == matched


def test_current_terms():
    domain = u"alfa bravo charlie delta".split()
    schema = fields.Schema(text=fields.TEXT(stored=True))
    with TempIndex(schema, "currentterms") as ix:
        with ix.writer() as w:
            for ls in permutations(domain, 3):
                w.add_document(text=" ".join(ls), _stored_text=ls)

        with ix.searcher() as s:
            q = query.And([query.Term("text", "alfa"),
                           query.Term("text", "charlie")])
            m = q.matcher(s)

            while m.is_active():
                assert sorted(m.matching_terms()) == [("text", b"alfa"),
                                                      ("text", b"charlie")]
                m.next()


def test_exclusion():
    from datetime import datetime

    schema = fields.Schema(id=fields.ID(stored=True), date=fields.DATETIME)
    with TempIndex(schema, "exclusion") as ix:
        dt1 = datetime(1950, 1, 1)
        dt2 = datetime(1960, 1, 1)
        with ix.writer() as w:
            # Make 39 documents with dates != dt1 and then make a last document
            # with feed == dt1.
            for i in xrange(40):
                w.add_document(id=u(str(i)), date=(dt2 if i >= 1 else dt1))

        with ix.searcher() as s:
            qp = qparser.QueryParser("id", schema)
            # Find documents where date != dt1
            q = qp.parse("NOT (date:(19500101000000))")

            r = s.search(q, limit=None)
            assert r.total_length() == 39  # Total number of matched documents
            assert r.scored_length() == 39  # Number of docs in the results


def test_arrayunion():
    l1 = make_matcher([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])
    l2 = make_matcher([100, 200, 300, 400, 500, 600])
    aum = matching.ArrayUnionMatcher([l1, l2], 601, partsize=5)
    assert aum.id() == 10
    aum.skip_to(45)
    assert aum.id() == 50
    aum.skip_to(550)
    assert aum.id() == 600


def test_arrayunion2():
    l1 = make_matcher([1, 2])
    l2 = make_matcher([1, 2, 10, 20])
    l3 = make_matcher([1, 5, 10, 50])
    aum = matching.ArrayUnionMatcher([l1, l2, l3], 51, partsize=2)

    assert aum.id() == 1
    assert not l1.is_active()
    aum.skip_to(50)
    assert aum.id() == 50