1. Matt Chaput
  2. whoosh

Source

whoosh / src / whoosh / filedb / fileindex.py

The branch 'mpwrite' does not exist.
  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 2009 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.

import copy, re, sys
from datetime import datetime
from os import urandom
from time import time, sleep

from whoosh import __version__
from whoosh.compat import pickle, integer_types, string_type, iteritems
from whoosh.fields import ensure_schema, merge_schemas
from whoosh.index import Index, EmptyIndexError, IndexVersionError, _DEF_INDEX_NAME
from whoosh.reading import EmptyReader, MultiReader
from whoosh.store import Storage, LockError
from whoosh.system import _INT_SIZE, _FLOAT_SIZE, _LONG_SIZE
from whoosh.util import b64encode, b64decode


_INDEX_VERSION = -110


def _make_id():
    return urandom(12)

class Revision(object):
    def __init__(self, indexname, id, schema, segments=None,
                 release=None, created=None):
        self.indexname = indexname
        self.id = id
        self.schema = schema
        self.segments = segments or ()
        self.release = release
        self.created = created
    
    @staticmethod
    def _filename(indexname, id):
        i = b64encode(id)
        return "%s.%s.toc" % (indexname, i)
    
    @staticmethod
    def regex(indexname):
        pat = r"^%s\.(?P<id>.{16})\.toc$" % indexname
        return re.compile(pat)
    
    @classmethod
    def create(cls, storage, indexname, id, schema, segments=None):
        rev = cls(indexname, id, schema, segments)
        rev.store(storage)
        return rev
    
    @classmethod
    def load(cls, storage, indexname, id, schema=None):
        fname = cls._filename(indexname, id)
        stream = storage.open_file(fname)
    
        # Check size of data types
        def check_size(name, target):
            sz = stream.read_varint()
            if sz != target:
                raise IndexError("Index was created on different architecture:"
                                 " saved %s=%s, this computer=%s" % (name, sz, target))
        check_size("int", _INT_SIZE)
        check_size("long", _LONG_SIZE)
        check_size("float", _FLOAT_SIZE)
        
        # Check byte order
        if not stream.read_int() == -12345:
            raise IndexError("Number misread: byte order problem?")
        
        # Check format version data
        version = stream.read_int()
        if version != _INDEX_VERSION:
            raise IndexVersionError("Can't read format %s" % version, version)
        # Load Whoosh version that created this TOC
        release = stream.read_pickle()
        # Check that the filename and internal ID match
        _id = stream.read(12)
        if _id != id:
            raise Exception("ID in %s is %s" % (fname, b64encode(_id)))
        # Creation date
        created = stream.read_pickle()
        # If a schema was supplied, use it instead of reading the one on disk
        if schema:
            stream.skip_string()
        else:
            schema = pickle.loads(stream.read_string())
        # Load the segments
        segments = stream.read_pickle()
        stream.close()
        return cls(indexname, id, schema, segments, release, created)
    
    @classmethod
    def find_all(cls, storage, indexname):
        regex = cls.regex(indexname)
        for fname in storage:
            m = regex.match(fname)
            if m:
                yield b64decode(m.group("id"))
    
    @classmethod
    def load_all(cls, storage, indexname, schema=None, suppress=False):
        revs = []
        for id in cls.find_all(storage, indexname):
            try:
                revs.append(cls.load(storage, indexname, id, schema=schema))
            except OSError:
                if not suppress:
                    raise
        return sorted(revs, key=lambda x: x.created)
    
    def __repr__(self):
        return "<%s %s>" % (self.__class__.__name__, self.filename())
    
    def filename(self):
        return self._filename(self.indexname, self.id)
    
    def store(self, storage):
        schema = ensure_schema(self.schema)
        schema.clean()
        
        tocfilename = self.filename()
        tempfilename = '%s.%s' % (tocfilename, time())
        stream = storage.create_file(tempfilename)
        
        # Write the sizes of datatypes to check system compatibility
        stream.write_varint(_INT_SIZE)
        stream.write_varint(_LONG_SIZE)
        stream.write_varint(_FLOAT_SIZE)
        # Write a dummy value to check byte order
        stream.write_int(-12345)
        # Write the index format version and Whoosh version
        stream.write_int(_INDEX_VERSION)
        stream.write_pickle(__version__)
        # Write self
        stream.write(self.id)
        stream.write_pickle(datetime.utcnow())
        stream.write_string(pickle.dumps(self.schema, -1))
        stream.write_pickle(self.segments)
        stream.close()
        
        # Rename temporary file to the proper filename
        storage.rename_file(tempfilename, tocfilename, safe=True)
    
    def delete_files(self, storage, suppress=True):
        try:
            storage.delete_file(self.filename())
        except OSError:
            if not suppress:
                raise


