whoosh / src / whoosh / filedb / filewriting.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
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
# 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.

from __future__ import with_statement
from bisect import bisect_right
from collections import defaultdict

try:
    import sqlite3  #@UnusedImport
    has_sqlite = True
except ImportError:
    has_sqlite = False

from whoosh.compat import integer_types, iteritems, text_type
from whoosh.fields import merge_schemas, UnknownFieldError
from whoosh.filedb.fileindex import (Revision, Segment, segments_from_revs,
                                     _make_id)
from whoosh.filedb.filepostings import FilePostingWriter
from whoosh.filedb.filetables import (TermIndexWriter, StoredFieldWriter,
                                      TermVectorWriter)
from whoosh.filedb.pools import TempfilePool, DiskSet
from whoosh.store import LockError
from whoosh.support.dawg import DawgBuilder, flatten
from whoosh.support.filelock import try_for
from whoosh.util import fib
from whoosh.writing import IndexWriter, IndexingError


# Merge policies

# A merge policy is a callable that takes the Index object, the SegmentWriter
# object, and the current segment list (not including the segment being
# written), and returns an updated segment list (not including the segment
# being written).

def NO_MERGE(writer, segments):
    """This policy does not merge any existing segments.
    """
    return segments


def MERGE_SMALL(writer, segments):
    """This policy merges small segments, where "small" is defined using a
    heuristic based on the fibonacci sequence.
    """

    from whoosh.filedb.filereading import SegmentReader
    
    newsegments = []
    sorted_segment_list = sorted((s.doc_count_all(), s) for s in segments)
    total_docs = 0
    for i, (count, seg) in enumerate(sorted_segment_list):
        if count > 0:
            total_docs += count
            if total_docs < fib(i + 5):
                reader = SegmentReader(writer.storage, writer.schema, seg)
                writer.add_reader(reader)
                reader.close()
            else:
                newsegments.append(seg)
    return newsegments


def OPTIMIZE(writer, segments):
    """This policy merges all existing segments.
    """

    from whoosh.filedb.filereading import SegmentReader
    
    for seg in segments:
        reader = SegmentReader(writer.storage, writer.schema, seg)
        writer.add_reader(reader)
        reader.close()
    return []


