forked from apache/lucenenet
-
Notifications
You must be signed in to change notification settings - Fork 3
/
DirectoryTaxonomyReader.cs
440 lines (397 loc) · 17.3 KB
/
DirectoryTaxonomyReader.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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
namespace Lucene.Net.Facet.Taxonomy.Directory
{
/*
* 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 BytesRef = Lucene.Net.Util.BytesRef;
using Directory = Lucene.Net.Store.Directory;
using DirectoryReader = Lucene.Net.Index.DirectoryReader;
using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator;
using DocsEnum = Lucene.Net.Index.DocsEnum;
using Document = Lucene.Net.Documents.Document;
using IndexWriter = Lucene.Net.Index.IndexWriter;
using IOUtils = Lucene.Net.Util.IOUtils;
using MultiFields = Lucene.Net.Index.MultiFields;
/// <summary>
/// A <see cref="TaxonomyReader"/> which retrieves stored taxonomy information from a
/// <see cref="Directory"/>.
/// <para/>
/// Reading from the on-disk index on every method call is too slow, so this
/// implementation employs caching: Some methods cache recent requests and their
/// results, while other methods prefetch all the data into memory and then
/// provide answers directly from in-memory tables. See the documentation of
/// individual methods for comments on their performance.
///
/// @lucene.experimental
/// </summary>
public class DirectoryTaxonomyReader : TaxonomyReader
{
/// <summary>
/// LUCENENET specific class to make an <see cref="int"/> type into a reference type.
/// </summary>
private class Int32Class
{
/// <summary>
/// NOTE: This was intItem (field) in Lucene
/// </summary>
public int Value { get; set; }
}
private const int DEFAULT_CACHE_VALUE = 4000;
private readonly DirectoryTaxonomyWriter taxoWriter;
private readonly long taxoEpoch; // used in doOpenIfChanged
private readonly DirectoryReader indexReader;
// TODO: test DoubleBarrelLRUCache and consider using it instead
private LRUHashMap<FacetLabel, Int32Class> ordinalCache;
private LRUHashMap<int, FacetLabel> categoryCache;
private volatile TaxonomyIndexArrays taxoArrays;
/// <summary>
/// Called only from <see cref="DoOpenIfChanged()"/>. If the taxonomy has been
/// recreated, you should pass <c>null</c> as the caches and parent/children
/// arrays.
/// </summary>
private DirectoryTaxonomyReader(DirectoryReader indexReader, DirectoryTaxonomyWriter taxoWriter,
LRUHashMap<FacetLabel, Int32Class> ordinalCache, LRUHashMap<int, FacetLabel> categoryCache,
TaxonomyIndexArrays taxoArrays)
{
this.indexReader = indexReader;
this.taxoWriter = taxoWriter;
this.taxoEpoch = taxoWriter == null ? -1 : taxoWriter.TaxonomyEpoch;
// use the same instance of the cache, note the protective code in getOrdinal and getPath
this.ordinalCache = ordinalCache ?? new LRUHashMap<FacetLabel, Int32Class>(DEFAULT_CACHE_VALUE);
this.categoryCache = categoryCache ?? new LRUHashMap<int, FacetLabel>(DEFAULT_CACHE_VALUE);
this.taxoArrays = taxoArrays != null ? new TaxonomyIndexArrays(indexReader, taxoArrays) : null;
}
/// <summary>
/// Open for reading a taxonomy stored in a given <see cref="Directory"/>.
/// </summary>
/// <param name="directory"> The <see cref="Directory"/> in which the taxonomy resides. </param>
/// <exception cref="Index.CorruptIndexException"> if the Taxonomy is corrupt. </exception>
/// <exception cref="IOException"> if another error occurred. </exception>
public DirectoryTaxonomyReader(Directory directory)
{
indexReader = OpenIndexReader(directory);
taxoWriter = null;
taxoEpoch = -1;
// These are the default cache sizes; they can be configured after
// construction with the cache's setMaxSize() method
ordinalCache = new LRUHashMap<FacetLabel, Int32Class>(DEFAULT_CACHE_VALUE);
categoryCache = new LRUHashMap<int, FacetLabel>(DEFAULT_CACHE_VALUE);
}
/// <summary>
/// Opens a <see cref="DirectoryTaxonomyReader"/> over the given
/// <see cref="DirectoryTaxonomyWriter"/> (for NRT).
/// </summary>
/// <param name="taxoWriter">
/// The <see cref="DirectoryTaxonomyWriter"/> from which to obtain newly
/// added categories, in real-time. </param>
public DirectoryTaxonomyReader(DirectoryTaxonomyWriter taxoWriter)
{
this.taxoWriter = taxoWriter;
taxoEpoch = taxoWriter.TaxonomyEpoch;
indexReader = OpenIndexReader(taxoWriter.InternalIndexWriter);
// These are the default cache sizes; they can be configured after
// construction with the cache's setMaxSize() method
ordinalCache = new LRUHashMap<FacetLabel, Int32Class>(DEFAULT_CACHE_VALUE);
categoryCache = new LRUHashMap<int, FacetLabel>(DEFAULT_CACHE_VALUE);
}
private void InitTaxoArrays()
{
lock (this)
{
if (taxoArrays == null)
{
// according to Java Concurrency in Practice, this might perform better on
// some JVMs, because the array initialization doesn't happen on the
// volatile member.
TaxonomyIndexArrays tmpArrays = new TaxonomyIndexArrays(indexReader);
taxoArrays = tmpArrays;
}
}
}
protected internal override void DoClose()
{
indexReader.Dispose();
taxoArrays = null;
// do not clear() the caches, as they may be used by other DTR instances.
ordinalCache = null;
categoryCache = null;
}
/// <summary>
/// Implements the opening of a new <see cref="DirectoryTaxonomyReader"/> instance if
/// the taxonomy has changed.
///
/// <para>
/// <b>NOTE:</b> the returned <see cref="DirectoryTaxonomyReader"/> shares the
/// ordinal and category caches with this reader. This is not expected to cause
/// any issues, unless the two instances continue to live. The reader
/// guarantees that the two instances cannot affect each other in terms of
/// correctness of the caches, however if the size of the cache is changed
/// through <see cref="SetCacheSize(int)"/>, it will affect both reader instances.
/// </para>
/// </summary>
protected override TaxonomyReader DoOpenIfChanged()
{
EnsureOpen();
// This works for both NRT and non-NRT readers (i.e. an NRT reader remains NRT).
var r2 = DirectoryReader.OpenIfChanged(indexReader);
if (r2 == null)
{
return null; // no changes, nothing to do
}
// check if the taxonomy was recreated
bool success = false;
try
{
bool recreated = false;
if (taxoWriter == null)
{
// not NRT, check epoch from commit data
string t1 = indexReader.IndexCommit.UserData[DirectoryTaxonomyWriter.INDEX_EPOCH];
string t2 = r2.IndexCommit.UserData[DirectoryTaxonomyWriter.INDEX_EPOCH];
if (t1 == null)
{
if (t2 != null)
{
recreated = true;
}
}
else if (!t1.Equals(t2, StringComparison.Ordinal))
{
// t1 != null and t2 cannot be null b/c DirTaxoWriter always puts the commit data.
// it's ok to use String.equals because we require the two epoch values to be the same.
recreated = true;
}
}
else
{
// NRT, compare current taxoWriter.epoch() vs the one that was given at construction
if (taxoEpoch != taxoWriter.TaxonomyEpoch)
{
recreated = true;
}
}
DirectoryTaxonomyReader newtr;
if (recreated)
{
// if recreated, do not reuse anything from this instace. the information
// will be lazily computed by the new instance when needed.
newtr = new DirectoryTaxonomyReader(r2, taxoWriter, null, null, null);
}
else
{
newtr = new DirectoryTaxonomyReader(r2, taxoWriter, ordinalCache, categoryCache, taxoArrays);
}
success = true;
return newtr;
}
finally
{
if (!success)
{
IOUtils.DisposeWhileHandlingException(r2);
}
}
}
/// <summary>
/// Open the <see cref="DirectoryReader"/> from this <see cref="Directory"/>.
/// </summary>
protected virtual DirectoryReader OpenIndexReader(Directory directory)
{
return DirectoryReader.Open(directory);
}
/// <summary>
/// Open the <see cref="DirectoryReader"/> from this <see cref="IndexWriter"/>.
/// </summary>
protected virtual DirectoryReader OpenIndexReader(IndexWriter writer)
{
return DirectoryReader.Open(writer, false);
}
/// <summary>
/// Expert: returns the underlying <see cref="DirectoryReader"/> instance that is
/// used by this <see cref="TaxonomyReader"/>.
/// </summary>
internal virtual DirectoryReader InternalIndexReader
{
get
{
EnsureOpen();
return indexReader;
}
}
public override ParallelTaxonomyArrays ParallelTaxonomyArrays
{
get
{
EnsureOpen();
if (taxoArrays == null)
{
InitTaxoArrays();
}
return taxoArrays;
}
}
public override IDictionary<string, string> CommitUserData
{
get
{
EnsureOpen();
return indexReader.IndexCommit.UserData;
}
}
public override int GetOrdinal(FacetLabel cp)
{
EnsureOpen();
if (cp.Length == 0)
{
return ROOT_ORDINAL;
}
// First try to find the answer in the LRU cache:
// LUCENENET: Lock was removed here because the underlying cache is thread-safe,
// and removing the lock seems to make the performance better.
Int32Class res = ordinalCache.Get(cp);
if (res != null)
{
if ((int)res.Value < indexReader.MaxDoc)
{
// Since the cache is shared with DTR instances allocated from
// doOpenIfChanged, we need to ensure that the ordinal is one that
// this DTR instance recognizes.
return (int)res.Value;
}
else
{
// if we get here, it means that the category was found in the cache,
// but is not recognized by this TR instance. Therefore there's no
// need to continue search for the path on disk, because we won't find
// it there too.
return TaxonomyReader.INVALID_ORDINAL;
}
}
// If we're still here, we have a cache miss. We need to fetch the
// value from disk, and then also put it in the cache:
int ret = TaxonomyReader.INVALID_ORDINAL;
DocsEnum docs = MultiFields.GetTermDocsEnum(indexReader, null, Consts.FULL, new BytesRef(FacetsConfig.PathToString(cp.Components, cp.Length)), 0);
if (docs != null && docs.NextDoc() != DocIdSetIterator.NO_MORE_DOCS)
{
ret = docs.DocID;
// we only store the fact that a category exists, not its inexistence.
// This is required because the caches are shared with new DTR instances
// that are allocated from doOpenIfChanged. Therefore, if we only store
// information about found categories, we cannot accidently tell a new
// generation of DTR that a category does not exist.
// LUCENENET: Lock was removed here because the underlying cache is thread-safe,
// and removing the lock seems to make the performance better.
ordinalCache.Put(cp, new Int32Class { Value = Convert.ToInt32(ret, CultureInfo.InvariantCulture) });
}
return ret;
}
public override FacetLabel GetPath(int ordinal)
{
EnsureOpen();
// Since the cache is shared with DTR instances allocated from
// doOpenIfChanged, we need to ensure that the ordinal is one that this DTR
// instance recognizes. Therefore we do this check up front, before we hit
// the cache.
if (ordinal < 0 || ordinal >= indexReader.MaxDoc)
{
return null;
}
// TODO: can we use an int-based hash impl, such as IntToObjectMap,
// wrapped as LRU?
// LUCENENET NOTE: We don't need to convert ordinal from int to int here as was done in Java.
FacetLabel res;
// LUCENENET: Lock was removed here because the underlying cache is thread-safe,
// and removing the lock seems to make the performance better.
if (categoryCache.TryGetValue(ordinal, out res))
{
return res;
}
Document doc = indexReader.Document(ordinal);
res = new FacetLabel(FacetsConfig.StringToPath(doc.Get(Consts.FULL)));
// LUCENENET: Lock was removed here because the underlying cache is thread-safe,
// and removing the lock seems to make the performance better.
categoryCache.Put(ordinal, res);
return res;
}
public override int Count
{
get
{
EnsureOpen();
return indexReader.NumDocs;
}
}
/// <summary>
/// <see cref="SetCacheSize"/> controls the maximum allowed size of each of the caches
/// used by <see cref="GetPath(int)"/> and <see cref="GetOrdinal(FacetLabel)"/>.
/// <para/>
/// Currently, if the given size is smaller than the current size of
/// a cache, it will not shrink, and rather we be limited to its current
/// size. </summary>
/// <param name="size"> the new maximum cache size, in number of entries. </param>
public virtual void SetCacheSize(int size)
{
EnsureOpen();
lock (categoryCache)
{
categoryCache.Limit = size;
}
lock (ordinalCache)
{
ordinalCache.Limit = size;
}
}
/// <summary>
/// Returns ordinal -> label mapping, up to the provided
/// max ordinal or number of ordinals, whichever is
/// smaller.
/// </summary>
public virtual string ToString(int max)
{
EnsureOpen();
StringBuilder sb = new StringBuilder();
int upperl = Math.Min(max, indexReader.MaxDoc);
for (int i = 0; i < upperl; i++)
{
try
{
FacetLabel category = this.GetPath(i);
if (category == null)
{
sb.Append(i + ": NULL!! \n");
continue;
}
if (category.Length == 0)
{
sb.Append(i + ": EMPTY STRING!! \n");
continue;
}
sb.Append(i + ": " + category.ToString() + "\n");
}
catch (IOException)
{
throw;
}
}
return sb.ToString();
}
}
}