class Segment(object):
    EXTENSIONS = {"dawg": "dag",
                  "fieldlengths": "fln",
                  "storedfields": "sto",
                  "termsindex": "trm",
                  "termposts": "pst",
                  "vectorindex": "vec",
                  "vectorposts": "vps"}
    
    def __init__(self, indexname, id, doccount=0, fieldlength_totals=None,
                 fieldlength_mins=None, fieldlength_maxes=None, deleted=None):
        self.indexname = indexname
        self.id = id
        self.doccount = doccount
        self.fieldlength_totals = fieldlength_totals or {}
        self.fieldlength_mins = fieldlength_mins or {}
        self.fieldlength_maxes = fieldlength_maxes or {}
        self.deleted = deleted
        
    @classmethod
    def _idstring(cls, segid):
        return b64encode(segid)
    
    @classmethod
    def _basename(cls, indexname, segid):
        return "%s.%s" % (indexname, cls._idstring(segid))
    
    @classmethod
    def _make_filename(cls, indexname, segid, ext):
        return "%s.%s" % (cls._basename(indexname, segid), ext)
    
    def __repr__(self):
        r = "<%s %s %d" % (self.__class__.__name__, b64encode(self.id), self.doccount)
        if self.deleted:
            r += " " + ",".join(str(docnum) for docnum in sorted(self.deleted))
        r += ">"
        return r

    def __getattr__(self, name):
        # Capture accesses to e.g. Segment.fieldlengths_filename and return
        # the appropriate filename
        ext = "_filename"
        if name.endswith(ext):
            basename = name[:0 - len(ext)]
            if basename in self.EXTENSIONS:
                return self.make_filename(self.EXTENSIONS[basename])
        
        raise AttributeError(name)
    
    def exists_in(self, storage):
        return any(storage.file_exists(self.make_filename(ext))
                   for ext in self.EXTENSIONS.values())
    
    def delete_files(self, storage, suppress=True):
        for ext in self.EXTENSIONS.values():
            fname = self.make_filename(ext)
            if storage.file_exists(fname):
                try:
                    storage.delete_file(fname)
                except OSError:
                    if not suppress:
                        raise
    
    def basename(self):
        return self._basename(self.indexname, self.id)

    def make_filename(self, ext):
        return self._make_filename(self.indexname, self.id, ext)
    
    def doc_count_all(self):
        """
        :returns: the total number of documents, DELETED OR UNDELETED, in this
            segment.
        """
        return self.doccount

    def doc_count(self):
        """
        :returns: the number of (undeleted) documents in this segment.
        """
        
        return self.doccount - self.deleted_count()

    def has_deletions(self):
        """
        :returns: True if any documents in this segment are deleted.
        """
        return self.deleted_count() > 0

    def deleted_count(self):
        """
        :returns: the total number of deleted documents in this segment.
        """
        if self.deleted is None:
            return 0
        return len(self.deleted)

    def field_length(self, fieldname, default=0):
        """Returns the total number of terms in the given field across all
        documents in this segment.
        """
        return self.fieldlength_totals.get(fieldname, default)

    def min_field_length(self, fieldname, default=0):
        """Returns the maximum length of the given field in any of the
        documents in the segment.
        """
        
        return self.fieldlength_mins.get(fieldname, default)

    def max_field_length(self, fieldname, default=0):
        """Returns the maximum length of the given field in any of the
        documents in the segment.
        """
        return self.fieldlength_maxes.get(fieldname, default)

    def delete_document(self, docnum, delete=True):
        """Deletes the given document number. The document is not actually
        removed from the index until it is optimized.

        :param docnum: The document number to delete.
        :param delete: If False, this undeletes a deleted document.
        """

        if delete:
            if self.deleted is None:
                self.deleted = set()
            self.deleted.add(docnum)
        elif self.deleted is not None and docnum in self.deleted:
            self.deleted.clear(docnum)

    def is_deleted(self, docnum):
        """:returns: True if the given document number is deleted."""

        if self.deleted is None:
            return False
        return docnum in self.deleted


def _create_index(storage, schema, indexname=_DEF_INDEX_NAME):
    # Clear existing files
    prefix = "%s." % indexname
    for filename in storage:
        if filename.startswith(prefix):
            storage.delete_file(filename)
    
    # Create and store the root revision
    schema = ensure_schema(schema)
    return Revision.create(storage, indexname, _make_id(), schema)


