You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@lucene.apache.org by ja...@apache.org on 2013/05/30 09:53:46 UTC
svn commit: r1487777 [17/50] - in /lucene/dev/branches/security: ./
dev-tools/ dev-tools/eclipse/dot.settings/ dev-tools/idea/.idea/
dev-tools/idea/.idea/libraries/ dev-tools/idea/lucene/replicator/
dev-tools/maven/ dev-tools/maven/lucene/ dev-tools/ma...
Modified: lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/MergePolicy.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/MergePolicy.java?rev=1487777&r1=1487776&r2=1487777&view=diff
==============================================================================
--- lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/MergePolicy.java (original)
+++ lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/MergePolicy.java Thu May 30 07:53:18 2013
@@ -19,11 +19,13 @@ package org.apache.lucene.index;
import java.io.IOException;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.MergeInfo;
+import org.apache.lucene.util.FixedBitSet;
import org.apache.lucene.util.SetOnce.AlreadySetException;
import org.apache.lucene.util.SetOnce;
@@ -57,7 +59,32 @@ import org.apache.lucene.util.SetOnce;
*/
public abstract class MergePolicy implements java.io.Closeable, Cloneable {
-
+
+ /** A map of doc IDs. */
+ public static abstract class DocMap {
+ /** Sole constructor, typically invoked from sub-classes constructors. */
+ protected DocMap() {}
+
+ /** Return the new doc ID according to its old value. */
+ public abstract int map(int old);
+
+ /** Useful from an assert. */
+ boolean isConsistent(int maxDoc) {
+ final FixedBitSet targets = new FixedBitSet(maxDoc);
+ for (int i = 0; i < maxDoc; ++i) {
+ final int target = map(i);
+ if (target < 0 || target >= maxDoc) {
+ assert false : "out of range: " + target + " not in [0-" + maxDoc + "[";
+ return false;
+ } else if (targets.get(target)) {
+ assert false : target + " is already taken (" + i + ")";
+ return false;
+ }
+ }
+ return true;
+ }
+ }
+
/** OneMerge provides the information necessary to perform
* an individual primitive merge operation, resulting in
* a single new segment. The merge spec includes the
@@ -104,6 +131,47 @@ public abstract class MergePolicy implem
totalDocCount = count;
}
+ /** Expert: Get the list of readers to merge. Note that this list does not
+ * necessarily match the list of segments to merge and should only be used
+ * to feed SegmentMerger to initialize a merge. When a {@link OneMerge}
+ * reorders doc IDs, it must override {@link #getDocMap} too so that
+ * deletes that happened during the merge can be applied to the newly
+ * merged segment. */
+ public List<AtomicReader> getMergeReaders() throws IOException {
+ if (readers == null) {
+ throw new IllegalStateException("IndexWriter has not initialized readers from the segment infos yet");
+ }
+ final List<AtomicReader> readers = new ArrayList<AtomicReader>(this.readers.size());
+ for (AtomicReader reader : this.readers) {
+ if (reader.numDocs() > 0) {
+ readers.add(reader);
+ }
+ }
+ return Collections.unmodifiableList(readers);
+ }
+
+ /**
+ * Expert: Sets the {@link SegmentInfoPerCommit} of this {@link OneMerge}.
+ * Allows sub-classes to e.g. set diagnostics properties.
+ */
+ public void setInfo(SegmentInfoPerCommit info) {
+ this.info = info;
+ }
+
+ /** Expert: If {@link #getMergeReaders()} reorders document IDs, this method
+ * must be overridden to return a mapping from the <i>natural</i> doc ID
+ * (the doc ID that would result from a natural merge) to the actual doc
+ * ID. This mapping is used to apply deletions that happened during the
+ * merge to the new segment. */
+ public DocMap getDocMap(MergeState mergeState) {
+ return new DocMap() {
+ @Override
+ public int map(int docID) {
+ return docID;
+ }
+ };
+ }
+
/** Record that an exception occurred while executing
* this merge */
synchronized void setException(Throwable error) {
Modified: lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/MergeScheduler.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/MergeScheduler.java?rev=1487777&r1=1487776&r2=1487777&view=diff
==============================================================================
--- lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/MergeScheduler.java (original)
+++ lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/MergeScheduler.java Thu May 30 07:53:18 2013
@@ -27,7 +27,7 @@ import java.io.IOException;
*
* @lucene.experimental
*/
-public abstract class MergeScheduler implements Closeable {
+public abstract class MergeScheduler implements Closeable, Cloneable {
/** Sole constructor. (For invocation by subclass
* constructors, typically implicit.) */
@@ -40,4 +40,13 @@ public abstract class MergeScheduler imp
/** Close this MergeScheduler. */
@Override
public abstract void close() throws IOException;
+
+ @Override
+ public MergeScheduler clone() {
+ try {
+ return (MergeScheduler) super.clone();
+ } catch (CloneNotSupportedException e) {
+ throw new Error(e);
+ }
+ }
}
Modified: lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/MergeState.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/MergeState.java?rev=1487777&r1=1487776&r2=1487777&view=diff
==============================================================================
--- lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/MergeState.java (original)
+++ lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/MergeState.java Thu May 30 07:53:18 2013
@@ -129,13 +129,13 @@ public class MergeState {
}
/** {@link SegmentInfo} of the newly merged segment. */
- public SegmentInfo segmentInfo;
+ public final SegmentInfo segmentInfo;
/** {@link FieldInfos} of the newly merged segment. */
public FieldInfos fieldInfos;
/** Readers being merged. */
- public List<AtomicReader> readers;
+ public final List<AtomicReader> readers;
/** Maps docIDs around deletions. */
public DocMap[] docMaps;
@@ -145,10 +145,10 @@ public class MergeState {
/** Holds the CheckAbort instance, which is invoked
* periodically to see if the merge has been aborted. */
- public CheckAbort checkAbort;
+ public final CheckAbort checkAbort;
/** InfoStream for debugging messages. */
- public InfoStream infoStream;
+ public final InfoStream infoStream;
// TODO: get rid of this? it tells you which segments are 'aligned' (e.g. for bulk merging)
// but is this really so expensive to compute again in different components, versus once in SM?
@@ -162,7 +162,11 @@ public class MergeState {
public int matchedCount;
/** Sole constructor. */
- MergeState() {
+ MergeState(List<AtomicReader> readers, SegmentInfo segmentInfo, InfoStream infoStream, CheckAbort checkAbort) {
+ this.readers = readers;
+ this.segmentInfo = segmentInfo;
+ this.infoStream = infoStream;
+ this.checkAbort = checkAbort;
}
/**
Modified: lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/MultiDocValues.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/MultiDocValues.java?rev=1487777&r1=1487776&r2=1487777&view=diff
==============================================================================
--- lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/MultiDocValues.java (original)
+++ lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/MultiDocValues.java Thu May 30 07:53:18 2013
@@ -217,7 +217,7 @@ public class MultiDocValues {
} else {
TermsEnum enums[] = new TermsEnum[values.length];
for (int i = 0; i < values.length; i++) {
- enums[i] = new SortedDocValuesTermsEnum(values[i]);
+ enums[i] = values[i].termsEnum();
}
OrdinalMap mapping = new OrdinalMap(r.getCoreCacheKey(), enums);
return new MultiSortedDocValues(values, starts, mapping);
@@ -261,7 +261,7 @@ public class MultiDocValues {
} else {
TermsEnum enums[] = new TermsEnum[values.length];
for (int i = 0; i < values.length; i++) {
- enums[i] = new SortedSetDocValuesTermsEnum(values[i]);
+ enums[i] = values[i].termsEnum();
}
OrdinalMap mapping = new OrdinalMap(r.getCoreCacheKey(), enums);
return new MultiSortedSetDocValues(values, starts, mapping);
Modified: lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/MultiDocsAndPositionsEnum.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/MultiDocsAndPositionsEnum.java?rev=1487777&r1=1487776&r2=1487777&view=diff
==============================================================================
--- lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/MultiDocsAndPositionsEnum.java (original)
+++ lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/MultiDocsAndPositionsEnum.java Thu May 30 07:53:18 2013
@@ -89,9 +89,16 @@ public final class MultiDocsAndPositions
@Override
public int advance(int target) throws IOException {
+ assert target > doc;
while(true) {
if (current != null) {
- final int doc = current.advance(target-currentBase);
+ final int doc;
+ if (target < currentBase) {
+ // target was in the previous slice but there was no matching doc after it
+ doc = current.nextDoc();
+ } else {
+ doc = current.advance(target-currentBase);
+ }
if (doc == NO_MORE_DOCS) {
current = null;
} else {
@@ -170,6 +177,15 @@ public final class MultiDocsAndPositions
}
@Override
+ public long cost() {
+ long cost = 0;
+ for (int i = 0; i < numSubs; i++) {
+ cost += subs[i].docsAndPositionsEnum.cost();
+ }
+ return cost;
+ }
+
+ @Override
public String toString() {
return "MultiDocsAndPositionsEnum(" + Arrays.toString(getSubs()) + ")";
}
Modified: lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/MultiDocsEnum.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/MultiDocsEnum.java?rev=1487777&r1=1487776&r2=1487777&view=diff
==============================================================================
--- lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/MultiDocsEnum.java (original)
+++ lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/MultiDocsEnum.java Thu May 30 07:53:18 2013
@@ -90,9 +90,16 @@ public final class MultiDocsEnum extends
@Override
public int advance(int target) throws IOException {
+ assert target > doc;
while(true) {
if (current != null) {
- final int doc = current.advance(target-currentBase);
+ final int doc;
+ if (target < currentBase) {
+ // target was in the previous slice but there was no matching doc after it
+ doc = current.nextDoc();
+ } else {
+ doc = current.advance(target-currentBase);
+ }
if (doc == NO_MORE_DOCS) {
current = null;
} else {
@@ -129,6 +136,15 @@ public final class MultiDocsEnum extends
}
}
}
+
+ @Override
+ public long cost() {
+ long cost = 0;
+ for (int i = 0; i < numSubs; i++) {
+ cost += subs[i].docsEnum.cost();
+ }
+ return cost;
+ }
// TODO: implement bulk read more efficiently than super
/** Holds a {@link DocsEnum} along with the
Modified: lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/MultiFields.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/MultiFields.java?rev=1487777&r1=1487776&r2=1487777&view=diff
==============================================================================
--- lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/MultiFields.java (original)
+++ lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/MultiFields.java Thu May 30 07:53:18 2013
@@ -243,25 +243,6 @@ public final class MultiFields extends F
return -1;
}
- /** Returns the total number of occurrences of this term
- * across all documents (the sum of the freq() for each
- * doc that has this term). This will be -1 if the
- * codec doesn't support this measure. Note that, like
- * other term measures, this measure does not take
- * deleted documents into account.
- * @see TermsEnum#totalTermFreq()
- */
- public static long totalTermFreq(IndexReader r, String field, BytesRef text) throws IOException {
- final Terms terms = getTerms(r, field);
- if (terms != null) {
- final TermsEnum termsEnum = terms.iterator(null);
- if (termsEnum.seekExact(text, true)) {
- return termsEnum.totalTermFreq();
- }
- }
- return 0;
- }
-
/** Call this to get the (merged) FieldInfos for a
* composite reader.
* <p>
Modified: lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/NoDeletionPolicy.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/NoDeletionPolicy.java?rev=1487777&r1=1487776&r2=1487777&view=diff
==============================================================================
--- lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/NoDeletionPolicy.java (original)
+++ lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/NoDeletionPolicy.java Thu May 30 07:53:18 2013
@@ -24,7 +24,7 @@ import java.util.List;
* deleting them. This class is a singleton and can be accessed by referencing
* {@link #INSTANCE}.
*/
-public final class NoDeletionPolicy implements IndexDeletionPolicy {
+public final class NoDeletionPolicy extends IndexDeletionPolicy {
/** The single instance of this class. */
public static final IndexDeletionPolicy INSTANCE = new NoDeletionPolicy();
@@ -38,5 +38,10 @@ public final class NoDeletionPolicy impl
@Override
public void onInit(List<? extends IndexCommit> commits) {}
-
+
+ @Override
+ public IndexDeletionPolicy clone() {
+ return this;
+ }
+
}
Modified: lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/NoMergeScheduler.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/NoMergeScheduler.java?rev=1487777&r1=1487776&r2=1487777&view=diff
==============================================================================
--- lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/NoMergeScheduler.java (original)
+++ lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/NoMergeScheduler.java Thu May 30 07:53:18 2013
@@ -41,4 +41,10 @@ public final class NoMergeScheduler exte
@Override
public void merge(IndexWriter writer) {}
+
+ @Override
+ public MergeScheduler clone() {
+ return this;
+ }
+
}
Modified: lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/ParallelAtomicReader.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/ParallelAtomicReader.java?rev=1487777&r1=1487776&r2=1487777&view=diff
==============================================================================
--- lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/ParallelAtomicReader.java (original)
+++ lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/ParallelAtomicReader.java Thu May 30 07:53:18 2013
@@ -47,7 +47,7 @@ import org.apache.lucene.util.Bits;
* same order to the other indexes. <em>Failure to do so will result in
* undefined behavior</em>.
*/
-public final class ParallelAtomicReader extends AtomicReader {
+public class ParallelAtomicReader extends AtomicReader {
private final FieldInfos fieldInfos;
private final ParallelFields fields = new ParallelFields();
private final AtomicReader[] parallelReaders, storedFieldsReaders;
@@ -214,12 +214,6 @@ public final class ParallelAtomicReader
}
@Override
- public boolean hasDeletions() {
- ensureOpen();
- return hasDeletions;
- }
-
- @Override
public void document(int docID, StoredFieldVisitor visitor) throws IOException {
ensureOpen();
for (final AtomicReader reader: storedFieldsReaders) {
Modified: lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/ParallelCompositeReader.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/ParallelCompositeReader.java?rev=1487777&r1=1487776&r2=1487777&view=diff
==============================================================================
--- lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/ParallelCompositeReader.java (original)
+++ lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/ParallelCompositeReader.java Thu May 30 07:53:18 2013
@@ -20,7 +20,6 @@ package org.apache.lucene.index;
import java.io.IOException;
import java.util.Collections;
import java.util.IdentityHashMap;
-import java.util.Iterator;
import java.util.List;
import java.util.Set;
@@ -47,10 +46,10 @@ import java.util.Set;
* by number of documents per segment. If you use different {@link MergePolicy}s
* it might happen that the segment structure of your index is no longer predictable.
*/
-public final class ParallelCompositeReader extends BaseCompositeReader<IndexReader> {
+public class ParallelCompositeReader extends BaseCompositeReader<IndexReader> {
private final boolean closeSubReaders;
- private final Set<CompositeReader> completeReaderSet =
- Collections.newSetFromMap(new IdentityHashMap<CompositeReader,Boolean>());
+ private final Set<IndexReader> completeReaderSet =
+ Collections.newSetFromMap(new IdentityHashMap<IndexReader,Boolean>());
/** Create a ParallelCompositeReader based on the provided
* readers; auto-closes the given readers on {@link #close()}. */
@@ -72,12 +71,14 @@ public final class ParallelCompositeRead
this.closeSubReaders = closeSubReaders;
Collections.addAll(completeReaderSet, readers);
Collections.addAll(completeReaderSet, storedFieldReaders);
- // do this finally so any Exceptions occurred before don't affect refcounts:
+ // update ref-counts (like MultiReader):
if (!closeSubReaders) {
- for (CompositeReader reader : completeReaderSet) {
+ for (final IndexReader reader : completeReaderSet) {
reader.incRef();
}
}
+ // finally add our own synthetic readers, so we close or decRef them, too (it does not matter what we do)
+ completeReaderSet.addAll(getSequentialSubReaders());
}
private static IndexReader[] prepareSubReaders(CompositeReader[] readers, CompositeReader[] storedFieldsReaders) throws IOException {
@@ -112,10 +113,12 @@ public final class ParallelCompositeRead
for (int j = 0; j < storedFieldsReaders.length; j++) {
storedSubs[j] = (AtomicReader) storedFieldsReaders[j].getSequentialSubReaders().get(i);
}
- // we simply enable closing of subReaders, to prevent incRefs on subReaders
- // -> for synthetic subReaders, close() is never
- // called by our doClose()
- subReaders[i] = new ParallelAtomicReader(true, atomicSubs, storedSubs);
+ // We pass true for closeSubs and we prevent closing of subreaders in doClose():
+ // By this the synthetic throw-away readers used here are completely invisible to ref-counting
+ subReaders[i] = new ParallelAtomicReader(true, atomicSubs, storedSubs) {
+ @Override
+ protected void doClose() {}
+ };
} else {
assert firstSubReaders.get(i) instanceof CompositeReader;
final CompositeReader[] compositeSubs = new CompositeReader[readers.length];
@@ -126,9 +129,12 @@ public final class ParallelCompositeRead
for (int j = 0; j < storedFieldsReaders.length; j++) {
storedSubs[j] = (CompositeReader) storedFieldsReaders[j].getSequentialSubReaders().get(i);
}
- // we simply enable closing of subReaders, to prevent incRefs on subReaders
- // -> for synthetic subReaders, close() is never called by our doClose()
- subReaders[i] = new ParallelCompositeReader(true, compositeSubs, storedSubs);
+ // We pass true for closeSubs and we prevent closing of subreaders in doClose():
+ // By this the synthetic throw-away readers used here are completely invisible to ref-counting
+ subReaders[i] = new ParallelCompositeReader(true, compositeSubs, storedSubs) {
+ @Override
+ protected void doClose() {}
+ };
}
}
return subReaders;
@@ -159,19 +165,9 @@ public final class ParallelCompositeRead
}
@Override
- public String toString() {
- final StringBuilder buffer = new StringBuilder("ParallelCompositeReader(");
- for (final Iterator<CompositeReader> iter = completeReaderSet.iterator(); iter.hasNext();) {
- buffer.append(iter.next());
- if (iter.hasNext()) buffer.append(", ");
- }
- return buffer.append(')').toString();
- }
-
- @Override
protected synchronized void doClose() throws IOException {
IOException ioe = null;
- for (final CompositeReader reader : completeReaderSet) {
+ for (final IndexReader reader : completeReaderSet) {
try {
if (closeSubReaders) {
reader.close();
Modified: lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/PersistentSnapshotDeletionPolicy.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/PersistentSnapshotDeletionPolicy.java?rev=1487777&r1=1487776&r2=1487777&view=diff
==============================================================================
--- lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/PersistentSnapshotDeletionPolicy.java (original)
+++ lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/PersistentSnapshotDeletionPolicy.java Thu May 30 07:53:18 2013
@@ -18,74 +18,71 @@ package org.apache.lucene.index;
*/
import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
import java.util.HashMap;
import java.util.List;
-import java.util.Map;
import java.util.Map.Entry;
+import java.util.Map;
-import org.apache.lucene.document.Document;
-import org.apache.lucene.document.Field;
-import org.apache.lucene.document.FieldType;
-import org.apache.lucene.document.StoredField;
+import org.apache.lucene.codecs.CodecUtil;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.store.Directory;
-import org.apache.lucene.util.Version;
+import org.apache.lucene.store.IOContext;
+import org.apache.lucene.store.IndexInput;
+import org.apache.lucene.store.IndexOutput;
+import org.apache.lucene.util.IOUtils;
/**
* A {@link SnapshotDeletionPolicy} which adds a persistence layer so that
* snapshots can be maintained across the life of an application. The snapshots
* are persisted in a {@link Directory} and are committed as soon as
- * {@link #snapshot(String)} or {@link #release(String)} is called.
- * <p>
- * <b>NOTE:</b> this class receives a {@link Directory} to persist the data into
- * a Lucene index. It is highly recommended to use a dedicated directory (and on
- * stable storage as well) for persisting the snapshots' information, and not
- * reuse the content index directory, or otherwise conflicts and index
- * corruption will occur.
+ * {@link #snapshot()} or {@link #release(IndexCommit)} is called.
* <p>
- * <b>NOTE:</b> you should call {@link #close()} when you're done using this
- * class for safety (it will close the {@link IndexWriter} instance used).
+ * <b>NOTE:</b> Sharing {@link PersistentSnapshotDeletionPolicy}s that write to
+ * the same directory across {@link IndexWriter}s will corrupt snapshots. You
+ * should make sure every {@link IndexWriter} has its own
+ * {@link PersistentSnapshotDeletionPolicy} and that they all write to a
+ * different {@link Directory}. It is OK to use the same
+ * Directory that holds the index.
+ *
+ * <p> This class adds a {@link #release(long)} method to
+ * release commits from a previous snapshot's {@link IndexCommit#getGeneration}.
+ *
+ * @lucene.experimental
*/
public class PersistentSnapshotDeletionPolicy extends SnapshotDeletionPolicy {
- // Used to validate that the given directory includes just one document w/ the
- // given ID field. Otherwise, it's not a valid Directory for snapshotting.
- private static final String SNAPSHOTS_ID = "$SNAPSHOTS_DOC$";
+ /** Prefix used for the save file. */
+ public static final String SNAPSHOTS_PREFIX = "snapshots_";
+ private static final int VERSION_START = 0;
+ private static final int VERSION_CURRENT = VERSION_START;
+ private static final String CODEC_NAME = "snapshots";
// The index writer which maintains the snapshots metadata
- private final IndexWriter writer;
+ private long nextWriteGen;
+
+ private final Directory dir;
/**
- * Reads the snapshots information from the given {@link Directory}. This
- * method can be used if the snapshots information is needed, however you
- * cannot instantiate the deletion policy (because e.g., some other process
- * keeps a lock on the snapshots directory).
+ * {@link PersistentSnapshotDeletionPolicy} wraps another
+ * {@link IndexDeletionPolicy} to enable flexible
+ * snapshotting, passing {@link OpenMode#CREATE_OR_APPEND}
+ * by default.
+ *
+ * @param primary
+ * the {@link IndexDeletionPolicy} that is used on non-snapshotted
+ * commits. Snapshotted commits, by definition, are not deleted until
+ * explicitly released via {@link #release}.
+ * @param dir
+ * the {@link Directory} which will be used to persist the snapshots
+ * information.
*/
- public static Map<String, String> readSnapshotsInfo(Directory dir) throws IOException {
- IndexReader r = DirectoryReader.open(dir);
- Map<String, String> snapshots = new HashMap<String, String>();
- try {
- int numDocs = r.numDocs();
- // index is allowed to have exactly one document or 0.
- if (numDocs == 1) {
- StoredDocument doc = r.document(r.maxDoc() - 1);
- if (doc.getField(SNAPSHOTS_ID) == null) {
- throw new IllegalStateException("directory is not a valid snapshots store!");
- }
- for (StorableField f : doc) {
- if (!f.name().equals(SNAPSHOTS_ID))
- snapshots.put(f.name(), f.stringValue());
- }
- } else if (numDocs != 0) {
- throw new IllegalStateException(
- "should be at most 1 document in the snapshots directory: " + numDocs);
- }
- } finally {
- r.close();
- }
- return snapshots;
+ public PersistentSnapshotDeletionPolicy(IndexDeletionPolicy primary,
+ Directory dir) throws IOException {
+ this(primary, dir, OpenMode.CREATE_OR_APPEND);
}
-
+
/**
* {@link PersistentSnapshotDeletionPolicy} wraps another
* {@link IndexDeletionPolicy} to enable flexible snapshotting.
@@ -93,7 +90,7 @@ public class PersistentSnapshotDeletionP
* @param primary
* the {@link IndexDeletionPolicy} that is used on non-snapshotted
* commits. Snapshotted commits, by definition, are not deleted until
- * explicitly released via {@link #release(String)}.
+ * explicitly released via {@link #release}.
* @param dir
* the {@link Directory} which will be used to persist the snapshots
* information.
@@ -101,99 +98,198 @@ public class PersistentSnapshotDeletionP
* specifies whether a new index should be created, deleting all
* existing snapshots information (immediately), or open an existing
* index, initializing the class with the snapshots information.
- * @param matchVersion
- * specifies the {@link Version} that should be used when opening the
- * IndexWriter.
*/
public PersistentSnapshotDeletionPolicy(IndexDeletionPolicy primary,
- Directory dir, OpenMode mode, Version matchVersion) throws IOException {
- super(primary, null);
+ Directory dir, OpenMode mode) throws IOException {
+ super(primary);
+
+ this.dir = dir;
- // Initialize the index writer over the snapshot directory.
- writer = new IndexWriter(dir, new IndexWriterConfig(matchVersion, null).setOpenMode(mode));
- if (mode != OpenMode.APPEND) {
- // IndexWriter no longer creates a first commit on an empty Directory. So
- // if we were asked to CREATE*, call commit() just to be sure. If the
- // index contains information and mode is CREATE_OR_APPEND, it's a no-op.
- writer.commit();
+ if (mode == OpenMode.CREATE) {
+ clearPriorSnapshots();
}
- try {
- // Initializes the snapshots information. This code should basically run
- // only if mode != CREATE, but if it is, it's no harm as we only open the
- // reader once and immediately close it.
- for (Entry<String, String> e : readSnapshotsInfo(dir).entrySet()) {
- registerSnapshotInfo(e.getKey(), e.getValue(), null);
- }
- } catch (RuntimeException e) {
- writer.close(); // don't leave any open file handles
- throw e;
- } catch (IOException e) {
- writer.close(); // don't leave any open file handles
- throw e;
+ loadPriorSnapshots();
+
+ if (mode == OpenMode.APPEND && nextWriteGen == 0) {
+ throw new IllegalStateException("no snapshots stored in this directory");
}
}
+ /**
+ * Snapshots the last commit. Once this method returns, the
+ * snapshot information is persisted in the directory.
+ *
+ * @see SnapshotDeletionPolicy#snapshot
+ */
@Override
- public synchronized void onInit(List<? extends IndexCommit> commits)
- throws IOException {
- // super.onInit() needs to be called first to ensure that initialization
- // behaves as expected. The superclass, SnapshotDeletionPolicy, ensures
- // that any snapshot IDs with empty IndexCommits are released. Since this
- // happens, this class needs to persist these changes.
- super.onInit(commits);
- persistSnapshotInfos(null, null);
+ public synchronized IndexCommit snapshot() throws IOException {
+ IndexCommit ic = super.snapshot();
+ boolean success = false;
+ try {
+ persist();
+ success = true;
+ } finally {
+ if (!success) {
+ try {
+ super.release(ic);
+ } catch (Exception e) {
+ // Suppress so we keep throwing original exception
+ }
+ }
+ }
+ return ic;
}
/**
- * Snapshots the last commit using the given ID. Once this method returns, the
- * snapshot information is persisted in the directory.
+ * Deletes a snapshotted commit. Once this method returns, the snapshot
+ * information is persisted in the directory.
*
- * @see SnapshotDeletionPolicy#snapshot(String)
+ * @see SnapshotDeletionPolicy#release
*/
@Override
- public synchronized IndexCommit snapshot(String id) throws IOException {
- checkSnapshotted(id);
- if (SNAPSHOTS_ID.equals(id)) {
- throw new IllegalArgumentException(id + " is reserved and cannot be used as a snapshot id");
+ public synchronized void release(IndexCommit commit) throws IOException {
+ super.release(commit);
+ boolean success = false;
+ try {
+ persist();
+ success = true;
+ } finally {
+ if (!success) {
+ try {
+ incRef(commit);
+ } catch (Exception e) {
+ // Suppress so we keep throwing original exception
+ }
+ }
}
- persistSnapshotInfos(id, lastCommit.getSegmentsFileName());
- return super.snapshot(id);
}
/**
- * Deletes a snapshotted commit by ID. Once this method returns, the snapshot
- * information is committed to the directory.
+ * Deletes a snapshotted commit by generation. Once this method returns, the snapshot
+ * information is persisted in the directory.
*
- * @see SnapshotDeletionPolicy#release(String)
+ * @see IndexCommit#getGeneration
+ * @see SnapshotDeletionPolicy#release
*/
- @Override
- public synchronized void release(String id) throws IOException {
- super.release(id);
- persistSnapshotInfos(null, null);
+ public synchronized void release(long gen) throws IOException {
+ super.releaseGen(gen);
+ persist();
}
- /** Closes the index which writes the snapshots to the directory. */
- public void close() throws IOException {
- writer.close();
+ synchronized private void persist() throws IOException {
+ String fileName = SNAPSHOTS_PREFIX + nextWriteGen;
+ IndexOutput out = dir.createOutput(fileName, IOContext.DEFAULT);
+ boolean success = false;
+ try {
+ CodecUtil.writeHeader(out, CODEC_NAME, VERSION_CURRENT);
+ out.writeVInt(refCounts.size());
+ for(Entry<Long,Integer> ent : refCounts.entrySet()) {
+ out.writeVLong(ent.getKey());
+ out.writeVInt(ent.getValue());
+ }
+ success = true;
+ } finally {
+ if (!success) {
+ IOUtils.closeWhileHandlingException(out);
+ try {
+ dir.deleteFile(fileName);
+ } catch (Exception e) {
+ // Suppress so we keep throwing original exception
+ }
+ } else {
+ IOUtils.close(out);
+ }
+ }
+
+ dir.sync(Collections.singletonList(fileName));
+
+ if (nextWriteGen > 0) {
+ String lastSaveFile = SNAPSHOTS_PREFIX + (nextWriteGen-1);
+ if (dir.fileExists(lastSaveFile)) {
+ dir.deleteFile(lastSaveFile);
+ }
+ }
+
+ nextWriteGen++;
+ }
+
+ private synchronized void clearPriorSnapshots() throws IOException {
+ for(String file : dir.listAll()) {
+ if (file.startsWith(SNAPSHOTS_PREFIX)) {
+ dir.deleteFile(file);
+ }
+ }
+ }
+
+ /** Returns the file name the snapshots are currently
+ * saved to, or null if no snapshots have been saved. */
+ public String getLastSaveFile() {
+ if (nextWriteGen == 0) {
+ return null;
+ } else {
+ return SNAPSHOTS_PREFIX + (nextWriteGen-1);
+ }
}
/**
- * Persists all snapshots information. If the given id and segment are not
- * null, it persists their information as well.
+ * Reads the snapshots information from the given {@link Directory}. This
+ * method can be used if the snapshots information is needed, however you
+ * cannot instantiate the deletion policy (because e.g., some other process
+ * keeps a lock on the snapshots directory).
*/
- private void persistSnapshotInfos(String id, String segment) throws IOException {
- writer.deleteAll();
- Document d = new Document();
- d.add(new StoredField(SNAPSHOTS_ID, ""));
- for (Entry<String, String> e : super.getSnapshots().entrySet()) {
- d.add(new StoredField(e.getKey(), e.getValue()));
+ private synchronized void loadPriorSnapshots() throws IOException {
+ long genLoaded = -1;
+ IOException ioe = null;
+ List<String> snapshotFiles = new ArrayList<String>();
+ for(String file : dir.listAll()) {
+ if (file.startsWith(SNAPSHOTS_PREFIX)) {
+ long gen = Long.parseLong(file.substring(SNAPSHOTS_PREFIX.length()));
+ if (genLoaded == -1 || gen > genLoaded) {
+ snapshotFiles.add(file);
+ Map<Long,Integer> m = new HashMap<Long,Integer>();
+ IndexInput in = dir.openInput(file, IOContext.DEFAULT);
+ try {
+ CodecUtil.checkHeader(in, CODEC_NAME, VERSION_START, VERSION_START);
+ int count = in.readVInt();
+ for(int i=0;i<count;i++) {
+ long commitGen = in.readVLong();
+ int refCount = in.readVInt();
+ m.put(commitGen, refCount);
+ }
+ } catch (IOException ioe2) {
+ // Save first exception & throw in the end
+ if (ioe == null) {
+ ioe = ioe2;
+ }
+ } finally {
+ in.close();
+ }
+
+ genLoaded = gen;
+ refCounts.clear();
+ refCounts.putAll(m);
+ }
+ }
}
- if (id != null) {
- d.add(new StoredField(id, segment));
+
+ if (genLoaded == -1) {
+ // Nothing was loaded...
+ if (ioe != null) {
+ // ... not for lack of trying:
+ throw ioe;
+ }
+ } else {
+ if (snapshotFiles.size() > 1) {
+ // Remove any broken / old snapshot files:
+ String curFileName = SNAPSHOTS_PREFIX + genLoaded;
+ for(String file : snapshotFiles) {
+ if (!curFileName.equals(file)) {
+ dir.deleteFile(file);
+ }
+ }
+ }
+ nextWriteGen = 1+genLoaded;
}
- writer.addDocument(d);
- writer.commit();
}
-
}
Modified: lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/SegmentInfos.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/SegmentInfos.java?rev=1487777&r1=1487776&r2=1487777&view=diff
==============================================================================
--- lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/SegmentInfos.java (original)
+++ lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/SegmentInfos.java Thu May 30 07:53:18 2013
@@ -242,6 +242,39 @@ public final class SegmentInfos implemen
}
}
+ /**
+ * A utility for writing the {@link IndexFileNames#SEGMENTS_GEN} file to a
+ * {@link Directory}.
+ *
+ * <p>
+ * <b>NOTE:</b> this is an internal utility which is kept public so that it's
+ * accessible by code from other packages. You should avoid calling this
+ * method unless you're absolutely sure what you're doing!
+ *
+ * @lucene.internal
+ */
+ public static void writeSegmentsGen(Directory dir, long generation) {
+ try {
+ IndexOutput genOutput = dir.createOutput(IndexFileNames.SEGMENTS_GEN, IOContext.READONCE);
+ try {
+ genOutput.writeInt(FORMAT_SEGMENTS_GEN_CURRENT);
+ genOutput.writeLong(generation);
+ genOutput.writeLong(generation);
+ } finally {
+ genOutput.close();
+ dir.sync(Collections.singleton(IndexFileNames.SEGMENTS_GEN));
+ }
+ } catch (Throwable t) {
+ // It's OK if we fail to write this file since it's
+ // used only as one of the retry fallbacks.
+ try {
+ dir.deleteFile(IndexFileNames.SEGMENTS_GEN);
+ } catch (Throwable t2) {
+ // Ignore; this file is only used in a retry
+ // fallback on init.
+ }
+ }
+ }
/**
* Get the next segments_N filename that will be written.
@@ -848,27 +881,7 @@ public final class SegmentInfos implemen
}
lastGeneration = generation;
-
- try {
- IndexOutput genOutput = dir.createOutput(IndexFileNames.SEGMENTS_GEN, IOContext.READONCE);
- try {
- genOutput.writeInt(FORMAT_SEGMENTS_GEN_CURRENT);
- genOutput.writeLong(generation);
- genOutput.writeLong(generation);
- } finally {
- genOutput.close();
- dir.sync(Collections.singleton(IndexFileNames.SEGMENTS_GEN));
- }
- } catch (Throwable t) {
- // It's OK if we fail to write this file since it's
- // used only as one of the retry fallbacks.
- try {
- dir.deleteFile(IndexFileNames.SEGMENTS_GEN);
- } catch (Throwable t2) {
- // Ignore; this file is only used in a retry
- // fallback on init.
- }
- }
+ writeSegmentsGen(dir, generation);
}
/** Writes & syncs to the Directory dir, taking care to
Modified: lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/SegmentMerger.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/SegmentMerger.java?rev=1487777&r1=1487776&r2=1487777&view=diff
==============================================================================
--- lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/SegmentMerger.java (original)
+++ lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/SegmentMerger.java Thu May 30 07:53:18 2013
@@ -34,12 +34,11 @@ import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.InfoStream;
/**
- * The SegmentMerger class combines two or more Segments, represented by an IndexReader ({@link #add},
- * into a single Segment. After adding the appropriate readers, call the merge method to combine the
+ * The SegmentMerger class combines two or more Segments, represented by an
+ * IndexReader, into a single Segment. Call the merge method to combine the
* segments.
*
* @see #merge
- * @see #add
*/
final class SegmentMerger {
private final Directory directory;
@@ -49,16 +48,13 @@ final class SegmentMerger {
private final IOContext context;
- private final MergeState mergeState = new MergeState();
+ private final MergeState mergeState;
private final FieldInfos.Builder fieldInfosBuilder;
// note, just like in codec apis Directory 'dir' is NOT the same as segmentInfo.dir!!
- SegmentMerger(SegmentInfo segmentInfo, InfoStream infoStream, Directory dir, int termIndexInterval,
+ SegmentMerger(List<AtomicReader> readers, SegmentInfo segmentInfo, InfoStream infoStream, Directory dir, int termIndexInterval,
MergeState.CheckAbort checkAbort, FieldInfos.FieldNumbers fieldNumbers, IOContext context) {
- mergeState.segmentInfo = segmentInfo;
- mergeState.infoStream = infoStream;
- mergeState.readers = new ArrayList<AtomicReader>();
- mergeState.checkAbort = checkAbort;
+ mergeState = new MergeState(readers, segmentInfo, infoStream, checkAbort);
directory = dir;
this.termIndexInterval = termIndexInterval;
this.codec = segmentInfo.getCodec();
@@ -67,21 +63,7 @@ final class SegmentMerger {
}
/**
- * Add an IndexReader to the collection of readers that are to be merged
- */
- void add(IndexReader reader) {
- for (final AtomicReaderContext ctx : reader.leaves()) {
- final AtomicReader r = ctx.reader();
- mergeState.readers.add(r);
- }
- }
-
- void add(SegmentReader reader) {
- mergeState.readers.add(reader);
- }
-
- /**
- * Merges the readers specified by the {@link #add} method into the directory passed to the constructor
+ * Merges the readers into the directory passed to the constructor
* @return The number of documents that were merged
* @throws CorruptIndexException if the index is corrupt
* @throws IOException if there is a low-level IO error
Modified: lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/SegmentReader.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/SegmentReader.java?rev=1487777&r1=1487776&r2=1487777&view=diff
==============================================================================
--- lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/SegmentReader.java (original)
+++ lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/SegmentReader.java Thu May 30 07:53:18 2013
@@ -114,12 +114,6 @@ public final class SegmentReader extends
}
@Override
- public boolean hasDeletions() {
- // Don't call ensureOpen() here (it could affect performance)
- return liveDocs != null;
- }
-
- @Override
public FieldInfos getFieldInfos() {
ensureOpen();
return core.fieldInfos;
@@ -198,7 +192,7 @@ public final class SegmentReader extends
/**
* Return the SegmentInfoPerCommit of the segment this reader is reading.
*/
- SegmentInfoPerCommit getSegmentInfo() {
+ public SegmentInfoPerCommit getSegmentInfo() {
return si;
}
Modified: lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/SlowCompositeReaderWrapper.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/SlowCompositeReaderWrapper.java?rev=1487777&r1=1487776&r2=1487777&view=diff
==============================================================================
--- lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/SlowCompositeReaderWrapper.java (original)
+++ lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/SlowCompositeReaderWrapper.java Thu May 30 07:53:18 2013
@@ -219,12 +219,6 @@ public final class SlowCompositeReaderWr
ensureOpen();
return MultiFields.getMergedFieldInfos(in);
}
-
- @Override
- public boolean hasDeletions() {
- ensureOpen();
- return liveDocs != null;
- }
@Override
public Object getCoreCacheKey() {
Modified: lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/SnapshotDeletionPolicy.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/SnapshotDeletionPolicy.java?rev=1487777&r1=1487776&r2=1487777&view=diff
==============================================================================
--- lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/SnapshotDeletionPolicy.java (original)
+++ lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/SnapshotDeletionPolicy.java Thu May 30 07:53:18 2013
@@ -19,18 +19,15 @@ package org.apache.lucene.index;
import java.util.Collection;
import java.util.HashMap;
-import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
-import java.util.Set;
-import java.util.Map.Entry;
import java.io.IOException;
import org.apache.lucene.store.Directory;
/**
- * An {@link IndexDeletionPolicy} that wraps around any other
+ * An {@link IndexDeletionPolicy} that wraps any other
* {@link IndexDeletionPolicy} and adds the ability to hold and later release
* snapshots of an index. While a snapshot is held, the {@link IndexWriter} will
* not remove any files associated with it even if the index is otherwise being
@@ -41,37 +38,178 @@ import org.apache.lucene.store.Directory
*
* <p>
* This class maintains all snapshots in-memory, and so the information is not
- * persisted and not protected against system failures. If persistency is
- * important, you can use {@link PersistentSnapshotDeletionPolicy} (or your own
- * extension) and when creating a new instance of this deletion policy, pass the
- * persistent snapshots information to
- * {@link #SnapshotDeletionPolicy(IndexDeletionPolicy, Map)}.
+ * persisted and not protected against system failures. If persistence is
+ * important, you can use {@link PersistentSnapshotDeletionPolicy}.
*
* @lucene.experimental
*/
-public class SnapshotDeletionPolicy implements IndexDeletionPolicy {
+public class SnapshotDeletionPolicy extends IndexDeletionPolicy {
- /** Holds a Snapshot's information. */
- private static class SnapshotInfo {
- String id;
- String segmentsFileName;
- IndexCommit commit;
-
- public SnapshotInfo(String id, String segmentsFileName, IndexCommit commit) {
- this.id = id;
- this.segmentsFileName = segmentsFileName;
- this.commit = commit;
+ /** Records how many snapshots are held against each
+ * commit generation */
+ protected Map<Long,Integer> refCounts = new HashMap<Long,Integer>();
+
+ /** Used to map gen to IndexCommit. */
+ protected Map<Long,IndexCommit> indexCommits = new HashMap<Long,IndexCommit>();
+
+ /** Wrapped {@link IndexDeletionPolicy} */
+ private IndexDeletionPolicy primary;
+
+ /** Most recently committed {@link IndexCommit}. */
+ protected IndexCommit lastCommit;
+
+ /** Used to detect misuse */
+ private boolean initCalled;
+
+ /** Sole constructor, taking the incoming {@link
+ * IndexDeletionPolicy} to wrap. */
+ public SnapshotDeletionPolicy(IndexDeletionPolicy primary) {
+ this.primary = primary;
+ }
+
+ @Override
+ public synchronized void onCommit(List<? extends IndexCommit> commits)
+ throws IOException {
+ primary.onCommit(wrapCommits(commits));
+ lastCommit = commits.get(commits.size() - 1);
+ }
+
+ @Override
+ public synchronized void onInit(List<? extends IndexCommit> commits)
+ throws IOException {
+ initCalled = true;
+ primary.onInit(wrapCommits(commits));
+ for(IndexCommit commit : commits) {
+ if (refCounts.containsKey(commit.getGeneration())) {
+ indexCommits.put(commit.getGeneration(), commit);
+ }
}
-
- @Override
- public String toString() {
- return id + " : " + segmentsFileName;
+ if (!commits.isEmpty()) {
+ lastCommit = commits.get(commits.size() - 1);
+ }
+ }
+
+ /**
+ * Release a snapshotted commit.
+ *
+ * @param commit
+ * the commit previously returned by {@link #snapshot}
+ */
+ public synchronized void release(IndexCommit commit) throws IOException {
+ long gen = commit.getGeneration();
+ releaseGen(gen);
+ }
+
+ /** Release a snapshot by generation. */
+ protected void releaseGen(long gen) throws IOException {
+ if (!initCalled) {
+ throw new IllegalStateException("this instance is not being used by IndexWriter; be sure to use the instance returned from writer.getConfig().getIndexDeletionPolicy()");
+ }
+ Integer refCount = refCounts.get(gen);
+ if (refCount == null) {
+ throw new IllegalArgumentException("commit gen=" + gen + " is not currently snapshotted");
+ }
+ int refCountInt = refCount.intValue();
+ assert refCountInt > 0;
+ refCountInt--;
+ if (refCountInt == 0) {
+ refCounts.remove(gen);
+ indexCommits.remove(gen);
+ } else {
+ refCounts.put(gen, refCountInt);
+ }
+ }
+
+ /** Increments the refCount for this {@link IndexCommit}. */
+ protected synchronized void incRef(IndexCommit ic) {
+ long gen = ic.getGeneration();
+ Integer refCount = refCounts.get(gen);
+ int refCountInt;
+ if (refCount == null) {
+ indexCommits.put(gen, lastCommit);
+ refCountInt = 0;
+ } else {
+ refCountInt = refCount.intValue();
+ }
+ refCounts.put(gen, refCountInt+1);
+ }
+
+ /**
+ * Snapshots the last commit and returns it. Once a commit is 'snapshotted,' it is protected
+ * from deletion (as long as this {@link IndexDeletionPolicy} is used). The
+ * snapshot can be removed by calling {@link #release(IndexCommit)} followed
+ * by a call to {@link IndexWriter#deleteUnusedFiles()}.
+ *
+ * <p>
+ * <b>NOTE:</b> while the snapshot is held, the files it references will not
+ * be deleted, which will consume additional disk space in your index. If you
+ * take a snapshot at a particularly bad time (say just before you call
+ * forceMerge) then in the worst case this could consume an extra 1X of your
+ * total index size, until you release the snapshot.
+ *
+ * @throws IllegalStateException
+ * if this index does not have any commits yet
+ * @return the {@link IndexCommit} that was snapshotted.
+ */
+ public synchronized IndexCommit snapshot() throws IOException {
+ if (!initCalled) {
+ throw new IllegalStateException("this instance is not being used by IndexWriter; be sure to use the instance returned from writer.getConfig().getIndexDeletionPolicy()");
+ }
+ if (lastCommit == null) {
+ // No commit yet, eg this is a new IndexWriter:
+ throw new IllegalStateException("No index commit to snapshot");
+ }
+
+ incRef(lastCommit);
+
+ return lastCommit;
+ }
+
+ /** Returns all IndexCommits held by at least one snapshot. */
+ public synchronized List<IndexCommit> getSnapshots() {
+ return new ArrayList<IndexCommit>(indexCommits.values());
+ }
+
+ /** Returns the total number of snapshots currently held. */
+ public synchronized int getSnapshotCount() {
+ int total = 0;
+ for(Integer refCount : refCounts.values()) {
+ total += refCount.intValue();
}
+
+ return total;
+ }
+
+ /** Retrieve an {@link IndexCommit} from its generation;
+ * returns null if this IndexCommit is not currently
+ * snapshotted */
+ public synchronized IndexCommit getIndexCommit(long gen) {
+ return indexCommits.get(gen);
+ }
+
+ @Override
+ public synchronized IndexDeletionPolicy clone() {
+ SnapshotDeletionPolicy other = (SnapshotDeletionPolicy) super.clone();
+ other.primary = this.primary.clone();
+ other.lastCommit = null;
+ other.refCounts = new HashMap<Long,Integer>(refCounts);
+ other.indexCommits = new HashMap<Long,IndexCommit>(indexCommits);
+ return other;
+ }
+
+ /** Wraps each {@link IndexCommit} as a {@link
+ * SnapshotCommitPoint}. */
+ private List<IndexCommit> wrapCommits(List<? extends IndexCommit> commits) {
+ List<IndexCommit> wrappedCommits = new ArrayList<IndexCommit>(commits.size());
+ for (IndexCommit ic : commits) {
+ wrappedCommits.add(new SnapshotCommitPoint(ic));
+ }
+ return wrappedCommits;
}
/** Wraps a provided {@link IndexCommit} and prevents it
* from being deleted. */
- protected class SnapshotCommitPoint extends IndexCommit {
+ private class SnapshotCommitPoint extends IndexCommit {
/** The {@link IndexCommit} we are preventing from deletion. */
protected IndexCommit cp;
@@ -87,20 +225,12 @@ public class SnapshotDeletionPolicy impl
return "SnapshotDeletionPolicy.SnapshotCommitPoint(" + cp + ")";
}
- /**
- * Returns true if this segment can be deleted. The default implementation
- * returns false if this segment is currently held as snapshot.
- */
- protected boolean shouldDelete(String segmentsFileName) {
- return !segmentsFileToIDs.containsKey(segmentsFileName);
- }
-
@Override
public void delete() {
synchronized (SnapshotDeletionPolicy.this) {
// Suppress the delete request if this commit point is
// currently snapshotted.
- if (shouldDelete(getSegmentsFileName())) {
+ if (!refCounts.containsKey(cp.getGeneration())) {
cp.delete();
}
}
@@ -141,236 +271,4 @@ public class SnapshotDeletionPolicy impl
return cp.getSegmentCount();
}
}
-
- /** Snapshots info */
- private Map<String, SnapshotInfo> idToSnapshot = new HashMap<String, SnapshotInfo>();
-
- // multiple IDs could point to the same commit point (segments file name)
- private Map<String, Set<String>> segmentsFileToIDs = new HashMap<String, Set<String>>();
-
- private IndexDeletionPolicy primary;
-
- /** Most recently committed {@link IndexCommit}. */
- protected IndexCommit lastCommit;
-
- /** Sole constructor, taking the incoming {@link
- * IndexDeletionPolicy} to wrap. */
- public SnapshotDeletionPolicy(IndexDeletionPolicy primary) {
- this.primary = primary;
- }
-
- /**
- * {@link SnapshotDeletionPolicy} wraps another {@link IndexDeletionPolicy} to
- * enable flexible snapshotting.
- *
- * @param primary
- * the {@link IndexDeletionPolicy} that is used on non-snapshotted
- * commits. Snapshotted commits, are not deleted until explicitly
- * released via {@link #release(String)}
- * @param snapshotsInfo
- * A mapping of snapshot ID to the segments filename that is being
- * snapshotted. The expected input would be the output of
- * {@link #getSnapshots()}. A null value signals that there are no
- * initial snapshots to maintain.
- */
- public SnapshotDeletionPolicy(IndexDeletionPolicy primary,
- Map<String, String> snapshotsInfo) {
- this(primary);
-
- if (snapshotsInfo != null) {
- // Add the ID->segmentIDs here - the actual IndexCommits will be
- // reconciled on the call to onInit()
- for (Entry<String, String> e : snapshotsInfo.entrySet()) {
- registerSnapshotInfo(e.getKey(), e.getValue(), null);
- }
- }
- }
-
- /**
- * Checks if the given id is already used by another snapshot, and throws
- * {@link IllegalStateException} if it is.
- */
- protected void checkSnapshotted(String id) {
- if (isSnapshotted(id)) {
- throw new IllegalStateException("Snapshot ID " + id
- + " is already used - must be unique");
- }
- }
-
- /** Registers the given snapshot information. */
- protected void registerSnapshotInfo(String id, String segment, IndexCommit commit) {
- idToSnapshot.put(id, new SnapshotInfo(id, segment, commit));
- Set<String> ids = segmentsFileToIDs.get(segment);
- if (ids == null) {
- ids = new HashSet<String>();
- segmentsFileToIDs.put(segment, ids);
- }
- ids.add(id);
- }
-
- /** Wraps each {@link IndexCommit} as a {@link
- * SnapshotCommitPoint}. */
- protected List<IndexCommit> wrapCommits(List<? extends IndexCommit> commits) {
- List<IndexCommit> wrappedCommits = new ArrayList<IndexCommit>(commits.size());
- for (IndexCommit ic : commits) {
- wrappedCommits.add(new SnapshotCommitPoint(ic));
- }
- return wrappedCommits;
- }
-
- /**
- * Get a snapshotted IndexCommit by ID. The IndexCommit can then be used to
- * open an IndexReader on a specific commit point, or rollback the index by
- * opening an IndexWriter with the IndexCommit specified in its
- * {@link IndexWriterConfig}.
- *
- * @param id
- * a unique identifier of the commit that was snapshotted.
- * @throws IllegalStateException
- * if no snapshot exists by the specified ID.
- * @return The {@link IndexCommit} for this particular snapshot.
- */
- public synchronized IndexCommit getSnapshot(String id) {
- SnapshotInfo snapshotInfo = idToSnapshot.get(id);
- if (snapshotInfo == null) {
- throw new IllegalStateException("No snapshot exists by ID: " + id);
- }
- return snapshotInfo.commit;
- }
-
- /**
- * Get all the snapshots in a map of snapshot IDs to the segments they
- * 'cover.' This can be passed to
- * {@link #SnapshotDeletionPolicy(IndexDeletionPolicy, Map)} in order to
- * initialize snapshots at construction.
- */
- public synchronized Map<String, String> getSnapshots() {
- Map<String, String> snapshots = new HashMap<String, String>();
- for (Entry<String, SnapshotInfo> e : idToSnapshot.entrySet()) {
- snapshots.put(e.getKey(), e.getValue().segmentsFileName);
- }
- return snapshots;
- }
-
- /**
- * Returns true if the given ID is already used by a snapshot. You can call
- * this method before {@link #snapshot(String)} if you are not sure whether
- * the ID is already used or not.
- */
- public boolean isSnapshotted(String id) {
- return idToSnapshot.containsKey(id);
- }
-
- @Override
- public synchronized void onCommit(List<? extends IndexCommit> commits)
- throws IOException {
- primary.onCommit(wrapCommits(commits));
- lastCommit = commits.get(commits.size() - 1);
- }
-
- @Override
- public synchronized void onInit(List<? extends IndexCommit> commits)
- throws IOException {
- primary.onInit(wrapCommits(commits));
- lastCommit = commits.get(commits.size() - 1);
-
- /*
- * Assign snapshotted IndexCommits to their correct snapshot IDs as
- * specified in the constructor.
- */
- for (IndexCommit commit : commits) {
- Set<String> ids = segmentsFileToIDs.get(commit.getSegmentsFileName());
- if (ids != null) {
- for (String id : ids) {
- idToSnapshot.get(id).commit = commit;
- }
- }
- }
-
- /*
- * Second, see if there are any instances where a snapshot ID was specified
- * in the constructor but an IndexCommit doesn't exist. In this case, the ID
- * should be removed.
- *
- * Note: This code is protective for extreme cases where IDs point to
- * non-existent segments. As the constructor should have received its
- * information via a call to getSnapshots(), the data should be well-formed.
- */
- // Find lost snapshots
- ArrayList<String> idsToRemove = null;
- for (Entry<String, SnapshotInfo> e : idToSnapshot.entrySet()) {
- if (e.getValue().commit == null) {
- if (idsToRemove == null) {
- idsToRemove = new ArrayList<String>();
- }
- idsToRemove.add(e.getKey());
- }
- }
- // Finally, remove those 'lost' snapshots.
- if (idsToRemove != null) {
- for (String id : idsToRemove) {
- SnapshotInfo info = idToSnapshot.remove(id);
- segmentsFileToIDs.remove(info.segmentsFileName);
- }
- }
- }
-
- /**
- * Release a snapshotted commit by ID.
- *
- * @param id
- * a unique identifier of the commit that is un-snapshotted.
- * @throws IllegalStateException
- * if no snapshot exists by this ID.
- */
- public synchronized void release(String id) throws IOException {
- SnapshotInfo info = idToSnapshot.remove(id);
- if (info == null) {
- throw new IllegalStateException("Snapshot doesn't exist: " + id);
- }
- Set<String> ids = segmentsFileToIDs.get(info.segmentsFileName);
- if (ids != null) {
- ids.remove(id);
- if (ids.size() == 0) {
- segmentsFileToIDs.remove(info.segmentsFileName);
- }
- }
- }
-
- /**
- * Snapshots the last commit. Once a commit is 'snapshotted,' it is protected
- * from deletion (as long as this {@link IndexDeletionPolicy} is used). The
- * commit can be removed by calling {@link #release(String)} using the same ID
- * parameter followed by a call to {@link IndexWriter#deleteUnusedFiles()}.
- * <p>
- * <b>NOTE:</b> ID must be unique in the system. If the same ID is used twice,
- * an {@link IllegalStateException} is thrown.
- * <p>
- * <b>NOTE:</b> while the snapshot is held, the files it references will not
- * be deleted, which will consume additional disk space in your index. If you
- * take a snapshot at a particularly bad time (say just before you call
- * forceMerge) then in the worst case this could consume an extra 1X of your
- * total index size, until you release the snapshot.
- *
- * @param id
- * a unique identifier of the commit that is being snapshotted.
- * @throws IllegalStateException
- * if either there is no 'last commit' to snapshot, or if the
- * parameter 'ID' refers to an already snapshotted commit.
- * @return the {@link IndexCommit} that was snapshotted.
- */
- public synchronized IndexCommit snapshot(String id) throws IOException {
- if (lastCommit == null) {
- // no commit exists. Really shouldn't happen, but might be if SDP is
- // accessed before onInit or onCommit were called.
- throw new IllegalStateException("No index commit to snapshot");
- }
-
- // Can't use the same snapshot ID twice...
- checkSnapshotted(id);
-
- registerSnapshotInfo(id, lastCommit.getSegmentsFileName(), lastCommit);
- return lastCommit;
- }
-
}
Modified: lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/SortedDocValues.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/SortedDocValues.java?rev=1487777&r1=1487776&r2=1487777&view=diff
==============================================================================
--- lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/SortedDocValues.java (original)
+++ lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/SortedDocValues.java Thu May 30 07:53:18 2013
@@ -114,4 +114,12 @@ public abstract class SortedDocValues ex
return -(low + 1); // key not found.
}
+
+ /**
+ * Returns a {@link TermsEnum} over the values.
+ * The enum supports {@link TermsEnum#ord()} and {@link TermsEnum#seekExact(long)}.
+ */
+ public TermsEnum termsEnum() {
+ return new SortedDocValuesTermsEnum(this);
+ }
}
Modified: lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/SortedDocValuesTermsEnum.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/SortedDocValuesTermsEnum.java?rev=1487777&r1=1487776&r2=1487777&view=diff
==============================================================================
--- lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/SortedDocValuesTermsEnum.java (original)
+++ lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/SortedDocValuesTermsEnum.java Thu May 30 07:53:18 2013
@@ -26,7 +26,7 @@ import org.apache.lucene.util.BytesRef;
/** Implements a {@link TermsEnum} wrapping a provided
* {@link SortedDocValues}. */
-public class SortedDocValuesTermsEnum extends TermsEnum {
+class SortedDocValuesTermsEnum extends TermsEnum {
private final SortedDocValues values;
private int currentOrd = -1;
private final BytesRef term = new BytesRef();
@@ -64,6 +64,12 @@ public class SortedDocValuesTermsEnum ex
public boolean seekExact(BytesRef text, boolean useCache) throws IOException {
int ord = values.lookupTerm(text);
if (ord >= 0) {
+ term.offset = 0;
+ // TODO: is there a cleaner way?
+ // term.bytes may be pointing to codec-private byte[]
+ // storage, so we must force new byte[] allocation:
+ term.bytes = new byte[text.length];
+ term.copyBytes(text);
currentOrd = ord;
return true;
} else {
Modified: lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/SortedSetDocValues.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/SortedSetDocValues.java?rev=1487777&r1=1487776&r2=1487777&view=diff
==============================================================================
--- lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/SortedSetDocValues.java (original)
+++ lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/SortedSetDocValues.java Thu May 30 07:53:18 2013
@@ -117,4 +117,12 @@ public abstract class SortedSetDocValues
return -(low + 1); // key not found.
}
+
+ /**
+ * Returns a {@link TermsEnum} over the values.
+ * The enum supports {@link TermsEnum#ord()} and {@link TermsEnum#seekExact(long)}.
+ */
+ public TermsEnum termsEnum() {
+ return new SortedSetDocValuesTermsEnum(this);
+ }
}
Modified: lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/SortedSetDocValuesTermsEnum.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/SortedSetDocValuesTermsEnum.java?rev=1487777&r1=1487776&r2=1487777&view=diff
==============================================================================
--- lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/SortedSetDocValuesTermsEnum.java (original)
+++ lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/SortedSetDocValuesTermsEnum.java Thu May 30 07:53:18 2013
@@ -26,7 +26,7 @@ import org.apache.lucene.util.BytesRef;
/** Implements a {@link TermsEnum} wrapping a provided
* {@link SortedSetDocValues}. */
-public class SortedSetDocValuesTermsEnum extends TermsEnum {
+class SortedSetDocValuesTermsEnum extends TermsEnum {
private final SortedSetDocValues values;
private long currentOrd = -1;
private final BytesRef term = new BytesRef();
@@ -64,6 +64,12 @@ public class SortedSetDocValuesTermsEnum
public boolean seekExact(BytesRef text, boolean useCache) throws IOException {
long ord = values.lookupTerm(text);
if (ord >= 0) {
+ term.offset = 0;
+ // TODO: is there a cleaner way?
+ // term.bytes may be pointing to codec-private byte[]
+ // storage, so we must force new byte[] allocation:
+ term.bytes = new byte[text.length];
+ term.copyBytes(text);
currentOrd = ord;
return true;
} else {
Modified: lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/StandardDirectoryReader.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/StandardDirectoryReader.java?rev=1487777&r1=1487776&r2=1487777&view=diff
==============================================================================
--- lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/StandardDirectoryReader.java (original)
+++ lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/StandardDirectoryReader.java Thu May 30 07:53:18 2013
@@ -89,6 +89,10 @@ final class StandardDirectoryReader exte
IOException prior = null;
boolean success = false;
try {
+ // NOTE: important that we use infos not
+ // segmentInfos here, so that we are passing the
+ // actual instance of SegmentInfoPerCommit in
+ // IndexWriter's segmentInfos:
final SegmentInfoPerCommit info = infos.info(i);
assert info.info.dir == dir;
final ReadersAndLiveDocs rld = writer.readerPool.get(info, true);
@@ -118,9 +122,10 @@ final class StandardDirectoryReader exte
writer, segmentInfos, writer.getConfig().getReaderTermsIndexDivisor(), applyAllDeletes);
}
- /** This constructor is only used for {@link #doOpenIfChanged(SegmentInfos, IndexWriter)} */
- private static DirectoryReader open(Directory directory, IndexWriter writer, SegmentInfos infos, List<? extends AtomicReader> oldReaders,
+ /** This constructor is only used for {@link #doOpenIfChanged(SegmentInfos)} */
+ private static DirectoryReader open(Directory directory, SegmentInfos infos, List<? extends AtomicReader> oldReaders,
int termInfosIndexDivisor) throws IOException {
+
// we put the old SegmentReaders in a map, that allows us
// to lookup a reader using its segment name
final Map<String,Integer> segmentReaders = new HashMap<String,Integer>();
@@ -207,7 +212,7 @@ final class StandardDirectoryReader exte
}
}
}
- return new StandardDirectoryReader(directory, newReaders, writer, infos, termInfosIndexDivisor, false);
+ return new StandardDirectoryReader(directory, newReaders, null, infos, termInfosIndexDivisor, false);
}
@Override
@@ -232,7 +237,7 @@ final class StandardDirectoryReader exte
@Override
protected DirectoryReader doOpenIfChanged() throws IOException {
- return doOpenIfChanged(null);
+ return doOpenIfChanged((IndexCommit) null);
}
@Override
@@ -260,7 +265,7 @@ final class StandardDirectoryReader exte
private DirectoryReader doOpenFromWriter(IndexCommit commit) throws IOException {
if (commit != null) {
- throw new IllegalArgumentException("a reader obtained from IndexWriter.getReader() cannot currently accept a commit");
+ return doOpenFromCommit(commit);
}
if (writer.nrtIsCurrent(segmentInfos)) {
@@ -293,18 +298,22 @@ final class StandardDirectoryReader exte
}
}
+ return doOpenFromCommit(commit);
+ }
+
+ private DirectoryReader doOpenFromCommit(IndexCommit commit) throws IOException {
return (DirectoryReader) new SegmentInfos.FindSegmentsFile(directory) {
@Override
protected Object doBody(String segmentFileName) throws IOException {
final SegmentInfos infos = new SegmentInfos();
infos.read(directory, segmentFileName);
- return doOpenIfChanged(infos, null);
+ return doOpenIfChanged(infos);
}
}.run(commit);
}
- DirectoryReader doOpenIfChanged(SegmentInfos infos, IndexWriter writer) throws IOException {
- return StandardDirectoryReader.open(directory, writer, infos, getSequentialSubReaders(), termInfosIndexDivisor);
+ DirectoryReader doOpenIfChanged(SegmentInfos infos) throws IOException {
+ return StandardDirectoryReader.open(directory, infos, getSequentialSubReaders(), termInfosIndexDivisor);
}
@Override
Modified: lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/StoredFieldVisitor.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/StoredFieldVisitor.java?rev=1487777&r1=1487776&r2=1487777&view=diff
==============================================================================
--- lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/StoredFieldVisitor.java (original)
+++ lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/StoredFieldVisitor.java Thu May 30 07:53:18 2013
@@ -27,7 +27,13 @@ import org.apache.lucene.document.Docume
* values in an index. See {@link IndexReader#document(int,
* StoredFieldVisitor)}.
*
- * See {@link DocumentStoredFieldVisitor}, which is a
+ * <p><b>NOTE</b>: a {@code StoredFieldVisitor} implementation
+ * should not try to load or visit other stored documents in
+ * the same reader because the implementation of stored
+ * fields for most codecs is not reeentrant and you will see
+ * strange exceptions as a result.
+ *
+ * <p>See {@link DocumentStoredFieldVisitor}, which is a
* <code>StoredFieldVisitor</code> that builds the
* {@link Document} containing all stored fields. This is
* used by {@link IndexReader#document(int)}.
Modified: lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/Term.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/Term.java?rev=1487777&r1=1487776&r2=1487777&view=diff
==============================================================================
--- lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/Term.java (original)
+++ lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/Term.java Thu May 30 07:53:18 2013
@@ -17,7 +17,13 @@ package org.apache.lucene.index;
* limitations under the License.
*/
+import java.nio.ByteBuffer;
+import java.nio.charset.CharacterCodingException;
+import java.nio.charset.CharsetDecoder;
+import java.nio.charset.CodingErrorAction;
+
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.IOUtils;
/**
A Term represents a word from text. This is the unit of search. It is
@@ -69,7 +75,23 @@ public final class Term implements Compa
/** Returns the text of this term. In the case of words, this is simply the
text of the word. In the case of dates and other types, this is an
encoding of the object as a string. */
- public final String text() { return bytes.utf8ToString(); }
+ public final String text() {
+ return toString(bytes);
+ }
+
+ /** Returns human-readable form of the term text. If the term is not unicode,
+ * the raw bytes will be printed instead. */
+ public static final String toString(BytesRef termText) {
+ // the term might not be text, but usually is. so we make a best effort
+ CharsetDecoder decoder = IOUtils.CHARSET_UTF_8.newDecoder()
+ .onMalformedInput(CodingErrorAction.REPORT)
+ .onUnmappableCharacter(CodingErrorAction.REPORT);
+ try {
+ return decoder.decode(ByteBuffer.wrap(termText.bytes, termText.offset, termText.length)).toString();
+ } catch (CharacterCodingException e) {
+ return termText.toString();
+ }
+ }
/** Returns the bytes of this term. */
public final BytesRef bytes() { return bytes; }
@@ -132,5 +154,5 @@ public final class Term implements Compa
}
@Override
- public final String toString() { return field + ":" + bytes.utf8ToString(); }
+ public final String toString() { return field + ":" + text(); }
}
Modified: lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/TermsEnum.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/TermsEnum.java?rev=1487777&r1=1487776&r2=1487777&view=diff
==============================================================================
--- lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/TermsEnum.java (original)
+++ lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/index/TermsEnum.java Thu May 30 07:53:18 2013
@@ -213,6 +213,7 @@ public abstract class TermsEnum implemen
return new TermState() {
@Override
public void copyFrom(TermState other) {
+ throw new UnsupportedOperationException();
}
};
}
Modified: lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/search/BooleanQuery.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/search/BooleanQuery.java?rev=1487777&r1=1487776&r2=1487777&view=diff
==============================================================================
--- lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/search/BooleanQuery.java (original)
+++ lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/search/BooleanQuery.java Thu May 30 07:53:18 2013
@@ -18,18 +18,16 @@ package org.apache.lucene.search;
*/
import java.io.IOException;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
import org.apache.lucene.index.AtomicReaderContext;
-import org.apache.lucene.index.DocsEnum;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
-import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.search.BooleanClause.Occur;
-import org.apache.lucene.search.ConjunctionTermScorer.DocsAndFreqs;
-import org.apache.lucene.search.TermQuery.TermWeight;
import org.apache.lucene.search.similarities.Similarity;
-import org.apache.lucene.search.similarities.Similarity.ExactSimScorer;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.ToStringUtils;
@@ -174,24 +172,18 @@ public class BooleanQuery extends Query
protected ArrayList<Weight> weights;
protected int maxCoord; // num optional + num required
private final boolean disableCoord;
- private final boolean termConjunction;
public BooleanWeight(IndexSearcher searcher, boolean disableCoord)
throws IOException {
this.similarity = searcher.getSimilarity();
this.disableCoord = disableCoord;
weights = new ArrayList<Weight>(clauses.size());
- boolean termConjunction = clauses.isEmpty() || minNrShouldMatch != 0 ? false : true;
for (int i = 0 ; i < clauses.size(); i++) {
BooleanClause c = clauses.get(i);
Weight w = c.getQuery().createWeight(searcher);
- if (!(c.isRequired() && (w instanceof TermWeight))) {
- termConjunction = false;
- }
weights.add(w);
if (!c.isProhibited()) maxCoord++;
}
- this.termConjunction = termConjunction;
}
@Override
@@ -310,10 +302,6 @@ public class BooleanQuery extends Query
public Scorer scorer(AtomicReaderContext context, boolean scoreDocsInOrder,
boolean topScorer, Bits acceptDocs)
throws IOException {
- if (termConjunction) {
- // specialized scorer for term conjunctions
- return createConjunctionTermScorer(context, acceptDocs);
- }
List<Scorer> required = new ArrayList<Scorer>();
List<Scorer> prohibited = new ArrayList<Scorer>();
List<Scorer> optional = new ArrayList<Scorer>();
@@ -341,8 +329,10 @@ public class BooleanQuery extends Query
// detect and we never do so today... (ie, we only
// return BooleanScorer for topScorer):
- // Check if we can return a BooleanScorer
- if (!scoreDocsInOrder && topScorer && required.size() == 0) {
+ // Check if we can and should return a BooleanScorer
+ // TODO: (LUCENE-4872) in some cases BooleanScorer may be faster for minNrShouldMatch
+ // but the same is even true of pure conjunctions...
+ if (!scoreDocsInOrder && topScorer && required.size() == 0 && minNrShouldMatch <= 1) {
return new BooleanScorer(this, disableCoord, minNrShouldMatch, optional, prohibited, maxCoord);
}
@@ -356,30 +346,23 @@ public class BooleanQuery extends Query
return null;
}
- // Return a BooleanScorer2
- return new BooleanScorer2(this, disableCoord, minNrShouldMatch, required, prohibited, optional, maxCoord);
- }
-
- private Scorer createConjunctionTermScorer(AtomicReaderContext context, Bits acceptDocs)
- throws IOException {
-
- // TODO: fix scorer API to specify "needsScores" up
- // front, so we can do match-only if caller doesn't
- // needs scores
-
- final DocsAndFreqs[] docsAndFreqs = new DocsAndFreqs[weights.size()];
- for (int i = 0; i < docsAndFreqs.length; i++) {
- final TermWeight weight = (TermWeight) weights.get(i);
- final Scorer scorer = weight.scorer(context, true, false, acceptDocs);
- if (scorer == null) {
- return null;
- } else {
- assert scorer instanceof TermScorer;
- docsAndFreqs[i] = new DocsAndFreqs((TermScorer) scorer);
+ // simple conjunction
+ if (optional.size() == 0 && prohibited.size() == 0) {
+ float coord = disableCoord ? 1.0f : coord(required.size(), maxCoord);
+ return new ConjunctionScorer(this, required.toArray(new Scorer[required.size()]), coord);
+ }
+
+ // simple disjunction
+ if (required.size() == 0 && prohibited.size() == 0 && minNrShouldMatch <= 1 && optional.size() > 1) {
+ float coord[] = new float[optional.size()+1];
+ for (int i = 0; i < coord.length; i++) {
+ coord[i] = disableCoord ? 1.0f : coord(i, maxCoord);
}
+ return new DisjunctionSumScorer(this, optional.toArray(new Scorer[optional.size()]), coord);
}
- return new ConjunctionTermScorer(this, disableCoord ? 1.0f : coord(
- docsAndFreqs.length, docsAndFreqs.length), docsAndFreqs);
+
+ // Return a BooleanScorer2
+ return new BooleanScorer2(this, disableCoord, minNrShouldMatch, required, prohibited, optional, maxCoord);
}
@Override
@@ -446,9 +429,11 @@ public class BooleanQuery extends Query
// inherit javadoc
@Override
public void extractTerms(Set<Term> terms) {
- for (BooleanClause clause : clauses) {
- clause.getQuery().extractTerms(terms);
- }
+ for (BooleanClause clause : clauses) {
+ if (clause.getOccur() != Occur.MUST_NOT) {
+ clause.getQuery().extractTerms(terms);
+ }
+ }
}
@Override @SuppressWarnings("unchecked")
Modified: lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/search/BooleanScorer.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/search/BooleanScorer.java?rev=1487777&r1=1487776&r2=1487777&view=diff
==============================================================================
--- lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/search/BooleanScorer.java (original)
+++ lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/search/BooleanScorer.java Thu May 30 07:53:18 2013
@@ -135,6 +135,9 @@ final class BooleanScorer extends Scorer
@Override
public float score() { return (float)score; }
+ @Override
+ public long cost() { return 1; }
+
}
static final class Bucket {
@@ -327,6 +330,11 @@ final class BooleanScorer extends Scorer
}
@Override
+ public long cost() {
+ return Integer.MAX_VALUE;
+ }
+
+ @Override
public void score(Collector collector) throws IOException {
score(collector, Integer.MAX_VALUE, -1);
}
Modified: lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/search/BooleanScorer2.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/search/BooleanScorer2.java?rev=1487777&r1=1487776&r2=1487777&view=diff
==============================================================================
--- lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/search/BooleanScorer2.java (original)
+++ lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/search/BooleanScorer2.java Thu May 30 07:53:18 2013
@@ -147,35 +147,41 @@ class BooleanScorer2 extends Scorer {
public int advance(int target) throws IOException {
return scorer.advance(target);
}
+
+ @Override
+ public long cost() {
+ return scorer.cost();
+ }
}
private Scorer countingDisjunctionSumScorer(final List<Scorer> scorers,
int minNrShouldMatch) throws IOException {
// each scorer from the list counted as a single matcher
- return new DisjunctionSumScorer(weight, scorers, minNrShouldMatch) {
- private int lastScoredDoc = -1;
- // Save the score of lastScoredDoc, so that we don't compute it more than
- // once in score().
- private float lastDocScore = Float.NaN;
- @Override public float score() throws IOException {
- int doc = docID();
- if (doc >= lastScoredDoc) {
- if (doc > lastScoredDoc) {
- lastDocScore = super.score();
- lastScoredDoc = doc;
- }
+ if (minNrShouldMatch > 1) {
+ return new MinShouldMatchSumScorer(weight, scorers, minNrShouldMatch) {
+ @Override
+ public float score() throws IOException {
coordinator.nrMatchers += super.nrMatchers;
+ return super.score();
}
- return lastDocScore;
- }
- };
+ };
+ } else {
+ // we pass null for coord[] since we coordinate ourselves and override score()
+ return new DisjunctionSumScorer(weight, scorers.toArray(new Scorer[scorers.size()]), null) {
+ @Override
+ public float score() throws IOException {
+ coordinator.nrMatchers += super.nrMatchers;
+ return (float) super.score;
+ }
+ };
+ }
}
private Scorer countingConjunctionSumScorer(boolean disableCoord,
List<Scorer> requiredScorers) throws IOException {
// each scorer from the list counted as a single matcher
final int requiredNrMatchers = requiredScorers.size();
- return new ConjunctionScorer(weight, requiredScorers) {
+ return new ConjunctionScorer(weight, requiredScorers.toArray(new Scorer[requiredScorers.size()])) {
private int lastScoredDoc = -1;
// Save the score of lastScoredDoc, so that we don't compute it more than
// once in score().
@@ -200,7 +206,7 @@ class BooleanScorer2 extends Scorer {
private Scorer dualConjunctionSumScorer(boolean disableCoord,
Scorer req1, Scorer req2) throws IOException { // non counting.
- return new ConjunctionScorer(weight, req1, req2);
+ return new ConjunctionScorer(weight, new Scorer[] { req1, req2 });
// All scorers match, so defaultSimilarity always has 1 as
// the coordination factor.
// Therefore the sum of the scores of two scorers
@@ -270,7 +276,7 @@ class BooleanScorer2 extends Scorer {
: new ReqExclScorer(requiredCountingSumScorer,
((prohibitedScorers.size() == 1)
? prohibitedScorers.get(0)
- : new DisjunctionSumScorer(weight, prohibitedScorers)));
+ : new MinShouldMatchSumScorer(weight, prohibitedScorers)));
}
/** Scores and collects all matching documents.
@@ -321,6 +327,11 @@ class BooleanScorer2 extends Scorer {
public int advance(int target) throws IOException {
return doc = countingSumScorer.advance(target);
}
+
+ @Override
+ public long cost() {
+ return countingSumScorer.cost();
+ }
@Override
public Collection<ChildScorer> getChildren() {
Modified: lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/search/CachingCollector.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/search/CachingCollector.java?rev=1487777&r1=1487776&r2=1487777&view=diff
==============================================================================
--- lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/search/CachingCollector.java (original)
+++ lucene/dev/branches/security/lucene/core/src/java/org/apache/lucene/search/CachingCollector.java Thu May 30 07:53:18 2013
@@ -89,6 +89,9 @@ public abstract class CachingCollector e
@Override
public final int nextDoc() { throw new UnsupportedOperationException(); }
+
+ @Override
+ public long cost() { return 1; }
}
// A CachingCollector which caches scores