-
Notifications
You must be signed in to change notification settings - Fork 641
/
IndexWriter.cs
6488 lines (6016 loc) · 266 KB
/
IndexWriter.cs
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
using J2N;
using J2N.Threading.Atomic;
using Lucene.Net.Diagnostics;
using Lucene.Net.Support;
using Lucene.Net.Support.Threading;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Text;
using System.Threading;
using JCG = J2N.Collections.Generic;
namespace Lucene.Net.Index
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Analyzer = Lucene.Net.Analysis.Analyzer;
using BytesRef = Lucene.Net.Util.BytesRef;
using Codec = Lucene.Net.Codecs.Codec;
using CompoundFileDirectory = Lucene.Net.Store.CompoundFileDirectory;
using Constants = Lucene.Net.Util.Constants;
using Directory = Lucene.Net.Store.Directory;
using FieldNumbers = Lucene.Net.Index.FieldInfos.FieldNumbers;
using IBits = Lucene.Net.Util.IBits;
using InfoStream = Lucene.Net.Util.InfoStream;
using IOContext = Lucene.Net.Store.IOContext;
using IOUtils = Lucene.Net.Util.IOUtils;
using Lock = Lucene.Net.Store.Lock;
using LockObtainFailedException = Lucene.Net.Store.LockObtainFailedException;
using Lucene3xCodec = Lucene.Net.Codecs.Lucene3x.Lucene3xCodec;
using Lucene3xSegmentInfoFormat = Lucene.Net.Codecs.Lucene3x.Lucene3xSegmentInfoFormat;
using MergeInfo = Lucene.Net.Store.MergeInfo;
using Query = Lucene.Net.Search.Query;
using TrackingDirectoryWrapper = Lucene.Net.Store.TrackingDirectoryWrapper;
/// <summary>
/// An <see cref="IndexWriter"/> creates and maintains an index.
/// </summary>
/// <remarks>
/// <para>The <see cref="OpenMode"/> option on
/// <see cref="IndexWriterConfig.OpenMode"/> determines
/// whether a new index is created, or whether an existing index is
/// opened. Note that you can open an index with <see cref="OpenMode.CREATE"/>
/// even while readers are using the index. The old readers will
/// continue to search the "point in time" snapshot they had opened,
/// and won't see the newly created index until they re-open. If
/// <see cref="OpenMode.CREATE_OR_APPEND"/> is used <see cref="IndexWriter"/> will create a
/// new index if there is not already an index at the provided path
/// and otherwise open the existing index.</para>
///
/// <para>In either case, documents are added with <see cref="AddDocument(IEnumerable{IIndexableField})"/>
/// and removed with <see cref="DeleteDocuments(Term)"/> or
/// <see cref="DeleteDocuments(Query)"/>. A document can be updated with
/// <see cref="UpdateDocument(Term, IEnumerable{IIndexableField})"/> (which just deletes
/// and then adds the entire document). When finished adding, deleting
/// and updating documents, <see cref="Dispose()"/> should be called.</para>
///
/// <a name="flush"></a>
/// <para>These changes are buffered in memory and periodically
/// flushed to the <see cref="Store.Directory"/> (during the above method
/// calls). A flush is triggered when there are enough added documents
/// since the last flush. Flushing is triggered either by RAM usage of the
/// documents (see <see cref="LiveIndexWriterConfig.RAMBufferSizeMB"/>) or the
/// number of added documents (see <see cref="LiveIndexWriterConfig.MaxBufferedDocs"/>).
/// The default is to flush when RAM usage hits
/// <see cref="IndexWriterConfig.DEFAULT_RAM_BUFFER_SIZE_MB"/> MB. For
/// best indexing speed you should flush by RAM usage with a
/// large RAM buffer. Additionally, if <see cref="IndexWriter"/> reaches the configured number of
/// buffered deletes (see <see cref="LiveIndexWriterConfig.MaxBufferedDeleteTerms"/>)
/// the deleted terms and queries are flushed and applied to existing segments.
/// In contrast to the other flush options <see cref="LiveIndexWriterConfig.RAMBufferSizeMB"/> and
/// <see cref="LiveIndexWriterConfig.MaxBufferedDocs"/>, deleted terms
/// won't trigger a segment flush. Note that flushing just moves the
/// internal buffered state in <see cref="IndexWriter"/> into the index, but
/// these changes are not visible to <see cref="IndexReader"/> until either
/// <see cref="Commit()"/> or <see cref="Dispose()"/> is called. A flush may
/// also trigger one or more segment merges which by default
/// run with a background thread so as not to block the
/// addDocument calls (see <a href="#mergePolicy">below</a>
/// for changing the <see cref="mergeScheduler"/>).</para>
///
/// <para>Opening an <see cref="IndexWriter"/> creates a lock file for the directory in use. Trying to open
/// another <see cref="IndexWriter"/> on the same directory will lead to a
/// <see cref="LockObtainFailedException"/>. The <see cref="LockObtainFailedException"/>
/// is also thrown if an <see cref="IndexReader"/> on the same directory is used to delete documents
/// from the index.</para>
///
/// <a name="deletionPolicy"></a>
/// <para>Expert: <see cref="IndexWriter"/> allows an optional
/// <see cref="IndexDeletionPolicy"/> implementation to be
/// specified. You can use this to control when prior commits
/// are deleted from the index. The default policy is
/// <see cref="KeepOnlyLastCommitDeletionPolicy"/> which removes all prior
/// commits as soon as a new commit is done (this matches
/// behavior before 2.2). Creating your own policy can allow
/// you to explicitly keep previous "point in time" commits
/// alive in the index for some time, to allow readers to
/// refresh to the new commit without having the old commit
/// deleted out from under them. This is necessary on
/// filesystems like NFS that do not support "delete on last
/// close" semantics, which Lucene's "point in time" search
/// normally relies on. </para>
///
/// <a name="mergePolicy"></a> <para>Expert:
/// <see cref="IndexWriter"/> allows you to separately change
/// the <see cref="mergePolicy"/> and the <see cref="mergeScheduler"/>.
/// The <see cref="mergePolicy"/> is invoked whenever there are
/// changes to the segments in the index. Its role is to
/// select which merges to do, if any, and return a
/// <see cref="MergePolicy.MergeSpecification"/> describing the merges.
/// The default is <see cref="LogByteSizeMergePolicy"/>. Then, the
/// <see cref="MergeScheduler"/> is invoked with the requested merges and
/// it decides when and how to run the merges. The default is
/// <see cref="ConcurrentMergeScheduler"/>. </para>
///
/// <a name="OOME"></a><para><b>NOTE</b>: if you hit an
/// <see cref="OutOfMemoryException"/> then <see cref="IndexWriter"/> will quietly record this
/// fact and block all future segment commits. This is a
/// defensive measure in case any internal state (buffered
/// documents and deletions) were corrupted. Any subsequent
/// calls to <see cref="Commit()"/> will throw an
/// <see cref="InvalidOperationException"/>. The only course of action is to
/// call <see cref="Dispose()"/>, which internally will call
/// <see cref="Rollback()"/>, to undo any changes to the index since the
/// last commit. You can also just call <see cref="Rollback()"/>
/// directly.</para>
///
/// <a name="thread-safety"></a><para><b>NOTE</b>:
/// <see cref="IndexWriter"/> instances are completely thread
/// safe, meaning multiple threads can call any of its
/// methods, concurrently. If your application requires
/// external synchronization, you should <b>not</b>
/// synchronize on the <see cref="IndexWriter"/> instance as
/// this may cause deadlock; use your own (non-Lucene) objects
/// instead. </para>
///
/// <para><b>NOTE</b>:
/// Do not use <see cref="Thread.Interrupt()"/> on a thread that's within
/// <see cref="IndexWriter"/>, as .NET will throw <see cref="ThreadInterruptedException"/> on any
/// wait, sleep, or join including any lock statement with contention on it.
/// As a result, it is not practical to try to support <see cref="Thread.Interrupt()"/> due to the
/// chance <see cref="ThreadInterruptedException"/> could potentially be thrown in the middle of a
/// <see cref="Commit()"/> or somewhere in the application that will cause a deadlock.</para>
/// <para>
/// We recommend using another shutdown mechanism to safely cancel a parallel operation.
/// See: <a href="https://github.com/apache/lucenenet/issues/526">https://github.com/apache/lucenenet/issues/526</a>.
/// </para>
/// </remarks>
/*
* Clarification: Check Points (and commits)
* IndexWriter writes new index files to the directory without writing a new segments_N
* file which references these new files. It also means that the state of
* the in memory SegmentInfos object is different than the most recent
* segments_N file written to the directory.
*
* Each time the SegmentInfos is changed, and matches the (possibly
* modified) directory files, we have a new "check point".
* If the modified/new SegmentInfos is written to disk - as a new
* (generation of) segments_N file - this check point is also an
* IndexCommit.
*
* A new checkpoint always replaces the previous checkpoint and
* becomes the new "front" of the index. this allows the IndexFileDeleter
* to delete files that are referenced only by stale checkpoints.
* (files that were created since the last commit, but are no longer
* referenced by the "front" of the index). For this, IndexFileDeleter
* keeps track of the last non commit checkpoint.
*/
public class IndexWriter : IDisposable, ITwoPhaseCommit
{
private const int UNBOUNDED_MAX_MERGE_SEGMENTS = -1;
/// <summary>
/// Name of the write lock in the index.
/// </summary>
public static readonly string WRITE_LOCK_NAME = "write.lock";
/// <summary>
/// Key for the source of a segment in the <see cref="SegmentInfo.Diagnostics"/>. </summary>
public static readonly string SOURCE = "source";
/// <summary>
/// Source of a segment which results from a merge of other segments. </summary>
public static readonly string SOURCE_MERGE = "merge";
/// <summary>
/// Source of a segment which results from a flush. </summary>
public static readonly string SOURCE_FLUSH = "flush";
/// <summary>
/// Source of a segment which results from a call to <see cref="AddIndexes(IndexReader[])"/>. </summary>
public static readonly string SOURCE_ADDINDEXES_READERS = "AddIndexes(params IndexReader[] readers)";
/// <summary>
/// Absolute hard maximum length for a term, in bytes once
/// encoded as UTF8. If a term arrives from the analyzer
/// longer than this length, an
/// <see cref="ArgumentException"/> is thrown
/// and a message is printed to <see cref="infoStream"/>, if set (see
/// <see cref="IndexWriterConfig.SetInfoStream(InfoStream)"/>).
/// </summary>
public static readonly int MAX_TERM_LENGTH = DocumentsWriterPerThread.MAX_TERM_LENGTH_UTF8;
private volatile bool hitOOM;
private readonly Directory directory; // where this index resides
private readonly Analyzer analyzer; // how to analyze text
private long changeCount; // increments every time a change is completed
private long lastCommitChangeCount; // last changeCount that was committed
private IList<SegmentCommitInfo> rollbackSegments; // list of segmentInfo we will fallback to if the commit fails
internal volatile SegmentInfos pendingCommit; // set when a commit is pending (after prepareCommit() & before commit())
internal long pendingCommitChangeCount;
private ICollection<string> filesToCommit;
internal readonly SegmentInfos segmentInfos; // the segments
internal readonly FieldNumbers globalFieldNumberMap;
private readonly DocumentsWriter docWriter;
private readonly ConcurrentQueue<IEvent> eventQueue;
internal readonly IndexFileDeleter deleter;
// used by forceMerge to note those needing merging
private readonly IDictionary<SegmentCommitInfo, bool> segmentsToMerge = new Dictionary<SegmentCommitInfo, bool>();
private int mergeMaxNumSegments;
private Lock writeLock;
private volatile bool closed;
private volatile bool closing;
// Holds all SegmentInfo instances currently involved in
// merges
private readonly JCG.HashSet<SegmentCommitInfo> mergingSegments = new JCG.HashSet<SegmentCommitInfo>();
private readonly MergePolicy mergePolicy;
private readonly IMergeScheduler mergeScheduler;
private readonly Queue<MergePolicy.OneMerge> pendingMerges = new Queue<MergePolicy.OneMerge>();
private readonly JCG.HashSet<MergePolicy.OneMerge> runningMerges = new JCG.HashSet<MergePolicy.OneMerge>();
private IList<MergePolicy.OneMerge> mergeExceptions = new JCG.List<MergePolicy.OneMerge>();
private long mergeGen;
private bool stopMerges;
internal readonly AtomicInt32 flushCount = new AtomicInt32();
internal readonly AtomicInt32 flushDeletesCount = new AtomicInt32();
internal ReaderPool readerPool;
internal readonly BufferedUpdatesStream bufferedUpdatesStream;
// this is a "write once" variable (like the organic dye
// on a DVD-R that may or may not be heated by a laser and
// then cooled to permanently record the event): it's
// false, until getReader() is called for the first time,
// at which point it's switched to true and never changes
// back to false. Once this is true, we hold open and
// reuse SegmentReader instances internally for applying
// deletes, doing merges, and reopening near real-time
// readers.
private volatile bool poolReaders;
// The instance that was passed to the constructor. It is saved only in order
// to allow users to query an IndexWriter settings.
private readonly LiveIndexWriterConfig config;
internal virtual DirectoryReader GetReader()
{
return GetReader(true);
}
/// <summary>
/// Expert: returns a readonly reader, covering all
/// committed as well as un-committed changes to the index.
/// this provides "near real-time" searching, in that
/// changes made during an <see cref="IndexWriter"/> session can be
/// quickly made available for searching without closing
/// the writer nor calling <see cref="Commit()"/>.
///
/// <para>Note that this is functionally equivalent to calling
/// Flush() and then opening a new reader. But the turnaround time of this
/// method should be faster since it avoids the potentially
/// costly <see cref="Commit()"/>.</para>
///
/// <para>You must close the <see cref="IndexReader"/> returned by
/// this method once you are done using it.</para>
///
/// <para>It's <i>near</i> real-time because there is no hard
/// guarantee on how quickly you can get a new reader after
/// making changes with <see cref="IndexWriter"/>. You'll have to
/// experiment in your situation to determine if it's
/// fast enough. As this is a new and experimental
/// feature, please report back on your findings so we can
/// learn, improve and iterate.</para>
///
/// <para>The resulting reader supports
/// <see cref="DirectoryReader.DoOpenIfChanged()"/>, but that call will simply forward
/// back to this method (though this may change in the
/// future).</para>
///
/// <para>The very first time this method is called, this
/// writer instance will make every effort to pool the
/// readers that it opens for doing merges, applying
/// deletes, etc. This means additional resources (RAM,
/// file descriptors, CPU time) will be consumed.</para>
///
/// <para>For lower latency on reopening a reader, you should
/// set <see cref="LiveIndexWriterConfig.MergedSegmentWarmer"/> to
/// pre-warm a newly merged segment before it's committed
/// to the index. This is important for minimizing
/// index-to-search delay after a large merge. </para>
///
/// <para>If an AddIndexes* call is running in another thread,
/// then this reader will only search those segments from
/// the foreign index that have been successfully copied
/// over, so far.</para>
///
/// <para><b>NOTE</b>: Once the writer is disposed, any
/// outstanding readers may continue to be used. However,
/// if you attempt to reopen any of those readers, you'll
/// hit an <see cref="ObjectDisposedException"/>.</para>
///
/// @lucene.experimental
/// </summary>
/// <returns> <see cref="IndexReader"/> that covers entire index plus all
/// changes made so far by this <see cref="IndexWriter"/> instance
/// </returns>
/// <exception cref="IOException"> If there is a low-level I/O error </exception>
public virtual DirectoryReader GetReader(bool applyAllDeletes)
{
EnsureOpen();
long tStart = Time.NanoTime() / Time.MillisecondsPerNanosecond; // LUCENENET: Use NanoTime() rather than CurrentTimeMilliseconds() for more accurate/reliable results
if (infoStream.IsEnabled("IW"))
{
infoStream.Message("IW", "flush at getReader");
}
// Do this up front before flushing so that the readers
// obtained during this flush are pooled, the first time
// this method is called:
poolReaders = true;
DirectoryReader r = null;
DoBeforeFlush();
bool anySegmentFlushed = false;
/*
* for releasing a NRT reader we must ensure that
* DW doesn't add any segments or deletes until we are
* done with creating the NRT DirectoryReader.
* We release the two stage full flush after we are done opening the
* directory reader!
*/
bool success2 = false;
try
{
UninterruptableMonitor.Enter(fullFlushLock);
try
{
bool success = false;
try
{
anySegmentFlushed = docWriter.FlushAllThreads(this);
if (!anySegmentFlushed)
{
// prevent double increment since docWriter#doFlush increments the flushcount
// if we flushed anything.
flushCount.IncrementAndGet();
}
success = true;
// Prevent segmentInfos from changing while opening the
// reader; in theory we could instead do similar retry logic,
// just like we do when loading segments_N
UninterruptableMonitor.Enter(this);
try
{
MaybeApplyDeletes(applyAllDeletes);
r = StandardDirectoryReader.Open(this, segmentInfos, applyAllDeletes);
if (infoStream.IsEnabled("IW"))
{
infoStream.Message("IW", "return reader version=" + r.Version + " reader=" + r);
}
}
finally
{
UninterruptableMonitor.Exit(this);
}
}
catch (Exception oom) when (oom.IsOutOfMemoryError())
{
HandleOOM(oom, "GetReader");
// never reached but javac disagrees:
return null;
}
finally
{
if (!success)
{
if (infoStream.IsEnabled("IW"))
{
infoStream.Message("IW", "hit exception during NRT reader");
}
}
// Done: finish the full flush!
docWriter.FinishFullFlush(success);
ProcessEvents(false, true);
DoAfterFlush();
}
}
finally
{
UninterruptableMonitor.Exit(fullFlushLock);
}
if (anySegmentFlushed)
{
MaybeMerge(MergeTrigger.FULL_FLUSH, UNBOUNDED_MAX_MERGE_SEGMENTS);
}
if (infoStream.IsEnabled("IW"))
{
infoStream.Message("IW", "getReader took " + ((Time.NanoTime() / Time.MillisecondsPerNanosecond) - tStart) + " msec"); // LUCENENET: Use NanoTime() rather than CurrentTimeMilliseconds() for more accurate/reliable results
}
success2 = true;
}
finally
{
if (!success2)
{
IOUtils.DisposeWhileHandlingException(r);
}
}
return r;
}
/// <summary>
/// Holds shared <see cref="SegmentReader"/> instances. <see cref="IndexWriter"/> uses
/// <see cref="SegmentReader"/>s for 1) applying deletes, 2) doing
/// merges, 3) handing out a real-time reader. This pool
/// reuses instances of the <see cref="SegmentReader"/>s in all these
/// places if it is in "near real-time mode" (<see cref="GetReader()"/>
/// has been called on this instance).
/// </summary>
internal class ReaderPool : IDisposable
{
private readonly IndexWriter outerInstance;
public ReaderPool(IndexWriter outerInstance)
{
this.outerInstance = outerInstance;
}
#if FEATURE_DICTIONARY_REMOVE_CONTINUEENUMERATION
private readonly IDictionary<SegmentCommitInfo, ReadersAndUpdates> readerMap = new Dictionary<SegmentCommitInfo, ReadersAndUpdates>();
#else
// LUCENENET: We use ConcurrentDictionary<TKey, TValue> because Dictionary<TKey, TValue> doesn't support
// deletion while iterating, but ConcurrentDictionary does.
private readonly IDictionary<SegmentCommitInfo, ReadersAndUpdates> readerMap = new ConcurrentDictionary<SegmentCommitInfo, ReadersAndUpdates>();
#endif
// used only by asserts
public virtual bool InfoIsLive(SegmentCommitInfo info)
{
UninterruptableMonitor.Enter(this);
try
{
int idx = outerInstance.segmentInfos.IndexOf(info);
Debugging.Assert(idx != -1, "info={0} isn't live", info);
Debugging.Assert(outerInstance.segmentInfos[idx] == info, "info={0} doesn't match live info in segmentInfos", info);
return true;
}
finally
{
UninterruptableMonitor.Exit(this);
}
}
public virtual void Drop(SegmentCommitInfo info)
{
UninterruptableMonitor.Enter(this);
try
{
if (readerMap.TryGetValue(info, out ReadersAndUpdates rld) && rld != null)
{
if (Debugging.AssertsEnabled) Debugging.Assert(info == rld.Info);
// System.out.println("[" + Thread.currentThread().getName() + "] ReaderPool.drop: " + info);
readerMap.Remove(info);
rld.DropReaders();
}
}
finally
{
UninterruptableMonitor.Exit(this);
}
}
public virtual bool AnyPendingDeletes()
{
UninterruptableMonitor.Enter(this);
try
{
foreach (ReadersAndUpdates rld in readerMap.Values)
{
if (rld.PendingDeleteCount != 0)
{
return true;
}
}
return false;
}
finally
{
UninterruptableMonitor.Exit(this);
}
}
public virtual void Release(ReadersAndUpdates rld)
{
UninterruptableMonitor.Enter(this);
try
{
Release(rld, true);
}
finally
{
UninterruptableMonitor.Exit(this);
}
}
public virtual void Release(ReadersAndUpdates rld, bool assertInfoLive)
{
UninterruptableMonitor.Enter(this);
try
{
// Matches incRef in get:
rld.DecRef();
// Pool still holds a ref:
if (Debugging.AssertsEnabled) Debugging.Assert(rld.RefCount() >= 1);
if (!outerInstance.poolReaders && rld.RefCount() == 1)
{
// this is the last ref to this RLD, and we're not
// pooling, so remove it:
// System.out.println("[" + Thread.currentThread().getName() + "] ReaderPool.release: " + rld.info);
if (rld.WriteLiveDocs(outerInstance.directory))
{
// Make sure we only write del docs for a live segment:
if (Debugging.AssertsEnabled) Debugging.Assert(assertInfoLive == false || InfoIsLive(rld.Info));
// Must checkpoint because we just
// created new _X_N.del and field updates files;
// don't call IW.checkpoint because that also
// increments SIS.version, which we do not want to
// do here: it was done previously (after we
// invoked BDS.applyDeletes), whereas here all we
// did was move the state to disk:
outerInstance.CheckpointNoSIS();
}
//System.out.println("IW: done writeLiveDocs for info=" + rld.info);
// System.out.println("[" + Thread.currentThread().getName() + "] ReaderPool.release: drop readers " + rld.info);
rld.DropReaders();
readerMap.Remove(rld.Info);
}
}
finally
{
UninterruptableMonitor.Exit(this);
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
DropAll(false);
}
}
/// <summary>
/// Remove all our references to readers, and commits
/// any pending changes.
/// </summary>
internal virtual void DropAll(bool doSave)
{
UninterruptableMonitor.Enter(this);
try
{
Exception priorE = null;
foreach (var pair in readerMap)
{
ReadersAndUpdates rld = pair.Value;
try
{
if (doSave && rld.WriteLiveDocs(outerInstance.directory)) // Throws IOException
{
// Make sure we only write del docs and field updates for a live segment:
if (Debugging.AssertsEnabled) Debugging.Assert(InfoIsLive(rld.Info));
// Must checkpoint because we just
// created new _X_N.del and field updates files;
// don't call IW.checkpoint because that also
// increments SIS.version, which we do not want to
// do here: it was done previously (after we
// invoked BDS.applyDeletes), whereas here all we
// did was move the state to disk:
outerInstance.CheckpointNoSIS(); // Throws IOException
}
}
catch (Exception t) when (t.IsThrowable())
{
if (doSave)
{
//IOUtils.ReThrow(t);
throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details)
}
else if (priorE is null)
{
priorE = t;
}
}
// Important to remove as-we-go, not with .clear()
// in the end, in case we hit an exception;
// otherwise we could over-decref if close() is
// called again:
readerMap.Remove(pair.Key);
// NOTE: it is allowed that these decRefs do not
// actually close the SRs; this happens when a
// near real-time reader is kept open after the
// IndexWriter instance is closed:
try
{
rld.DropReaders(); // Throws IOException
}
catch (Exception t) when (t.IsThrowable())
{
if (doSave)
{
//IOUtils.ReThrow(t);
throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details)
}
else if (priorE is null)
{
priorE = t;
}
}
}
if (Debugging.AssertsEnabled) Debugging.Assert(readerMap.Count == 0);
IOUtils.ReThrow(priorE);
}
finally
{
UninterruptableMonitor.Exit(this);
}
}
/// <summary>
/// Commit live docs changes for the segment readers for
/// the provided infos.
/// </summary>
/// <exception cref="IOException"> If there is a low-level I/O error </exception>
public virtual void Commit(SegmentInfos infos)
{
UninterruptableMonitor.Enter(this);
try
{
foreach (SegmentCommitInfo info in infos.Segments)
{
if (readerMap.TryGetValue(info, out ReadersAndUpdates rld))
{
if (Debugging.AssertsEnabled) Debugging.Assert(rld.Info == info);
if (rld.WriteLiveDocs(outerInstance.directory))
{
// Make sure we only write del docs for a live segment:
if (Debugging.AssertsEnabled) Debugging.Assert(InfoIsLive(info));
// Must checkpoint because we just
// created new _X_N.del and field updates files;
// don't call IW.checkpoint because that also
// increments SIS.version, which we do not want to
// do here: it was done previously (after we
// invoked BDS.applyDeletes), whereas here all we
// did was move the state to disk:
outerInstance.CheckpointNoSIS();
}
}
}
}
finally
{
UninterruptableMonitor.Exit(this);
}
}
/// <summary>
/// Obtain a <see cref="ReadersAndUpdates"/> instance from the
/// readerPool. If <paramref name="create"/> is <c>true</c>, you must later call
/// <see cref="Release(ReadersAndUpdates)"/>.
/// </summary>
public virtual ReadersAndUpdates Get(SegmentCommitInfo info, bool create)
{
UninterruptableMonitor.Enter(this);
try
{
if (Debugging.AssertsEnabled) Debugging.Assert(info.Info.Dir == outerInstance.directory, "info.dir={0} vs {1}", info.Info.Dir, outerInstance.directory);
if (!readerMap.TryGetValue(info, out ReadersAndUpdates rld) || rld is null)
{
if (!create)
{
return null;
}
rld = new ReadersAndUpdates(outerInstance, info);
// Steal initial reference:
readerMap[info] = rld;
}
else
{
if (Debugging.AssertsEnabled && !(rld.Info == info))
throw AssertionError.Create(string.Format("rld.info={0} info={1} isLive?={2} vs {3}", rld.Info, info, InfoIsLive(rld.Info), InfoIsLive(info)));
}
if (create)
{
// Return ref to caller:
rld.IncRef();
}
if (Debugging.AssertsEnabled) Debugging.Assert(NoDups());
return rld;
}
finally
{
UninterruptableMonitor.Exit(this);
}
}
/// <summary>
/// Make sure that every segment appears only once in the
/// pool:
/// </summary>
private bool NoDups()
{
JCG.HashSet<string> seen = new JCG.HashSet<string>();
foreach (SegmentCommitInfo info in readerMap.Keys)
{
if (Debugging.AssertsEnabled) Debugging.Assert(!seen.Contains(info.Info.Name));
seen.Add(info.Info.Name);
}
return true;
}
}
/// <summary>
/// Obtain the number of deleted docs for a pooled reader.
/// If the reader isn't being pooled, the segmentInfo's
/// delCount is returned.
/// </summary>
public virtual int NumDeletedDocs(SegmentCommitInfo info)
{
EnsureOpen(false);
int delCount = info.DelCount;
ReadersAndUpdates rld = readerPool.Get(info, false);
if (rld != null)
{
delCount += rld.PendingDeleteCount;
}
return delCount;
}
/// <summary>
/// Used internally to throw an <see cref="ObjectDisposedException"/> if this
/// <see cref="IndexWriter"/> has been disposed or is in the process of diposing.
/// </summary>
/// <param name="failIfDisposing">
/// if <c>true</c>, also fail when <see cref="IndexWriter"/> is in the process of
/// disposing (<c>closing=true</c>) but not yet done disposing (
/// <c>closed=false</c>) </param>
/// <exception cref="ObjectDisposedException">
/// if this IndexWriter is closed or in the process of closing </exception>
protected internal void EnsureOpen(bool failIfDisposing)
{
if (closed || (failIfDisposing && closing))
{
throw AlreadyClosedException.Create(this.GetType().FullName, "this IndexWriter is disposed.");
}
}
/// <summary>
/// Used internally to throw an
/// <see cref="ObjectDisposedException"/> if this <see cref="IndexWriter"/> has been
/// disposed (<c>closed=true</c>) or is in the process of
/// disposing (<c>closing=true</c>).
/// <para/>
/// Calls <see cref="EnsureOpen(bool)"/>.
/// </summary>
/// <exception cref="ObjectDisposedException"> if this <see cref="IndexWriter"/> is disposed </exception>
protected internal void EnsureOpen()
{
EnsureOpen(true);
}
internal readonly Codec codec; // for writing new segments
/// <summary>
/// Constructs a new <see cref="IndexWriter"/> per the settings given in <paramref name="conf"/>.
/// If you want to make "live" changes to this writer instance, use
/// <see cref="Config"/>.
///
/// <para/>
/// <b>NOTE:</b> after ths writer is created, the given configuration instance
/// cannot be passed to another writer. If you intend to do so, you should
/// <see cref="IndexWriterConfig.Clone()"/> it beforehand.
/// </summary>
/// <param name="d">
/// the index directory. The index is either created or appended
/// according <see cref="IndexWriterConfig.OpenMode"/>. </param>
/// <param name="conf">
/// the configuration settings according to which <see cref="IndexWriter"/> should
/// be initialized. </param>
/// <exception cref="IOException">
/// if the directory cannot be read/written to, or if it does not
/// exist and <see cref="IndexWriterConfig.OpenMode"/> is
/// <see cref="OpenMode.APPEND"/> or if there is any other low-level
/// IO error </exception>
public IndexWriter(Directory d, IndexWriterConfig conf)
{
readerPool = new ReaderPool(this);
conf.SetIndexWriter(this); // prevent reuse by other instances
config = new LiveIndexWriterConfig(conf);
directory = d;
analyzer = config.Analyzer;
infoStream = config.InfoStream;
mergePolicy = config.MergePolicy;
mergePolicy.SetIndexWriter(this);
mergeScheduler = config.MergeScheduler;
codec = config.Codec;
bufferedUpdatesStream = new BufferedUpdatesStream(infoStream);
poolReaders = config.UseReaderPooling;
writeLock = directory.MakeLock(WRITE_LOCK_NAME);
if (!writeLock.Obtain(config.WriteLockTimeout)) // obtain write lock
{
throw new LockObtainFailedException("Index locked for write: " + writeLock);
}
bool success = false;
try
{
OpenMode? mode = config.OpenMode;
bool create;
if (mode == OpenMode.CREATE)
{
create = true;
}
else if (mode == OpenMode.APPEND)
{
create = false;
}
else
{
// CREATE_OR_APPEND - create only if an index does not exist
create = !DirectoryReader.IndexExists(directory);
}
// If index is too old, reading the segments will throw
// IndexFormatTooOldException.
segmentInfos = new SegmentInfos();
bool initialIndexExists = true;
if (create)
{
// Try to read first. this is to allow create
// against an index that's currently open for
// searching. In this case we write the next
// segments_N file with no segments:
try
{
segmentInfos.Read(directory);
segmentInfos.Clear();
}
catch (Exception e) when (e.IsIOException())
{
// Likely this means it's a fresh directory
initialIndexExists = false;
}
// Record that we have a change (zero out all
// segments) pending:
Changed();
}
else
{
segmentInfos.Read(directory);
IndexCommit commit = config.IndexCommit;
if (commit != null)
{
// Swap out all segments, but, keep metadata in
// SegmentInfos, like version & generation, to
// preserve write-once. this is important if
// readers are open against the future commit
// points.
if (commit.Directory != directory)
{
throw new ArgumentException(string.Format("IndexCommit's directory doesn't match my directory (mine: {0}, commit's: {1})", directory, commit.Directory));
}
SegmentInfos oldInfos = new SegmentInfos();
oldInfos.Read(directory, commit.SegmentsFileName);
segmentInfos.Replace(oldInfos);
Changed();
if (infoStream.IsEnabled("IW"))
{
infoStream.Message("IW", "init: loaded commit \"" + commit.SegmentsFileName + "\"");
}
}
}
rollbackSegments = segmentInfos.CreateBackupSegmentInfos();
// start with previous field numbers, but new FieldInfos
globalFieldNumberMap = FieldNumberMap;
config.FlushPolicy.Init(config);
docWriter = new DocumentsWriter(this, config, directory);
eventQueue = docWriter.EventQueue;
// Default deleter (for backwards compatibility) is
// KeepOnlyLastCommitDeleter:
UninterruptableMonitor.Enter(this);
try
{
deleter = new IndexFileDeleter(directory, config.IndexDeletionPolicy, segmentInfos, infoStream, this, initialIndexExists);
}
finally
{
UninterruptableMonitor.Exit(this);
}
if (deleter.startingCommitDeleted)
{
// Deletion policy deleted the "head" commit point.
// We have to mark ourself as changed so that if we
// are closed w/o any further changes we write a new
// segments_N file.
Changed();
}
if (infoStream.IsEnabled("IW"))
{
infoStream.Message("IW", "init: create=" + create);
MessageState();
}
success = true;
}
finally
{
if (!success)
{
if (infoStream.IsEnabled("IW"))
{
infoStream.Message("IW", "init: hit exception on init; releasing write lock");
}
IOUtils.DisposeWhileHandlingException(writeLock);
writeLock = null;
}