def segments_from_revs(revs):
    segs = []
    for rev in revs:
        segs.extend(rev.segments)
    return merge_segments(segs)


def merge_segments(segments):
    segs = []
    byid = {}
    # Merge the list of segments in each revision
    for seg in segments:
        if seg.id in byid:
            first = byid[seg.id]
            # Segment objects with the same id are identical except the
            # set of deleted documents... merge that
            if seg.deleted:
                if first.deleted is None:
                    first.deleted = seg.deleted
                else:
                    first.deleted.update(seg.deleted)
        else:
            # Make a copy so we can modify the deleted attr without
            # having to worry if the caller expected the list of revs
            # to remain unchanged
            seg = copy.copy(seg)
            byid[seg.id] = seg
            segs.append(seg)
    return segs


# Index placeholder object

class FileIndex(Index):
    def __init__(self, storage, schema=None, indexname=_DEF_INDEX_NAME):
        if not isinstance(storage, Storage):
            raise ValueError("%r is not a Storage object" % storage)
        if not isinstance(indexname, string_type):
            raise ValueError("indexname %r is not a string" % indexname)
        
        if schema:
            schema = ensure_schema(schema)
        
        self.storage = storage
        self.indexname = indexname
        self._schema = schema
        
        if len(self._revisions()) == 0:
            raise EmptyIndexError

    def __repr__(self):
        return "%s(%r, %r)" % (self.__class__.__name__,
                               self.storage, self.indexname)

    def close(self):
        pass

    def _revisions(self):
        return list(Revision.load_all(self.storage, self.indexname, suppress=True))
    
    def _segments(self):
        return segments_from_revs(self._revisions())

    # add_field
    # remove_field
    
    @staticmethod
    def _comp_id(revs):
        if len(revs) == 1:
            return revs[0].id
        else:
            return tuple(sorted(rev.id for rev in revs))
    
    def latest_generation(self):
        return self._comp_id(self._revisions())
    
    # refresh
    # up_to_date
    
    def last_modified(self):
        return max(rev.created for rev in self._revisions())

    def is_empty(self):
        return sum(len(rev.segments) for rev in self._revisions()) == 0
    
    def optimize(self):
        w = self.writer()
        w.commit(optimize=True)

    # searcher
    
    def writer(self, **kwargs):
        from whoosh.filedb.filewriting import SegmentWriter
        return SegmentWriter(self, **kwargs)

    def lock(self, name):
        """Returns a lock object that you can try to call acquire() on to
        lock the index.
        """
        
        return self.storage.lock(self.indexname + "_" + name)

    @property
    def schema(self):
        return (self._schema
                or merge_schemas([rev.schema for rev
                                  in self._revisions()]))

    def _read_segments(self, schema, segments, reuse=None):
        from whoosh.filedb.filereading import SegmentReader
        
        reusable = {}
        try:
            if len(segments) == 0:
                # This index has no segments! Return an EmptyReader object,
                # which simply returns empty or zero to every method
                return EmptyReader(schema)
            
            if reuse:
                # Put all atomic readers in a dictionary keyed by their
                # generation, so we can re-use them if them if possible
                readers = [r for r, _ in reuse.leaf_readers()]
                reusable = dict((r.generation(), r) for r in readers)
            
            # Make a function to open readers, which reuses reusable readers.
            # It removes any readers it reuses from the "reusable" dictionary,
            # so later we can close any readers left in the dictionary.
            def segreader(segment):
                segid = segment.id
                if segid in reusable:
                    r = reusable[segid]
                    del reusable[segid]
                    return r
                else:
                    return SegmentReader(self.storage, schema, segment)
            
            if len(segments) == 1:
                # This index has one segment, so return a SegmentReader object
                # for the segment
                return segreader(segments[0])
            else:
                # This index has multiple segments, so create a list of
                # SegmentReaders for the segments, then composite them with a
                # MultiReader
                
                readers = [segreader(segment) for segment in segments]
                gen = tuple(r.generation() for r in readers)
                return MultiReader(readers, generation=gen)
        finally:
            for r in reusable.values():
                r.close()

    def reader(self, reuse=None):
        retries = 10
        while retries > 0:
            # Read the information from the TOC file
            try:
                segments = self._segments()
                return self._read_segments(self.schema, segments, reuse=reuse)
            except IOError:
                # Presume that we got a "file not found error" because a writer
                # deleted one of the files just as we were trying to open it,
                # and so retry a few times before actually raising the
                # exception
                e = sys.exc_info()[1]
                retries -= 1
                if retries <= 0:
                    raise e
                sleep(0.05)