def MERGE_SQUARES(writer, segments):
    """This is an alternative merge policy similar to Lucene's. It is less
    optimal than the default MERGE_SMALL.
    """
    
    from whoosh.filedb.filereading import SegmentReader
    
    sizedsegs = [(s.doc_count_all(), s) for s in segments]
    tomerge = []
    for size in (10, 100, 1000, 10000, 100000):
        smaller = [seg for segsize, seg in sizedsegs
                   if segsize < size - 1 and segsize >= size//10]
        if len(smaller) >= 10:
            tomerge.extend(smaller)
            for seg in smaller:
                segments.remove(seg)
    
    for seg in tomerge:
        reader = SegmentReader(writer.storage, writer.schema, seg)
        writer.add_reader(reader)
        reader.close()
    
    return segments


# Writer object

class SegmentWriter(IndexWriter):
    def __init__(self, ix, id=None, poolclass=None, procs=0, blocklimit=128,
                 timeout=0.0, delay=0.1, **poolargs):
        self._ix = ix
        self.mergelock = ix.lock("mergelock")
        self.storage = storage = ix.storage
        self.indexname = ix.indexname
        self.id = id if id is not None else _make_id()
        self.revs = list(ix._revisions())
        self.schema = ix._schema or merge_schemas([rev.schema for rev in self.revs])
        self.is_closed = False
        self.blocklimit = blocklimit
        self.timeout = timeout
        self.delay = delay
        self.docnum = 0
        self.fieldlength_totals = defaultdict(int)
        self._added = False
        
        # Pool
        if poolclass is None:
            if procs > 1:
                from whoosh.filedb.multiproc import MultiPool
                poolclass = MultiPool
            else:
                poolclass = TempfilePool
        self.pool = poolclass(self.schema, procs=procs, **poolargs)
        
        self.segments = segments_from_revs(self.revs)
        self._doc_offsets = []
        docbase = 0
        for seg in self.segments:
            self._doc_offsets.append(docbase)
            docbase += seg.doc_count_all()
        
        # Filenames
        newsegment = self._getsegment()
        self.dawgname = newsegment.dawg_filename
        self.termsname = newsegment.termsindex_filename
        self.postsname = newsegment.termposts_filename
        self.vectname = newsegment.vectorindex_filename
        self.vpostsname = newsegment.vectorposts_filename
        self.storedname = newsegment.storedfields_filename
        self.lengthsname = newsegment.fieldlengths_filename
        
        # Create files
        self.lengthfile = storage.create_file(self.lengthsname)
        self.storedfields = StoredFieldWriter(storage.create_file(self.storedname),
                                              self.schema.stored_names())
        # Terms writer
        self.wordsets = {}
        self.dawg = None
        if any(field.spelling for field in self.schema):
            self.dawgfile = storage.create_file(self.dawgname)
            self.dawg = DawgBuilder(field_root=True)
        ti = TermIndexWriter(storage.create_file(self.termsname))
        pw = FilePostingWriter(storage.create_file(self.postsname),
                               blocklimit=blocklimit)
        self.termswriter = TermsWriter(self.schema, ti, pw, self.dawg)
        
        # Vectors
        self.vectorindex = self.vpostwriter = None
        if self.schema.has_vectored_fields():
            # Vector index
            vf = storage.create_file(self.vectname)
            self.vectorindex = TermVectorWriter(vf)
            
            # Vector posting file
            vpf = storage.create_file(self.vpostsname)
            self.vpostwriter = FilePostingWriter(vpf, stringids=True)
    
    def _getsegment(self):
        return Segment(self.indexname, self.id, self.docnum,
                       self.pool.fieldlength_totals(),
                       self.pool.fieldlength_mins(),
                       self.pool.fieldlength_maxes())
    
    def _check_state(self):
        if self.is_closed:
            raise IndexingError("This writer is closed")
    
    def add_field(self, fieldname, fieldspec):
        self._check_state()
        if self._added:
            raise Exception("Can't modify schema after adding data to writer")
        super(SegmentWriter, self).add_field(fieldname, fieldspec)
    
    def remove_field(self, fieldname):
        self._check_state()
        if self._added:
            raise Exception("Can't modify schema after adding data to writer")
        super(SegmentWriter, self).remove_field(fieldname)
    
    def _document_segment(self, docnum):
        #Returns the index.Segment object containing the given document
        #number.

        offsets = self._doc_offsets
        if len(offsets) == 1:
            return 0
        return bisect_right(offsets, docnum) - 1

    def _segment_and_docnum(self, docnum):
        #Returns an (index.Segment, segment_docnum) pair for the segment
        #containing the given document number.

        segmentnum = self._document_segment(docnum)
        offset = self._doc_offsets[segmentnum]
        segment = self.segments[segmentnum]
        return segment, docnum - offset

    def has_deletions(self):
        """
        :returns: True if this index has documents that are marked deleted but
            haven't been optimized out of the index yet.
        """
        
        return any(s.has_deletions() for s in self.segments)

    def delete_document(self, docnum, delete=True):
        self._check_state()
        maxdoc = sum(seg.doccount for seg in self.segments)
        if docnum >= maxdoc:
            raise IndexingError("No document ID %r in this index (%d)" % (docnum, maxdoc))
        segment, segdocnum = self._segment_and_docnum(docnum)
        segment.delete_document(segdocnum, delete=delete)

    def deleted_count(self):
        """
        :returns: the total number of deleted documents in the index.
        """
        
        return sum(s.deleted_count() for s in self.segments)

    def is_deleted(self, docnum):
        segment, segdocnum = self._segment_and_docnum(docnum)
        return segment.is_deleted(segdocnum)

    def reader(self, reuse=None):
        self._check_state()
        return self._ix._read_segments(self.schema, self.segments, reuse=reuse)
    
    def add_reader(self, reader):
        self._check_state()
        startdoc = self.docnum
        
        has_deletions = reader.has_deletions()
        if has_deletions:
            docmap = {}
        
        fieldnames = set(self.schema.names())
        
        # Add stored documents, vectors, and field lengths
        for docnum in reader.all_doc_ids():
            if (not has_deletions) or (not reader.is_deleted(docnum)):
                d = dict(item for item
                         in iteritems(reader.stored_fields(docnum))
                         if item[0] in fieldnames)
                # We have to append a dictionary for every document, even if
                # it's empty.
                self.storedfields.append(d)
                
                if has_deletions:
                    docmap[docnum] = self.docnum
                
                for fieldname in reader.schema.scorable_names():
                    length = reader.doc_field_length(docnum, fieldname)
                    if length and fieldname in fieldnames:
                        self.pool.add_field_length(self.docnum, fieldname, length)
                
                for fieldname in reader.schema.vector_names():
                    if (fieldname in fieldnames
                        and reader.has_vector(docnum, fieldname)):
                        vpostreader = reader.vector(docnum, fieldname)
                        self._add_vector_reader(self.docnum, fieldname, vpostreader)
                
                self.docnum += 1
        
        # Add dawg contents to word sets for fields that require separate
        # handling
        for fieldname in self.schema.separate_spelling_names():
            if reader.has_word_graph(fieldname):
                graph = reader.word_graph(fieldname)
                self.add_spell_words(fieldname, flatten(graph))
        
        # Add postings
        for fieldname, text in reader.all_terms():
            if fieldname in fieldnames:
                postreader = reader.postings(fieldname, text)
                while postreader.is_active():
                    docnum = postreader.id()
                    valuestring = postreader.value()
                    if has_deletions:
                        newdoc = docmap[docnum]
                    else:
                        newdoc = startdoc + docnum
                    
                    self.pool.add_posting(fieldname, text, newdoc,
                                          postreader.weight(), valuestring)
                    postreader.next()
                    
        self._added = True
    
    def add_document(self, **fields):
        #from whoosh.util import now
        #t = now()
        self._check_state()
        schema = self.schema
        #ssnames = self.ssnames
        docboost = self._doc_boost(fields)
        
        # Sort the keys
        fieldnames = sorted([name for name in fields.keys()
                             if not name.startswith("_")])
        
        # Check if the caller gave us a bogus field
        for name in fieldnames:
            if name not in schema:
                raise UnknownFieldError("No field named %r in %s" % (name, schema))
        
        storedvalues = {}
        
        docnum = self.docnum
        for fieldname in fieldnames:
            value = fields.get(fieldname)
            if value is None:
                continue
            field = schema[fieldname]
            
            if field.indexed:
                fieldboost = self._field_boost(fields, fieldname, docboost)
                self.pool.add_content(docnum, fieldname, field, value,
                                      fieldboost)
            
            if field.separate_spelling():
                # This field requires spelling words to be added in a separate
                # step, instead of as part of indexing
                self.add_spell_words(fieldname, field.spellable_words(value))
            
            vformat = field.vector
            if vformat:
                wvs = vformat.word_values(value, field.analyzer, mode="index")
                vlist = sorted((w, weight, valuestring)
                               for w, _, weight, valuestring in wvs)
                self._add_vector(docnum, fieldname, vlist)
            
            if field.stored:
                # Caller can override the stored value by including a key
                # _stored_<fieldname>
                storedvalue = value
                storedname = "_stored_" + fieldname
                if storedname in fields:
                    storedvalue = fields[storedname]
                storedvalues[fieldname] = storedvalue
        
        self._added = True
        self.storedfields.append(storedvalues)
        self.docnum += 1
    
    #def update_document(self, **fields):
    
    def add_spell_words(self, fieldname, words):
        # Get or make a set for the words in this field
        if fieldname not in self.wordsets:
            self.wordsets[fieldname] = set()
        wordset = self.wordsets[fieldname]
        
        # If the in-memory set is getting big, replace it with an
        # on-disk set
        if has_sqlite and isinstance(wordset, set) and len(wordset) > 4096:
            diskset = DiskSet(wordset)
            self.wordsets[fieldname] = wordset = diskset
        
        for word in words:
            wordset.add(word)
            
        self._added = True
    
    def _add_wordsets(self):
        dawg = self.dawg
        for fieldname in self.wordsets:
            ws = self.wordsets[fieldname]
            ft = (fieldname, )
            
            words = sorted(ws) if isinstance(ws, set) else iter(ws)
            for text in words:
                dawg.insert(ft + tuple(text))
            
            if isinstance(ws, DiskSet):
                ws.destroy()
    
    def _add_vector(self, docnum, fieldname, vlist):
        vpostwriter = self.vpostwriter
        offset = vpostwriter.start(self.schema[fieldname].vector)
        for text, weight, valuestring in vlist:
            assert isinstance(text, text_type), "%r is not unicode" % text
            vpostwriter.write(text, weight, valuestring, 0)
        vpostwriter.finish()
        
        self.vectorindex.add((docnum, fieldname), offset)
    
    def _add_vector_reader(self, docnum, fieldname, vreader):
        vpostwriter = self.vpostwriter
        offset = vpostwriter.start(self.schema[fieldname].vector)
        while vreader.is_active():
            # text, weight, valuestring, fieldlen
            vpostwriter.write(vreader.id(), vreader.weight(), vreader.value(), 0)
            vreader.next()
        vpostwriter.finish()
        
        self.vectorindex.add((docnum, fieldname), offset)
    
    def _close_all(self, delete=False):
        self.is_closed = True
        self.termswriter.close()
        self.storedfields.close()
        if not self.lengthfile.is_closed:
            self.lengthfile.close()
        if self.vectorindex:
            self.vectorindex.close()
        if self.vpostwriter:
            self.vpostwriter.close()
    
    def _delete_files(self):
        storage = self.storage
        def rem(name):
            if storage.file_exists(name):
                storage.delete_file(name)
        rem(self.dawgname)
        rem(self.termsname)
        rem(self.postsname)
        rem(self.vectname)
        rem(self.vpostsname)
        rem(self.storedname)
        rem(self.lengthsname)
    
    def commit(self, mergetype=None, optimize=False, merge=True):
        """Finishes writing and saves all additions and changes to disk.
        
        There are four possible ways to use this method::
        
            # Merge small segments but leave large segments, trying to
            # balance fast commits with fast searching:
            writer.commit()
        
            # Merge all segments into a single segment:
            writer.commit(optimize=True)
            
            # Don't merge any existing segments:
            writer.commit(merge=False)
            
            # Use a custom merge function
            writer.commit(mergetype=my_merge_function)
        
        :param mergetype: a custom merge function taking a Writer object and
            segment list as arguments, and returning a new segment list. If you
            supply a ``mergetype`` function, the values of the ``optimize`` and
            ``merge`` arguments are ignored.
        :param optimize: if True, all existing segments are merged with the
            documents you've added to this writer (and the value of the
            ``merge`` argument is ignored).
        :param merge: if False, do not merge small segments.
        """
        
        self._check_state()
        segments = self.segments
        if merge:
            # Try to acquire the merge lock
            to, delay = self.timeout, self.delay
            gotlock = try_for(self.mergelock.acquire, timeout=to, delay=delay)
            if gotlock:
                try:
                    if mergetype:
                        pass
                    elif optimize:
                        mergetype = OPTIMIZE
                    else:
                        mergetype = MERGE_SMALL
                    
                    # Check that the segments we started with still exist
                    segments = [seg for seg in segments
                                if seg.exists_in(self.storage)]
                    # Remember the IDs of the pre-merged segments
                    orig_ids = set(seg.id for seg in segments)
                    # Call the merge policy function. The policy may choose to
                    # merge other segments into this writer's pool
                    new_segments = mergetype(self, segments)
                    # Find which segments got merged
                    merged_ids = orig_ids - set(seg.id for seg in new_segments)
                    
                    # Delete leftover files
                    for rev in self.revs:
                        rev.delete_files(self.storage)
                    for seg in segments:
                        if seg.id in merged_ids:
                            seg.delete_files(self.storage)
                    segments = new_segments
                finally:
                    self.mergelock.release()
        
        if self._added:
            # Tell the pool we're finished adding information, it should
            # add its accumulated data to the lengths, terms index, and
            # posting files.
            self.pool.finish(self.termswriter, self.docnum, self.lengthfile)
            
            # Write out spelling files
            if self.dawg:
                # Insert any wordsets we've accumulated into the word graph
                self._add_wordsets()
                # Write out the word graph
                self.dawg.write(self.dawgfile)
            
            # Create a Segment object for the segment created by this
            # writer and add it to the list of new segments
            thissegment = self._getsegment()
            segments.append(thissegment)
            
            # Close all files
            self._close_all()
        else:
            self.pool.cleanup()
        
        # Write new revision
        return Revision.create(self.storage, self.indexname, self.id,
                               self.schema, segments)
        
    def cancel(self):
        self._check_state()
        self.pool.cancel()
        self._close_all()
        self._delete_files()


class TermsWriter(object):
    def __init__(self, schema, termsindex, postwriter, dawg, inlinelimit=1):
        self.schema = schema
        # This file maps terms to TermInfo structures
        self.termsindex = termsindex
        
        # This object writes postings to the posting file and keeps track of
        # blocks
        self.postwriter = postwriter
        
        # Spelling
        self.dawg = dawg
        
        # Posting lists with <= this number of postings will be inlined into
        # the terms index instead of being written to the posting file
        assert isinstance(inlinelimit, integer_types)
        self.inlinelimit = inlinelimit
        
        self.spelling = False
        self.lastfn = None
        self.lasttext = None
        self.format = None
        self.offset = None
        
    def _new_term(self, fieldname, text):
        # This method tests whether a new field/term has started in the stream
        # of incoming postings, and if so performs appropriate work
        
        lastfn = self.lastfn or ''
        lasttext = self.lasttext or ''
        
        if fieldname < lastfn or (fieldname == lastfn and text < lasttext):
            raise Exception("Postings are out of order: %r:%s .. %r:%s" %
                            (lastfn, lasttext, fieldname, text))
    
        # Is the fieldname of this posting different from the last one?
        if fieldname != lastfn:
            # Store information we need about the new field
            field = self.schema[fieldname]
            self.format = field.format
            self.spelling = field.spelling and not field.separate_spelling()
        
        # Is the term of this posting different from the last one?
        if fieldname != lastfn or text != lasttext:
            # Finish up the last term before starting a new one
            self._finish_term()
            
            # If this field has spelling, add the term to the word graph
            if self.spelling:
                self.dawg.insert((fieldname, ) + tuple(text))
                
            # Set up internal state for the new term
            self.offset = self.postwriter.start(self.format)
            self.lasttext = text
            self.lastfn = fieldname
    
    def _finish_term(self):
        postwriter = self.postwriter
        if self.lasttext is not None:
            terminfo = postwriter.finish(self.inlinelimit)
            self.termsindex.add((self.lastfn, self.lasttext), terminfo)
    
    def add_postings(self, fieldname, text, matcher, getlen, offset=0,
                     docmap=None):
        self._new_term(fieldname, text)
        postwrite = self.postwriter.write
        while matcher.is_active():
            docnum = matcher.id()
            weight = matcher.weight()
            valuestring = matcher.value()
            if docmap:
                newdoc = docmap[docnum]
            else:
                newdoc = offset + docnum
            postwrite(newdoc, weight, valuestring, getlen(docnum, fieldname))
            matcher.next()
    
    def add_iter(self, postiter, getlen, offset=0, docmap=None):
        _new_term = self._new_term
        postwrite = self.postwriter.write
        for fieldname, text, docnum, weight, valuestring in postiter:
            _new_term(fieldname, text)
            if docmap:
                newdoc = docmap[docnum]
            else:
                newdoc = offset + docnum
            postwrite(newdoc, weight, valuestring, getlen(docnum, fieldname))
    
    def add(self, fieldname, text, docnum, weight, valuestring, fieldlen):
        self._new_term(fieldname, text)
        self.postwriter.write(docnum, weight, valuestring, fieldlen)
        
    def close(self):
        self._finish_term()
        self.termsindex.close()
        self.postwriter.close()


# Retroactively add spelling files to an existing index

def add_spelling(ix, fieldnames, commit=True):
    """Adds spelling files to an existing index that was created without
    them, and modifies the schema so the given fields have the ``spelling``
    attribute. Only works on filedb indexes.
    
    >>> ix = index.open_dir("testindex")
    >>> add_spelling(ix, ["content", "tags"])
    
    :param ix: a :class:`whoosh.filedb.fileindex.FileIndex` object.
    :param fieldnames: a list of field names to create word graphs for.
    :param force: if True, overwrites existing word graph files. This is only
        useful for debugging.
    """
    
    from whoosh.filedb.filereading import SegmentReader
    
    writer = ix.writer()
    storage = writer.storage
    schema = writer.schema
    segments = writer.segments
    
    for segment in segments:
        filename = segment.dawg_filename
        r = SegmentReader(storage, schema, segment)
        f = storage.create_file(filename)
        dawg = DawgBuilder(field_root=True)
        for fieldname in fieldnames:
            ft = (fieldname, )
            for word in r.lexicon(fieldname):
                dawg.insert(ft + tuple(word))
        dawg.write(f)
    
    for fieldname in fieldnames:
        schema[fieldname].spelling = True
    
    if commit:
        writer.commit(merge=False)
        
            
        
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.