1 package org.apache.lucene.index;
4 * Licensed to the Apache Software Foundation (ASF) under one or more
5 * contributor license agreements. See the NOTICE file distributed with
6 * this work for additional information regarding copyright ownership.
7 * The ASF licenses this file to You under the Apache License, Version 2.0
8 * (the "License"); you may not use this file except in compliance with
9 * the License. You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
20 import java.io.IOException;
21 import java.util.Arrays;
22 import java.util.Collection;
23 import java.util.HashMap;
25 import java.util.concurrent.ConcurrentHashMap;
27 import org.apache.lucene.document.Document;
28 import org.apache.lucene.document.FieldSelector;
29 import org.apache.lucene.index.DirectoryReader.MultiTermDocs;
30 import org.apache.lucene.index.DirectoryReader.MultiTermEnum;
31 import org.apache.lucene.index.DirectoryReader.MultiTermPositions;
32 import org.apache.lucene.search.Similarity;
33 import org.apache.lucene.util.MapBackedSet;
35 /** An IndexReader which reads multiple indexes, appending
37 public class MultiReader extends IndexReader implements Cloneable {
38 protected IndexReader[] subReaders;
39 private int[] starts; // 1st docno for each segment
40 private boolean[] decrefOnClose; // remember which subreaders to decRef on close
41 private Map<String,byte[]> normsCache = new HashMap<String,byte[]>();
42 private int maxDoc = 0;
43 private int numDocs = -1;
44 private boolean hasDeletions = false;
47 * <p>Construct a MultiReader aggregating the named set of (sub)readers.
48 * Directory locking for delete, undeleteAll, and setNorm operations is
49 * left to the subreaders. </p>
50 * <p>Note that all subreaders are closed if this Multireader is closed.</p>
51 * @param subReaders set of (sub)readers
53 public MultiReader(IndexReader... subReaders) {
54 initialize(subReaders, true);
58 * <p>Construct a MultiReader aggregating the named set of (sub)readers.
59 * Directory locking for delete, undeleteAll, and setNorm operations is
60 * left to the subreaders. </p>
61 * @param closeSubReaders indicates whether the subreaders should be closed
62 * when this MultiReader is closed
63 * @param subReaders set of (sub)readers
65 public MultiReader(IndexReader[] subReaders, boolean closeSubReaders) {
66 initialize(subReaders, closeSubReaders);
69 private void initialize(IndexReader[] subReaders, boolean closeSubReaders) {
70 this.subReaders = subReaders.clone();
71 starts = new int[subReaders.length + 1]; // build starts array
72 decrefOnClose = new boolean[subReaders.length];
73 for (int i = 0; i < subReaders.length; i++) {
75 maxDoc += subReaders[i].maxDoc(); // compute maxDocs
77 if (!closeSubReaders) {
78 subReaders[i].incRef();
79 decrefOnClose[i] = true;
81 decrefOnClose[i] = false;
84 if (subReaders[i].hasDeletions())
87 starts[subReaders.length] = maxDoc;
88 readerFinishedListeners = new MapBackedSet<ReaderFinishedListener>(new ConcurrentHashMap<ReaderFinishedListener,Boolean>());
92 * Tries to reopen the subreaders.
94 * If one or more subreaders could be re-opened (i. e. IndexReader.openIfChanged(subReader)
95 * returned a new instance), then a new MultiReader instance
96 * is returned, otherwise this instance is returned.
98 * A re-opened instance might share one or more subreaders with the old
99 * instance. Index modification operations result in undefined behavior
100 * when performed before the old instance is closed.
101 * (see {@link IndexReader#openIfChanged}).
103 * If subreaders are shared, then the reference count of those
104 * readers is increased to ensure that the subreaders remain open
105 * until the last referring reader is closed.
107 * @throws CorruptIndexException if the index is corrupt
108 * @throws IOException if there is a low-level IO error
111 protected synchronized IndexReader doOpenIfChanged() throws CorruptIndexException, IOException {
112 return doOpenIfChanged(false);
116 * Clones the subreaders.
117 * (see {@link IndexReader#clone()}).
120 * If subreaders are shared, then the reference count of those
121 * readers is increased to ensure that the subreaders remain open
122 * until the last referring reader is closed.
125 public synchronized Object clone() {
127 return doOpenIfChanged(true);
128 } catch (Exception ex) {
129 throw new RuntimeException(ex);
134 * If clone is true then we clone each of the subreaders
136 * @return New IndexReader, or null if open/clone is not necessary
137 * @throws CorruptIndexException
138 * @throws IOException
140 protected IndexReader doOpenIfChanged(boolean doClone) throws CorruptIndexException, IOException {
143 boolean changed = false;
144 IndexReader[] newSubReaders = new IndexReader[subReaders.length];
146 boolean success = false;
148 for (int i = 0; i < subReaders.length; i++) {
150 newSubReaders[i] = (IndexReader) subReaders[i].clone();
153 final IndexReader newSubReader = IndexReader.openIfChanged(subReaders[i]);
154 if (newSubReader != null) {
155 newSubReaders[i] = newSubReader;
158 newSubReaders[i] = subReaders[i];
164 if (!success && changed) {
165 for (int i = 0; i < newSubReaders.length; i++) {
166 if (newSubReaders[i] != subReaders[i]) {
168 newSubReaders[i].close();
169 } catch (IOException ignore) {
170 // keep going - we want to clean up as much as possible
178 boolean[] newDecrefOnClose = new boolean[subReaders.length];
179 for (int i = 0; i < subReaders.length; i++) {
180 if (newSubReaders[i] == subReaders[i]) {
181 newSubReaders[i].incRef();
182 newDecrefOnClose[i] = true;
185 MultiReader mr = new MultiReader(newSubReaders);
186 mr.decrefOnClose = newDecrefOnClose;
194 public TermFreqVector[] getTermFreqVectors(int n) throws IOException {
196 int i = readerIndex(n); // find segment num
197 return subReaders[i].getTermFreqVectors(n - starts[i]); // dispatch to segment
201 public TermFreqVector getTermFreqVector(int n, String field)
204 int i = readerIndex(n); // find segment num
205 return subReaders[i].getTermFreqVector(n - starts[i], field);
210 public void getTermFreqVector(int docNumber, String field, TermVectorMapper mapper) throws IOException {
212 int i = readerIndex(docNumber); // find segment num
213 subReaders[i].getTermFreqVector(docNumber - starts[i], field, mapper);
217 public void getTermFreqVector(int docNumber, TermVectorMapper mapper) throws IOException {
219 int i = readerIndex(docNumber); // find segment num
220 subReaders[i].getTermFreqVector(docNumber - starts[i], mapper);
225 public boolean isOptimized() {
231 public int numDocs() {
232 // Don't call ensureOpen() here (it could affect performance)
233 // NOTE: multiple threads may wind up init'ing
234 // numDocs... but that's harmless
235 if (numDocs == -1) { // check cache
236 int n = 0; // cache miss--recompute
237 for (int i = 0; i < subReaders.length; i++)
238 n += subReaders[i].numDocs(); // sum from readers
245 public int maxDoc() {
246 // Don't call ensureOpen() here (it could affect performance)
252 public Document document(int n, FieldSelector fieldSelector) throws CorruptIndexException, IOException {
254 int i = readerIndex(n); // find segment num
255 return subReaders[i].document(n - starts[i], fieldSelector); // dispatch to segment reader
259 public boolean isDeleted(int n) {
260 // Don't call ensureOpen() here (it could affect performance)
261 int i = readerIndex(n); // find segment num
262 return subReaders[i].isDeleted(n - starts[i]); // dispatch to segment reader
266 public boolean hasDeletions() {
272 protected void doDelete(int n) throws CorruptIndexException, IOException {
273 numDocs = -1; // invalidate cache
274 int i = readerIndex(n); // find segment num
275 subReaders[i].deleteDocument(n - starts[i]); // dispatch to segment reader
280 protected void doUndeleteAll() throws CorruptIndexException, IOException {
281 for (int i = 0; i < subReaders.length; i++)
282 subReaders[i].undeleteAll();
284 hasDeletions = false;
285 numDocs = -1; // invalidate cache
288 private int readerIndex(int n) { // find reader for doc n:
289 return DirectoryReader.readerIndex(n, this.starts, this.subReaders.length);
293 public boolean hasNorms(String field) throws IOException {
295 for (int i = 0; i < subReaders.length; i++) {
296 if (subReaders[i].hasNorms(field)) return true;
302 public synchronized byte[] norms(String field) throws IOException {
304 byte[] bytes = normsCache.get(field);
306 return bytes; // cache hit
307 if (!hasNorms(field))
310 bytes = new byte[maxDoc()];
311 for (int i = 0; i < subReaders.length; i++)
312 subReaders[i].norms(field, bytes, starts[i]);
313 normsCache.put(field, bytes); // update cache
318 public synchronized void norms(String field, byte[] result, int offset)
321 byte[] bytes = normsCache.get(field);
322 for (int i = 0; i < subReaders.length; i++) // read from segments
323 subReaders[i].norms(field, result, offset + starts[i]);
325 if (bytes==null && !hasNorms(field)) {
326 Arrays.fill(result, offset, result.length, Similarity.getDefault().encodeNormValue(1.0f));
327 } else if (bytes != null) { // cache hit
328 System.arraycopy(bytes, 0, result, offset, maxDoc());
330 for (int i = 0; i < subReaders.length; i++) { // read from segments
331 subReaders[i].norms(field, result, offset + starts[i]);
337 protected void doSetNorm(int n, String field, byte value)
338 throws CorruptIndexException, IOException {
339 synchronized (normsCache) {
340 normsCache.remove(field); // clear cache
342 int i = readerIndex(n); // find segment num
343 subReaders[i].setNorm(n-starts[i], field, value); // dispatch
347 public TermEnum terms() throws IOException {
349 if (subReaders.length == 1) {
350 // Optimize single segment case:
351 return subReaders[0].terms();
353 return new MultiTermEnum(this, subReaders, starts, null);
358 public TermEnum terms(Term term) throws IOException {
360 if (subReaders.length == 1) {
361 // Optimize single segment case:
362 return subReaders[0].terms(term);
364 return new MultiTermEnum(this, subReaders, starts, term);
369 public int docFreq(Term t) throws IOException {
371 int total = 0; // sum freqs in segments
372 for (int i = 0; i < subReaders.length; i++)
373 total += subReaders[i].docFreq(t);
378 public TermDocs termDocs() throws IOException {
380 if (subReaders.length == 1) {
381 // Optimize single segment case:
382 return subReaders[0].termDocs();
384 return new MultiTermDocs(this, subReaders, starts);
389 public TermDocs termDocs(Term term) throws IOException {
391 if (subReaders.length == 1) {
392 // Optimize single segment case:
393 return subReaders[0].termDocs(term);
395 return super.termDocs(term);
400 public TermPositions termPositions() throws IOException {
402 if (subReaders.length == 1) {
403 // Optimize single segment case:
404 return subReaders[0].termPositions();
406 return new MultiTermPositions(this, subReaders, starts);
411 protected void doCommit(Map<String,String> commitUserData) throws IOException {
412 for (int i = 0; i < subReaders.length; i++)
413 subReaders[i].commit(commitUserData);
417 protected synchronized void doClose() throws IOException {
418 for (int i = 0; i < subReaders.length; i++) {
419 if (decrefOnClose[i]) {
420 subReaders[i].decRef();
422 subReaders[i].close();
428 public Collection<String> getFieldNames (IndexReader.FieldOption fieldNames) {
430 return DirectoryReader.getFieldNames(fieldNames, this.subReaders);
434 * Checks recursively if all subreaders are up to date.
437 public boolean isCurrent() throws CorruptIndexException, IOException {
439 for (int i = 0; i < subReaders.length; i++) {
440 if (!subReaders[i].isCurrent()) {
445 // all subreaders are up to date
450 * @throws UnsupportedOperationException
453 public long getVersion() {
454 throw new UnsupportedOperationException("MultiReader does not support this method.");
458 public IndexReader[] getSequentialSubReaders() {
463 public void addReaderFinishedListener(ReaderFinishedListener listener) {
464 super.addReaderFinishedListener(listener);
465 for(IndexReader sub : subReaders) {
466 sub.addReaderFinishedListener(listener);
471 public void removeReaderFinishedListener(ReaderFinishedListener listener) {
472 super.removeReaderFinishedListener(listener);
473 for(IndexReader sub : subReaders) {
474 sub.removeReaderFinishedListener(listener);