Skip to content

Apache Lucene open-source search software

merged with trunk and integrated doc values with codec per field support

Simon Willnauerd225b6467dae
diff --cc lucene/src/java/org/apache/lucene/index/DirectoryReader.java
index 9863fb961d6,64f77e0503c..31a4f72b9bf
--- a/lucene/src/java/org/apache/lucene/index/DirectoryReader.java
+++ b/lucene/src/java/org/apache/lucene/index/DirectoryReader.java
@@@ -988,9 -985,12 +985,12 @@@ class DirectoryReader extends IndexRead
}
}
+ // Ensure that the commit points are sorted in ascending order.
+ Collections.sort(commits);
+
return commits;
- }
-
+ }
+
private static final class ReaderCommit extends IndexCommit {
private String segmentsFileName;
Collection<String> files;
diff --cc lucene/src/java/org/apache/lucene/index/DocFieldProcessor.java
index d1b46e1b9c9,980479b961c..097113a1532
--- a/lucene/src/java/org/apache/lucene/index/DocFieldProcessor.java
+++ b/lucene/src/java/org/apache/lucene/index/DocFieldProcessor.java
@@@ -38,37 -34,12 +38,38 @@@ import org.apache.lucene.store.Director
final class DocFieldProcessor extends DocConsumer {
final DocumentsWriter docWriter;
- final FieldInfos fieldInfos = new FieldInfos();
+ final FieldInfos fieldInfos;
final DocFieldConsumer consumer;
final StoredFieldsWriter fieldsWriter;
+ final private Map<String,DocValuesConsumer> docValues = new HashMap<String,DocValuesConsumer>();
+ private FieldsConsumer fieldsConsumer; // TODO this should be encapsulated in DocumentsWriter
+
+ synchronized DocValuesConsumer docValuesConsumer(Directory dir,
+ String segment, String name, ValuesAttribute attr, FieldInfo fieldInfo)
+ throws IOException {
+ DocValuesConsumer valuesConsumer;
+ if ((valuesConsumer = docValues.get(name)) == null) {
+ fieldInfo.setDocValues(attr.type());
+
+ if(fieldsConsumer == null) {
+ /* nocommit -- this is a hack and only works since DocValuesCodec supports initializing the FieldsConsumer twice.
+ * we need to find a way that allows us to obtain a FieldsConsumer per DocumentsWriter. Currently some codecs rely on
+ * the SegmentsWriteState passed in right at the moment when the segment is flushed (doccount etc) but we need the consumer earlier
+ * to support docvalues and later on stored fields too.
+ */
+ SegmentWriteState state = docWriter.segWriteState();
- fieldsConsumer = state.codec.fieldsConsumer(state);
++ fieldsConsumer = state.segmentCodecs.codec().fieldsConsumer(state);
+ }
+ valuesConsumer = fieldsConsumer.addValuesField(fieldInfo);
+ docValues.put(name, valuesConsumer);
+ }
+ return valuesConsumer;
+ }
+
+
public DocFieldProcessor(DocumentsWriter docWriter, DocFieldConsumer consumer) {
+ this.fieldInfos = new FieldInfos();
this.docWriter = docWriter;
this.consumer = consumer;
consumer.setFieldInfos(fieldInfos);
diff --cc lucene/src/java/org/apache/lucene/index/DocumentsWriter.java
index acc20d4b842,31fdaa802d1..4738ecc5e67
--- a/lucene/src/java/org/apache/lucene/index/DocumentsWriter.java
+++ b/lucene/src/java/org/apache/lucene/index/DocumentsWriter.java
@@@ -603,19 -601,15 +601,22 @@@ final class DocumentsWriter
}
synchronized private void initFlushState(boolean onlyDocStore) {
-- initSegmentName(onlyDocStore);
- flushState = segWriteState();
++ initSegmentName(onlyDocStore); // nocommit - this does not work for docValues
+ final SegmentCodecs info = SegmentCodecs.build(docFieldProcessor.fieldInfos, writer.codecs);
+ flushState = new SegmentWriteState(infoStream, directory, segment, docFieldProcessor.fieldInfos,
+ docStoreSegment, numDocsInRAM, numDocsInStore, writer.getConfig().getTermIndexInterval(), info);
}
+
+ SegmentWriteState segWriteState() {
++ final SegmentCodecs info = SegmentCodecs.build(docFieldProcessor.fieldInfos, writer.codecs);
+ return new SegmentWriteState(infoStream, directory, segment, docFieldProcessor.fieldInfos,
+ docStoreSegment, numDocsInRAM, numDocsInStore, writer.getConfig().getTermIndexInterval(),
- writer.codecs);
++ info);
+ }
- /** Returns the codec used to flush the last segment */
- Codec getCodec() {
- return flushState.codec;
+ /** Returns the SegmentCodecs used to flush the last segment */
+ SegmentCodecs getSegmentCodecs() {
+ return flushState.segmentCodecs;
}
/** Flush all pending docs to a new segment */
diff --cc lucene/src/java/org/apache/lucene/index/FieldInfos.java
index aa11aa77fbd,07111ef29a7..0c8aef3b11e
--- a/lucene/src/java/org/apache/lucene/index/FieldInfos.java
+++ b/lucene/src/java/org/apache/lucene/index/FieldInfos.java
@@@ -39,12 -38,10 +39,13 @@@ public final class FieldInfos
// First used in 2.9; prior to 2.9 there was no format header
public static final int FORMAT_START = -2;
+ public static final int FORMAT_PER_FIELD_CODEC = -3;
+ // Records index values for this field
+ public static final int FORMAT_INDEX_VALUES = -3;
+
// whenever you add a new format, make it 1 smaller (negative version logic)!
- static final int FORMAT_CURRENT = FORMAT_INDEX_VALUES;
+ static final int FORMAT_CURRENT = FORMAT_PER_FIELD_CODEC;
static final int FORMAT_MINIMUM = FORMAT_START;
@@@ -305,51 -303,9 +307,51 @@@
if (fi.omitNorms) bits |= OMIT_NORMS;
if (fi.storePayloads) bits |= STORE_PAYLOADS;
if (fi.omitTermFreqAndPositions) bits |= OMIT_TERM_FREQ_AND_POSITIONS;
-
output.writeString(fi.name);
+ output.writeInt(fi.codecId);
output.writeByte(bits);
+
+ final byte b;
+
+ if (fi.docValues == null) {
+ b = 0;
+ } else {
+ switch(fi.docValues) {
+ case PACKED_INTS:
+ b = 1;
+ break;
+ case SIMPLE_FLOAT_4BYTE:
+ b = 2;
+ break;
+ case SIMPLE_FLOAT_8BYTE:
+ b = 3;
+ break;
+ case BYTES_FIXED_STRAIGHT:
+ b = 4;
+ break;
+ case BYTES_FIXED_DEREF:
+ b = 5;
+ break;
+ case BYTES_FIXED_SORTED:
+ b = 6;
+ break;
+ case BYTES_VAR_STRAIGHT:
+ b = 7;
+ break;
+ case BYTES_VAR_DEREF:
+ b = 8;
+ break;
+ case BYTES_VAR_SORTED:
+ b = 9;
+ break;
+ case PACKED_INTS_FIXED:
+ b = 10;
+ break;
+ default:
+ throw new IllegalStateException("unhandled indexValues type " + fi.docValues);
+ }
+ }
+ output.writeByte(b);
}
}
@@@ -375,48 -333,8 +379,48 @@@
boolean omitNorms = (bits & OMIT_NORMS) != 0;
boolean storePayloads = (bits & STORE_PAYLOADS) != 0;
boolean omitTermFreqAndPositions = (bits & OMIT_TERM_FREQ_AND_POSITIONS) != 0;
-
- FieldInfo fi = addInternal(name, isIndexed, storeTermVector, storePositionsWithTermVector, storeOffsetWithTermVector, omitNorms, storePayloads, omitTermFreqAndPositions);
- final FieldInfo addInternal = addInternal(name, isIndexed, storeTermVector, storePositionsWithTermVector, storeOffsetWithTermVector, omitNorms, storePayloads, omitTermFreqAndPositions);
- addInternal.codecId = codecId;
++ final FieldInfo fi = addInternal(name, isIndexed, storeTermVector, storePositionsWithTermVector, storeOffsetWithTermVector, omitNorms, storePayloads, omitTermFreqAndPositions);
+ if (format <= FORMAT_INDEX_VALUES) {
+ final byte b = input.readByte();
+ switch(b) {
+ case 0:
+ fi.docValues = null;
+ break;
+ case 1:
+ fi.docValues = Values.PACKED_INTS;
+ break;
+ case 2:
+ fi.docValues = Values.SIMPLE_FLOAT_4BYTE;
+ break;
+ case 3:
+ fi.docValues = Values.SIMPLE_FLOAT_8BYTE;
+ break;
+ case 4:
+ fi.docValues = Values.BYTES_FIXED_STRAIGHT;
+ break;
+ case 5:
+ fi.docValues = Values.BYTES_FIXED_DEREF;
+ break;
+ case 6:
+ fi.docValues = Values.BYTES_FIXED_SORTED;
+ break;
+ case 7:
+ fi.docValues = Values.BYTES_VAR_STRAIGHT;
+ break;
+ case 8:
+ fi.docValues = Values.BYTES_VAR_DEREF;
+ break;
+ case 9:
+ fi.docValues = Values.BYTES_VAR_SORTED;
+ break;
+ case 10:
+ fi.docValues = Values.PACKED_INTS_FIXED;
+ break;
+ default:
+ throw new IllegalStateException("unhandled indexValues type " + b);
+ }
+ }
++ fi.codecId = codecId;
}
if (input.getFilePointer() != input.length()) {
diff --cc lucene/src/java/org/apache/lucene/index/IndexReader.java
index 060346373ff,73266e8831d..2130c221959
--- a/lucene/src/java/org/apache/lucene/index/IndexReader.java
+++ b/lucene/src/java/org/apache/lucene/index/IndexReader.java
@@@ -20,8 -20,8 +20,9 @@@ package org.apache.lucene.index
import org.apache.lucene.document.Document;
import org.apache.lucene.document.FieldSelector;
import org.apache.lucene.search.Similarity;
+ import org.apache.lucene.index.codecs.Codec;
import org.apache.lucene.index.codecs.CodecProvider;
+import org.apache.lucene.index.values.DocValues;
import org.apache.lucene.store.*;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.Bits;
diff --cc lucene/src/java/org/apache/lucene/index/PerFieldCodecWrapper.java
index b00d4dbc774,b052b26cbdc..5ec6a1e1b59
--- a/lucene/src/java/org/apache/lucene/index/PerFieldCodecWrapper.java
+++ b/lucene/src/java/org/apache/lucene/index/PerFieldCodecWrapper.java
@@@ -17,58 -17,40 +17,42 @@@ package org.apache.lucene.index
* limitations under the License.
*/
- import java.util.Map;
+ import java.io.IOException;
+ import java.util.ArrayList;
import java.util.HashMap;
- import java.util.Set;
- import java.util.HashSet;
import java.util.Iterator;
- import java.util.IdentityHashMap;
+ import java.util.Map;
+ import java.util.Set;
import java.util.TreeSet;
- import java.io.IOException;
- import org.apache.lucene.index.FieldsEnum;
- import org.apache.lucene.index.TermsEnum;
- import org.apache.lucene.index.Terms;
- import org.apache.lucene.index.FieldInfo;
- import org.apache.lucene.index.FieldInfos;
- import org.apache.lucene.index.SegmentInfo;
- import org.apache.lucene.index.SegmentWriteState;
- import org.apache.lucene.index.SegmentReadState;
+ import org.apache.lucene.index.codecs.Codec;
+ import org.apache.lucene.index.codecs.FieldsConsumer;
+ import org.apache.lucene.index.codecs.FieldsProducer;
+ import org.apache.lucene.index.codecs.TermsConsumer;
+import org.apache.lucene.index.codecs.docvalues.DocValuesConsumer;
+import org.apache.lucene.index.values.DocValues;
import org.apache.lucene.store.Directory;
+ /**
+ * Enables native per field codec support. This class selects the codec used to
+ * write a field depending on the provided {@link SegmentCodecs}. For each field
+ * seen it resolves the codec based on the {@link FieldInfo#codecId} which is
+ * only valid during a segment merge. See {@link SegmentCodecs} javadoc for
+ * details.
+ *
+ * @lucene.internal
+ */
+ final class PerFieldCodecWrapper extends Codec {
+ private final SegmentCodecs segmentCodecs;
- /** Simple Codec that dispatches field-specific codecs.
- * You must ensure every field you index has a Codec, or
- * the defaultCodec is non null. Also, the separate
- * codecs cannot conflict on file names.
- *
- * @lucene.experimental */
- public class PerFieldCodecWrapper extends Codec {
- private final Map<String,Codec> fields = new IdentityHashMap<String,Codec>();
- private final Codec defaultCodec;
-
- public PerFieldCodecWrapper(Codec defaultCodec) {
+ PerFieldCodecWrapper(SegmentCodecs segmentCodecs) {
name = "PerField";
- this.defaultCodec = defaultCodec;
+ this.segmentCodecs = segmentCodecs;
}
- public void add(String field, Codec codec) {
- fields.put(field, codec);
- }
-
- public Codec getCodec(String field) {
- Codec codec = fields.get(field);
- if (codec != null) {
- return codec;
- } else {
- return defaultCodec;
- }
- }
-
@Override
- public FieldsConsumer fieldsConsumer(SegmentWriteState state) throws IOException {
+ public FieldsConsumer fieldsConsumer(SegmentWriteState state)
+ throws IOException {
return new FieldsWriter(state);
}
@@@ -94,11 -73,11 +75,17 @@@
return fields.addField(field);
}
++ @Override
++ public DocValuesConsumer addValuesField(FieldInfo field) throws IOException {
++ final FieldsConsumer fields = consumers.get(field.codecId);
++ return fields.addValuesField(field);
++ }
++
@Override
public void close() throws IOException {
- Iterator<FieldsConsumer> it = codecs.values().iterator();
+ Iterator<FieldsConsumer> it = consumers.iterator();
IOException err = null;
- while(it.hasNext()) {
+ while (it.hasNext()) {
try {
it.next().close();
} catch (IOException ioe) {
@@@ -130,24 -97,26 +105,27 @@@
private class FieldsReader extends FieldsProducer {
private final Set<String> fields = new TreeSet<String>();
- private final Map<Codec,FieldsProducer> codecs = new HashMap<Codec,FieldsProducer>();
+ private final Map<String, FieldsProducer> codecs = new HashMap<String, FieldsProducer>();
- public FieldsReader(Directory dir, FieldInfos fieldInfos,
- SegmentInfo si, int readBufferSize,
- int indexDivisor) throws IOException {
+ public FieldsReader(Directory dir, FieldInfos fieldInfos, SegmentInfo si,
+ int readBufferSize, int indexDivisor) throws IOException {
final int fieldCount = fieldInfos.size();
- for(int i=0;i<fieldCount;i++) {
+ final Map<Codec, FieldsProducer> producers = new HashMap<Codec, FieldsProducer>();
+ for (int i = 0; i < fieldCount; i++) {
FieldInfo fi = fieldInfos.fieldInfo(i);
- if (fi.isIndexed) {
- if (fi.isIndexed) { // TODO this does not work for non-indexed fields
++ if (fi.isIndexed || fi.hasDocValues()) { // TODO this does not work for non-indexed fields
fields.add(fi.name);
- Codec codec = getCodec(fi.name);
- if (!codecs.containsKey(codec)) {
- codecs.put(codec, codec.fieldsProducer(new SegmentReadState(dir, si, fieldInfos, readBufferSize, indexDivisor)));
+ Codec codec = segmentCodecs.codecs[fi.codecId];
+ if (!producers.containsKey(codec)) {
+ producers.put(codec, codec.fieldsProducer(new SegmentReadState(dir,
+ si, fieldInfos, readBufferSize, indexDivisor)));
}
+ codecs.put(fi.name, producers.get(codec));
}
}
}
++
private final class FieldsIterator extends FieldsEnum {
private final Iterator<String> it;
@@@ -174,16 -143,11 +152,16 @@@
if (terms != null) {
return terms.iterator();
} else {
- return null;
+ return TermsEnum.EMPTY;
}
}
+
+ @Override
+ public DocValues docValues() throws IOException {
- return codecs.get(getCodec(current)).docValues(current);
++ return codecs.get(current).docValues(current);
+ }
}
-
+
@Override
public FieldsEnum iterator() throws IOException {
return new FieldsIterator();
@@@ -191,12 -155,9 +169,15 @@@
@Override
public Terms terms(String field) throws IOException {
- Codec codec = getCodec(field);
-
- FieldsProducer fields = codecs.get(codec);
- assert fields != null;
- return fields.terms(field);
+ FieldsProducer fields = codecs.get(field);
+ return fields == null ? null : fields.terms(field);
+ }
++
++ @Override
++ public DocValues docValues(String field) throws IOException {
++ FieldsProducer fieldsProducer = codecs.get(field);
++ return fieldsProducer == null? null: fieldsProducer.docValues(field);
+ }
@Override
public void close() throws IOException {
diff --cc lucene/src/java/org/apache/lucene/index/SegmentCodecs.java
index 00000000000,8ad1efb9242..de55723e1d2
mode 000000,100644..100644
--- a/lucene/src/java/org/apache/lucene/index/SegmentCodecs.java
+++ b/lucene/src/java/org/apache/lucene/index/SegmentCodecs.java
@@@ -1,0 -1,137 +1,137 @@@
+ package org.apache.lucene.index;
+
+ /**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+ import java.io.IOException;
+ import java.util.ArrayList;
+ import java.util.HashSet;
+ import java.util.IdentityHashMap;
+ import java.util.Map;
+ import java.util.Set;
+
+ import org.apache.lucene.index.codecs.Codec;
+ import org.apache.lucene.index.codecs.CodecProvider;
+ import org.apache.lucene.store.Directory;
+ import org.apache.lucene.store.IndexInput;
+ import org.apache.lucene.store.IndexOutput;
+
+ /**
+ * SegmentCodecs maintains an ordered list of distinct codecs used within a
+ * segment. Within a segment on codec is used to write multiple fields while
+ * each field could be written by a different codec. To enable codecs per field
+ * within a single segment we need to record the distinct codecs and map them to
+ * each field present in the segment. SegmentCodecs is created together with
+ * {@link SegmentWriteState} for each flush and is maintained in the
+ * corresponding {@link SegmentInfo} until it is committed.
+ * <p>
+ * {@link SegmentCodecs#build(FieldInfos, CodecProvider)} should be used to
+ * create a {@link SegmentCodecs} instance during {@link IndexWriter} sessions
+ * which creates the ordering of distinct codecs and assigns the
+ * {@link FieldInfo#codecId} or in other words, the ord of the codec maintained
+ * inside {@link SegmentCodecs}, to the {@link FieldInfo}. This ord is valid
+ * only until the current segment is flushed and {@link FieldInfos} for that
+ * segment are written including the ord for each field. This ord is later used
+ * to get the right codec when the segment is opened in a reader. The
+ * {@link Codec} returned from {@link SegmentCodecs#codec()} in turn uses
+ * {@link SegmentCodecs} internal structure to select and initialize the right
+ * codec for a fields when it is written.
+ * <p>
+ * Once a flush succeeded the {@link SegmentCodecs} is maintained inside the
+ * {@link SegmentInfo} for the flushed segment it was created for.
+ * {@link SegmentInfo} writes the name of each codec in {@link SegmentCodecs}
+ * for each segment and maintains the order. Later if a segment is opened by a
+ * reader this mapping is deserialized and used to create the codec per field.
+ *
+ *
+ * @lucene.internal
+ */
+ final class SegmentCodecs implements Cloneable {
+ /**
+ * internal structure to map codecs to fields - don't modify this from outside
+ * of this class!
+ */
+ Codec[] codecs;
+ final CodecProvider provider;
+ private final Codec codec = new PerFieldCodecWrapper(this);
+
+ SegmentCodecs(CodecProvider provider, Codec... codecs) {
+ this.provider = provider;
+ this.codecs = codecs;
+ }
+
+ static SegmentCodecs build(FieldInfos infos, CodecProvider provider) {
+ final int size = infos.size();
+ final Map<Codec, Integer> codecRegistry = new IdentityHashMap<Codec, Integer>();
+ final ArrayList<Codec> codecs = new ArrayList<Codec>();
+
+ for (int i = 0; i < size; i++) {
+ final FieldInfo info = infos.fieldInfo(i);
- if (info.isIndexed) {
++ if (info.isIndexed || info.hasDocValues()) {
+ final Codec fieldCodec = provider.lookup(provider
+ .getFieldCodec(info.name));
+ Integer ord = codecRegistry.get(fieldCodec);
+ if (ord == null) {
+ ord = Integer.valueOf(codecs.size());
+ codecRegistry.put(fieldCodec, ord);
+ codecs.add(fieldCodec);
+ }
+ info.codecId = ord.intValue();
+ }
+ }
+ return new SegmentCodecs(provider, codecs.toArray(Codec.EMPTY));
+
+ }
+
+ Codec codec() {
+ return codec;
+ }
+
+ void write(IndexOutput out) throws IOException {
+ out.writeVInt(codecs.length);
+ for (Codec codec : codecs) {
+ out.writeString(codec.name);
+ }
+ }
+
+ void read(IndexInput in) throws IOException {
+ final int size = in.readVInt();
+ final ArrayList<Codec> list = new ArrayList<Codec>();
+ for (int i = 0; i < size; i++) {
+ final String codecName = in.readString();
+ final Codec lookup = provider.lookup(codecName);
+ list.add(i, lookup);
+ }
+ codecs = list.toArray(Codec.EMPTY);
+ }
+
+ void files(Directory dir, SegmentInfo info, Set<String> files)
+ throws IOException {
+ final Set<Codec> seen = new HashSet<Codec>();
+ final Codec[] codecArray = codecs;
+ for (Codec codec : codecArray) {
+ if (!seen.contains(codec)) {
+ seen.add(codec);
+ codec.files(dir, info, files);
+ }
+ }
+ }
+
+ @Override
+ public String toString() {
+ return "CodecInfo [codecs=" + codecs + ", provider=" + provider + "]";
+ }
+ }
diff --cc lucene/src/java/org/apache/lucene/index/SegmentMerger.java
index 64a7b479f41,6dcaa281f5d..05ded0aa5ba
--- a/lucene/src/java/org/apache/lucene/index/SegmentMerger.java
+++ b/lucene/src/java/org/apache/lucene/index/SegmentMerger.java
@@@ -183,12 -183,13 +183,12 @@@ final class SegmentMerger
!ext.equals(IndexFileNames.FIELDS_INDEX_EXTENSION)))
fileSet.add(IndexFileNames.segmentFileName(segment, "", ext));
}
- codec.files(directory, info, fileSet);
-
+ segmentWriteState.segmentCodecs.files(directory, info, fileSet);
// Fieldable norm files
- int numFIs = fieldInfos.size();
+ final int numFIs = fieldInfos.size();
for (int i = 0; i < numFIs; i++) {
- FieldInfo fi = fieldInfos.fieldInfo(i);
+ final FieldInfo fi = fieldInfos.fieldInfo(i);
if (fi.isIndexed && !fi.omitNorms) {
fileSet.add(IndexFileNames.segmentFileName(segment, "", IndexFileNames.NORMS_EXTENSION));
break;
@@@ -309,9 -302,9 +309,10 @@@
addIndexed(reader, fieldInfos, reader.getFieldNames(FieldOption.STORES_PAYLOADS), false, false, false, true, false);
addIndexed(reader, fieldInfos, reader.getFieldNames(FieldOption.INDEXED), false, false, false, false, false);
fieldInfos.add(reader.getFieldNames(FieldOption.UNINDEXED), false);
+ fieldInfos.add(reader.getFieldNames(FieldOption.DOC_VALUES), false);
}
}
+ final SegmentCodecs codecInfo = SegmentCodecs.build(fieldInfos, this.codecs);
fieldInfos.write(directory, segment + ".fnm");
int docCount = 0;
diff --cc lucene/src/java/org/apache/lucene/index/SegmentReader.java
index b1b73929caf,6adf9554282..649caad071c
--- a/lucene/src/java/org/apache/lucene/index/SegmentReader.java
+++ b/lucene/src/java/org/apache/lucene/index/SegmentReader.java
@@@ -40,13 -39,7 +40,12 @@@ import org.apache.lucene.store.IndexOut
import org.apache.lucene.util.BitVector;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.CloseableThreadLocal;
- import org.apache.lucene.index.codecs.CodecProvider;
import org.apache.lucene.index.codecs.FieldsProducer;
+import org.apache.lucene.index.values.Bytes;
+import org.apache.lucene.index.values.Ints;
+import org.apache.lucene.index.values.DocValues;
+import org.apache.lucene.index.values.Floats;
+import org.apache.lucene.index.values.Values;
import org.apache.lucene.search.FieldCache; // not great (circular); used only to purge FieldCache entry on close
import org.apache.lucene.util.BytesRef;
@@@ -135,12 -124,13 +130,12 @@@ public class SegmentReader extends Inde
cfsDir = dir0;
fieldInfos = new FieldInfos(cfsDir, IndexFileNames.segmentFileName(segment, "", IndexFileNames.FIELD_INFOS_EXTENSION));
-
+
this.termsIndexDivisor = termsIndexDivisor;
-
+
// Ask codec for its Fields
- fields = si.getCodec().fieldsProducer(new SegmentReadState(cfsDir, si, fieldInfos, readBufferSize, termsIndexDivisor));
+ fields = codecInfo.codec().fieldsProducer(new SegmentReadState(cfsDir, si, fieldInfos, readBufferSize, termsIndexDivisor));
assert fields != null;
-
success = true;
} finally {
if (!success) {
diff --cc lucene/src/java/org/apache/lucene/index/codecs/simpletext/SimpleTextFieldsReader.java
index cc9f7de9be8,7d2037943f4..96571ee8730
--- a/lucene/src/java/org/apache/lucene/index/codecs/simpletext/SimpleTextFieldsReader.java
+++ b/lucene/src/java/org/apache/lucene/index/codecs/simpletext/SimpleTextFieldsReader.java
@@@ -102,14 -108,8 +109,14 @@@ class SimpleTextFieldsReader extends Fi
@Override
public TermsEnum terms() throws IOException {
- return new SimpleTextTermsEnum(in.getFilePointer(), omitTF);
+ return SimpleTextFieldsReader.this.terms(current).iterator();
}
+
+ @Override
+ public DocValues docValues() throws IOException {
+ // TODO Auto-generated method stub
+ return null;
+ }
}
private class SimpleTextTermsEnum extends TermsEnum {
diff --cc lucene/src/java/org/apache/lucene/util/IOUtils.java
index 158e56e302c,f03d302faa9..43120dde1bd
--- a/lucene/src/java/org/apache/lucene/util/IOUtils.java
+++ b/lucene/src/java/org/apache/lucene/util/IOUtils.java
@@@ -20,10 -20,11 +20,13 @@@ package org.apache.lucene.util
import java.io.Closeable;
import java.io.IOException;
+import org.apache.lucene.store.DataOutput;
+
/** @lucene.internal */
- public class IOUtils {
+ public final class IOUtils {
+
+ private IOUtils() {} // no instance
+
/**
* <p>Closes all given <tt>Closeable</tt>s, suppressing all thrown exceptions. Some of the <tt>Closeable</tt>s
* may be null, they are ignored. After everything is closed, method either throws <tt>priorException</tt>,
diff --cc lucene/src/test/org/apache/lucene/index/values/TestIndexValues.java
index 0912e0d1204,00000000000..5728c396600
mode 100644,000000..100644
--- a/lucene/src/test/org/apache/lucene/index/values/TestIndexValues.java
+++ b/lucene/src/test/org/apache/lucene/index/values/TestIndexValues.java
@@@ -1,723 -1,0 +1,722 @@@
+package org.apache.lucene.index.values;
+
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.EnumSet;
+import java.util.List;
+
+import org.apache.lucene.analysis.MockAnalyzer;
+import org.apache.lucene.document.Document;
+import org.apache.lucene.document.Field;
+import org.apache.lucene.document.Fieldable;
+import org.apache.lucene.document.ValuesField;
+import org.apache.lucene.document.Field.Index;
+import org.apache.lucene.document.Field.Store;
+import org.apache.lucene.index.CorruptIndexException;
+import org.apache.lucene.index.Fields;
+import org.apache.lucene.index.FieldsEnum;
+import org.apache.lucene.index.IndexReader;
+import org.apache.lucene.index.IndexWriter;
+import org.apache.lucene.index.IndexWriterConfig;
+import org.apache.lucene.index.LogDocMergePolicy;
+import org.apache.lucene.index.LogMergePolicy;
+import org.apache.lucene.index.MergePolicy;
+import org.apache.lucene.index.MultiFields;
+import org.apache.lucene.index.Term;
+import org.apache.lucene.index.codecs.CodecProvider;
+import org.apache.lucene.index.codecs.docvalues.DocValuesCodec;
+import org.apache.lucene.index.values.DocValues.SortedSource;
+import org.apache.lucene.index.values.DocValues.Source;
+import org.apache.lucene.store.Directory;
+import org.apache.lucene.store.LockObtainFailedException;
+import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.FloatsRef;
+import org.apache.lucene.util.LongsRef;
+import org.apache.lucene.util.LuceneTestCase;
+import org.apache.lucene.util.OpenBitSet;
+import org.apache.lucene.util.UnicodeUtil;
+import org.apache.lucene.util._TestUtil;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+
+public class TestIndexValues extends LuceneTestCase {
+
+ // TODO test addIndexes
+ private static DocValuesCodec docValuesCodec;
-
++ private static CodecProvider provider;
+ @BeforeClass
+ public static void beforeClassLuceneTestCaseJ4() {
+ LuceneTestCase.beforeClassLuceneTestCaseJ4();
- final CodecProvider cp = CodecProvider.getDefault();
- docValuesCodec = new DocValuesCodec(cp.lookup(CodecProvider
++ provider = new CodecProvider();
++ docValuesCodec = new DocValuesCodec(CodecProvider.getDefault().lookup(CodecProvider
+ .getDefaultCodec()));
- cp.register(docValuesCodec);
- CodecProvider.setDefaultCodec(docValuesCodec.name);
++ provider.register(docValuesCodec);
++ provider.setDefaultFieldCodec(docValuesCodec.name);
+ }
+
+ @AfterClass
+ public static void afterClassLuceneTestCaseJ4() {
- final CodecProvider cp = CodecProvider.getDefault();
- cp.unregister(docValuesCodec);
+ LuceneTestCase.afterClassLuceneTestCaseJ4();
+ }
+
+ public void testBytesStraight() throws IOException {
+ runTestBytes(Bytes.Mode.STRAIGHT, true);
+ runTestBytes(Bytes.Mode.STRAIGHT, false);
+ }
+
+ public void testBytesDeref() throws IOException {
+ runTestBytes(Bytes.Mode.DEREF, true);
+ runTestBytes(Bytes.Mode.DEREF, false);
+ }
+
+ public void testBytesSorted() throws IOException {
+ runTestBytes(Bytes.Mode.SORTED, true);
+ runTestBytes(Bytes.Mode.SORTED, false);
+ }
+
+ // nocommit -- for sorted test, do our own Sort of the
+ // values and verify it's identical
+ public void runTestBytes(final Bytes.Mode mode, final boolean fixedSize)
+ throws IOException {
+
+ final BytesRef bytesRef = new BytesRef();
+
+ final Comparator<BytesRef> comp = mode == Bytes.Mode.SORTED ? BytesRef
+ .getUTF8SortedAsUnicodeComparator() : null;
+
+ Directory dir = newDirectory();
+ Writer w = Bytes.getWriter(dir, "test", mode, comp, fixedSize);
+ int maxDoc = 220;
+ final String[] values = new String[maxDoc];
+ final int lenMin, lenMax;
+ if (fixedSize) {
+ lenMin = lenMax = 3 + random.nextInt(7);
+ } else {
+ lenMin = 1;
+ lenMax = 15 + random.nextInt(6);
+ }
+ for (int i = 0; i < 100; i++) {
+ final String s;
+ if (i > 0 && random.nextInt(5) <= 2) {
+ // use prior value
+ s = values[2 * random.nextInt(i)];
+ } else {
+ s = _TestUtil.randomUnicodeString(random, lenMin, lenMax);
+ }
+ values[2 * i] = s;
+
+ UnicodeUtil.UTF16toUTF8(s, 0, s.length(), bytesRef);
+ w.add(2 * i, bytesRef);
+ }
+ w.finish(maxDoc);
+
+ DocValues r = Bytes.getValues(dir, "test", mode, fixedSize, maxDoc);
+ for (int iter = 0; iter < 2; iter++) {
+ ValuesEnum bytesEnum = r.getEnum();
+ assertNotNull("enum is null", bytesEnum);
+ ValuesAttribute attr = bytesEnum.addAttribute(ValuesAttribute.class);
+ assertNotNull("attribute is null", attr);
+ BytesRef ref = attr.bytes();
+ assertNotNull("BytesRef is null - enum not initialized to use bytes",
+ attr);
+
+ for (int i = 0; i < 2; i++) {
+ final int idx = 2 * i;
+ assertEquals("doc: " + idx, idx, bytesEnum.advance(idx));
+ String utf8String = ref.utf8ToString();
+ assertEquals("doc: " + idx + " lenLeft: " + values[idx].length()
+ + " lenRight: " + utf8String.length(), values[idx], utf8String);
+ }
+ assertEquals(ValuesEnum.NO_MORE_DOCS, bytesEnum.advance(maxDoc));
+ assertEquals(ValuesEnum.NO_MORE_DOCS, bytesEnum.advance(maxDoc + 1));
+
+ bytesEnum.close();
+ }
+
+ // Verify we can load source twice:
+ for (int iter = 0; iter < 2; iter++) {
+ Source s;
+ DocValues.SortedSource ss;
+ if (mode == Bytes.Mode.SORTED) {
+ s = ss = getSortedSource(r, comp);
+ } else {
+ s = getSource(r);
+ ss = null;
+ }
+
+ for (int i = 0; i < 100; i++) {
+ final int idx = 2 * i;
+ assertNotNull("doc " + idx + "; value=" + values[idx], s.getBytes(idx));
+ assertEquals("doc " + idx, values[idx], s.getBytes(idx).utf8ToString());
+ if (ss != null) {
+ assertEquals("doc " + idx, values[idx], ss.getByOrd(ss.ord(idx))
+ .utf8ToString());
+ DocValues.SortedSource.LookupResult result = ss
+ .getByValue(new BytesRef(values[idx]));
+ assertTrue(result.found);
+ assertEquals(ss.ord(idx), result.ord);
+ }
+ }
+
+ // Lookup random strings:
+ if (mode == Bytes.Mode.SORTED) {
+ final int numValues = ss.getValueCount();
+ for (int i = 0; i < 1000; i++) {
+ BytesRef bytesValue = new BytesRef(_TestUtil.randomUnicodeString(
+ random, lenMin, lenMax));
+ SortedSource.LookupResult result = ss.getByValue(bytesValue);
+ if (result.found) {
+ assert result.ord > 0;
+ assertTrue(bytesValue.bytesEquals(ss.getByOrd(result.ord)));
+ int count = 0;
+ for (int k = 0; k < 100; k++) {
+ if (bytesValue.utf8ToString().equals(values[2 * k])) {
+ assertEquals(ss.ord(2 * k), result.ord);
+ count++;
+ }
+ }
+ assertTrue(count > 0);
+ } else {
+ assert result.ord >= 0;
+ if (result.ord == 0) {
+ final BytesRef firstRef = ss.getByOrd(1);
+ // random string was before our first
+ assertTrue(firstRef.compareTo(bytesValue) > 0);
+ } else if (result.ord == numValues) {
+ final BytesRef lastRef = ss.getByOrd(numValues);
+ // random string was after our last
+ assertTrue(lastRef.compareTo(bytesValue) < 0);
+ } else {
+ // random string fell between two of our values
+ final BytesRef before = (BytesRef) ss.getByOrd(result.ord)
+ .clone();
+ final BytesRef after = ss.getByOrd(result.ord + 1);
+ assertTrue(before.compareTo(bytesValue) < 0);
+ assertTrue(bytesValue.compareTo(after) < 0);
+
+ }
+ }
+ }
+ }
+ }
+
+ r.close();
+ dir.close();
+ }
+
+ public void testInts() throws IOException {
+ long maxV = 1;
+ final int NUM_VALUES = 1000;
+ final long[] values = new long[NUM_VALUES];
+ for (int rx = 1; rx < 63; rx++, maxV *= 2) {
+ for (int b = 0; b < 2; b++) {
+ Directory dir = newDirectory();
+ boolean useFixedArrays = b == 0;
+ Writer w = Ints.getWriter(dir, "test", useFixedArrays);
+ for (int i = 0; i < NUM_VALUES; i++) {
+ final long v = random.nextLong() % (1 + maxV);
+ values[i] = v;
+ w.add(i, v);
+ }
+ final int additionalDocs = 1 + random.nextInt(9);
+ w.finish(NUM_VALUES + additionalDocs);
+
+ DocValues r = Ints.getValues(dir, "test", useFixedArrays);
+ for (int iter = 0; iter < 2; iter++) {
+ Source s = getSource(r);
+ for (int i = 0; i < NUM_VALUES; i++) {
+ final long v = s.getInt(i);
+ assertEquals("index " + i + " b: " + b, values[i], v);
+ }
+ }
+
+ for (int iter = 0; iter < 2; iter++) {
+ ValuesEnum iEnum = r.getEnum();
+ ValuesAttribute attr = iEnum.addAttribute(ValuesAttribute.class);
+ LongsRef ints = attr.ints();
+ for (int i = 0; i < NUM_VALUES; i++) {
+ assertEquals(i, iEnum.nextDoc());
+ assertEquals(values[i], ints.get());
+ }
+ for (int i = NUM_VALUES; i < NUM_VALUES + additionalDocs; i++) {
+ assertEquals(i, iEnum.nextDoc());
+ assertEquals("" + i, 0, ints.get());
+ }
+
+ iEnum.close();
+ }
+
+ for (int iter = 0; iter < 2; iter++) {
+ ValuesEnum iEnum = r.getEnum();
+ ValuesAttribute attr = iEnum.addAttribute(ValuesAttribute.class);
+ LongsRef ints = attr.ints();
+ for (int i = 0; i < NUM_VALUES; i += 1 + random.nextInt(25)) {
+ assertEquals(i, iEnum.advance(i));
+ assertEquals(values[i], ints.get());
+ }
+ for (int i = NUM_VALUES; i < NUM_VALUES + additionalDocs; i++) {
+ assertEquals(i, iEnum.advance(i));
+ assertEquals("" + i, 0, ints.get());
+ }
+
+ iEnum.close();
+ }
+ r.close();
+ dir.close();
+ }
+ }
+ }
+
+ public void testFloats4() throws IOException {
+ runTestFloats(4, 0.00001);
+ }
+
+ private void runTestFloats(int precision, double delta) throws IOException {
+ Directory dir = newDirectory();
+ Writer w = Floats.getWriter(dir, "test", precision);
+ final int NUM_VALUES = 1000;
+ final double[] values = new double[NUM_VALUES];
+ for (int i = 0; i < NUM_VALUES; i++) {
+ final double v = precision == 4 ? random.nextFloat() : random
+ .nextDouble();
+ values[i] = v;
+ w.add(i, v);
+ }
+ final int additionalValues = 1 + random.nextInt(10);
+ w.finish(NUM_VALUES + additionalValues);
+
+ DocValues r = Floats.getValues(dir, "test", NUM_VALUES + additionalValues);
+ for (int iter = 0; iter < 2; iter++) {
+ Source s = getSource(r);
+ for (int i = 0; i < NUM_VALUES; i++) {
+ assertEquals(values[i], s.getFloat(i), 0.0f);
+ }
+ }
+
+ for (int iter = 0; iter < 2; iter++) {
+ ValuesEnum fEnum = r.getEnum();
+ ValuesAttribute attr = fEnum.addAttribute(ValuesAttribute.class);
+ FloatsRef floats = attr.floats();
+ for (int i = 0; i < NUM_VALUES; i++) {
+ assertEquals(i, fEnum.nextDoc());
+ assertEquals(values[i], floats.get(), delta);
+ }
+ for (int i = NUM_VALUES; i < NUM_VALUES + additionalValues; i++) {
+ assertEquals(i, fEnum.nextDoc());
+ assertEquals(0.0, floats.get(), delta);
+ }
+ fEnum.close();
+ }
+ for (int iter = 0; iter < 2; iter++) {
+ ValuesEnum fEnum = r.getEnum();
+ ValuesAttribute attr = fEnum.addAttribute(ValuesAttribute.class);
+ FloatsRef floats = attr.floats();
+ for (int i = 0; i < NUM_VALUES; i += 1 + random.nextInt(25)) {
+ assertEquals(i, fEnum.advance(i));
+ assertEquals(values[i], floats.get(), delta);
+ }
+ for (int i = NUM_VALUES; i < NUM_VALUES + additionalValues; i++) {
+ assertEquals(i, fEnum.advance(i));
+ assertEquals(0.0, floats.get(), delta);
+ }
+ fEnum.close();
+ }
+
+ r.close();
+ dir.close();
+ }
+
+ public void testFloats8() throws IOException {
+ runTestFloats(8, 0.0);
+ }
+
+ /**
+ * Tests complete indexing of {@link Values} including deletions, merging and
+ * sparse value fields on Compound-File
+ */
+ public void testCFSIndex() throws IOException {
+ // without deletions
+ IndexWriterConfig cfg = writerConfig(true);
+ // primitives - no deletes
+ runTestNumerics(cfg, false);
+
+ cfg = writerConfig(true);
+ // bytes - no deletes
+ runTestIndexBytes(cfg, false);
+
+ // with deletions
+ cfg = writerConfig(true);
+ // primitives
+ runTestNumerics(cfg, true);
+
+ cfg = writerConfig(true);
+ // bytes
+ runTestIndexBytes(cfg, true);
+ }
+
+ /**
+ * Tests complete indexing of {@link Values} including deletions, merging and
+ * sparse value fields on None-Compound-File
+ */
+ public void testIndex() throws IOException {
+ //
+ // without deletions
+ IndexWriterConfig cfg = writerConfig(false);
+ // primitives - no deletes
+ runTestNumerics(cfg, false);
+
+ cfg = writerConfig(false);
+ // bytes - no deletes
+ runTestIndexBytes(cfg, false);
+
+ // with deletions
+ cfg = writerConfig(false);
+ // primitives
+ runTestNumerics(cfg, true);
+
+ cfg = writerConfig(false);
+ // bytes
+ runTestIndexBytes(cfg, true);
+ }
+
+ private IndexWriterConfig writerConfig(boolean useCompoundFile) {
+ final IndexWriterConfig cfg = newIndexWriterConfig(TEST_VERSION_CURRENT,
+ new MockAnalyzer());
+ MergePolicy mergePolicy = cfg.getMergePolicy();
+ if (mergePolicy instanceof LogMergePolicy) {
+ ((LogMergePolicy) mergePolicy).setUseCompoundFile(useCompoundFile);
+ } else if (useCompoundFile) {
+ LogMergePolicy policy = new LogDocMergePolicy();
+ policy.setUseCompoundFile(useCompoundFile);
+ cfg.setMergePolicy(policy);
+ }
++ cfg.setCodecProvider(provider);
+ return cfg;
+ }
+
+ public void runTestNumerics(IndexWriterConfig cfg, boolean withDeletions)
+ throws IOException {
+ Directory d = newDirectory();
+ IndexWriter w = new IndexWriter(d, cfg);
+ final int numValues = 350;
+ final List<Values> numVariantList = new ArrayList<Values>(NUMERICS);
+
+ // run in random order to test if fill works correctly during merges
+ Collections.shuffle(numVariantList, random);
+ for (Values val : numVariantList) {
+ OpenBitSet deleted = indexValues(w, numValues, val, numVariantList,
+ withDeletions, 7);
+ List<Closeable> closeables = new ArrayList<Closeable>();
+ IndexReader r = IndexReader.open(w);
+ final int numRemainingValues = (int) (numValues - deleted.cardinality());
+ final int base = r.numDocs() - numRemainingValues;
+ switch (val) {
+ case PACKED_INTS:
+ case PACKED_INTS_FIXED: {
- if(val == Values.PACKED_INTS_FIXED)
- getDocValues(r, val.name());
+ DocValues intsReader = getDocValues(r, val.name());
++ assertNotNull(intsReader);
++
+ Source ints = getSource(intsReader);
+
+ ValuesEnum intsEnum = intsReader.getEnum();
+ assertNotNull(intsEnum);
+ LongsRef enumRef = intsEnum.addAttribute(ValuesAttribute.class).ints();
+ for (int i = 0; i < base; i++) {
+ assertEquals("index " + i, 0, ints.getInt(i));
+ assertEquals(val.name() + " base: " + base + " index: " + i, i,
+ random.nextBoolean() ? intsEnum.advance(i) : intsEnum.nextDoc());
+ assertEquals(0, enumRef.get());
+ }
+ int expected = 0;
+ for (int i = base; i < r.numDocs(); i++, expected++) {
+ while (deleted.get(expected)) {
+ expected++;
+ }
+ assertEquals("advance failed at index: " + i + " of " + r.numDocs()
+ + " docs", i, intsEnum.advance(i));
+ assertEquals(expected, enumRef.get());
+ assertEquals(expected, ints.getInt(i));
+
+ }
+ }
+ break;
+ case SIMPLE_FLOAT_4BYTE:
+ case SIMPLE_FLOAT_8BYTE: {
+ DocValues floatReader = getDocValues(r, val.name());
+ assertNotNull(floatReader);
+ Source floats = getSource(floatReader);
+ ValuesEnum floatEnum = floatReader.getEnum();
+ assertNotNull(floatEnum);
+ FloatsRef enumRef = floatEnum.addAttribute(ValuesAttribute.class)
+ .floats();
+
+ for (int i = 0; i < base; i++) {
+ assertEquals(" floats failed for doc: " + i + " base: " + base, 0.0d,
+ floats.getFloat(i), 0.0d);
+ assertEquals(i, random.nextBoolean() ? floatEnum.advance(i)
+ : floatEnum.nextDoc());
+ assertEquals("index " + i, 0.0, enumRef.get(), 0.0);
+ }
+ int expected = 0;
+ for (int i = base; i < r.numDocs(); i++, expected++) {
+ while (deleted.get(expected)) {
+ expected++;
+ }
+ assertEquals("advance failed at index: " + i + " of " + r.numDocs()
+ + " docs base:" + base, i, floatEnum.advance(i));
+ assertEquals("index " + i, 2.0 * expected, enumRef.get(), 0.00001);
+ assertEquals("index " + i, 2.0 * expected, floats.getFloat(i),
+ 0.00001);
+ }
+ }
+ break;
+ default:
+ fail("unexpected value " + val);
+ }
+
+ closeables.add(r);
+ for (Closeable toClose : closeables) {
+ toClose.close();
+ }
+ }
+ w.close();
+ d.close();
+ }
+
+ private static EnumSet<Values> BYTES = EnumSet.of(Values.BYTES_FIXED_DEREF,
+ Values.BYTES_FIXED_SORTED, Values.BYTES_FIXED_STRAIGHT,
+ Values.BYTES_VAR_DEREF, Values.BYTES_VAR_SORTED,
+ Values.BYTES_VAR_STRAIGHT);
+
+ private static EnumSet<Values> NUMERICS = EnumSet.of(Values.PACKED_INTS,
+ Values.PACKED_INTS_FIXED, Values.SIMPLE_FLOAT_4BYTE,
+ Values.SIMPLE_FLOAT_8BYTE);
+
+ private static Index[] IDX_VALUES = new Index[] { Index.ANALYZED,
+ Index.ANALYZED_NO_NORMS, Index.NOT_ANALYZED, Index.NOT_ANALYZED_NO_NORMS,
+ Index.NO };
+
+ private OpenBitSet indexValues(IndexWriter w, int numValues, Values value,
+ List<Values> valueVarList, boolean withDeletions, int multOfSeven)
+ throws CorruptIndexException, IOException {
+ final boolean isNumeric = NUMERICS.contains(value);
+ OpenBitSet deleted = new OpenBitSet(numValues);
+ Document doc = new Document();
+ Index idx = IDX_VALUES[random.nextInt(IDX_VALUES.length)];
+ Fieldable field = random.nextBoolean() ? new ValuesField(value.name())
+ : newField(value.name(), _TestUtil.randomRealisticUnicodeString(random,
+ 10), idx == Index.NO ? Store.YES : Store.NO, idx);
+ doc.add(field);
+
+ ValuesAttribute valuesAttribute = ValuesField.values(field);
+ valuesAttribute.setType(value);
+ final LongsRef intsRef = valuesAttribute.ints();
+ final FloatsRef floatsRef = valuesAttribute.floats();
+ final BytesRef bytesRef = valuesAttribute.bytes();
+
+ final String idBase = value.name() + "_";
+ final byte[] b = new byte[multOfSeven];
+ if (bytesRef != null) {
+ bytesRef.bytes = b;
+ bytesRef.length = b.length;
+ bytesRef.offset = 0;
+ }
+ //
+ byte upto = 0;
+ for (int i = 0; i < numValues; i++) {
+ if (isNumeric) {
+ switch (value) {
+ case PACKED_INTS:
+ case PACKED_INTS_FIXED:
+ intsRef.set(i);
+ break;
+ case SIMPLE_FLOAT_4BYTE:
+ case SIMPLE_FLOAT_8BYTE:
+ floatsRef.set(2.0f * i);
+ break;
+ default:
+ fail("unexpected value " + value);
+ }
+ } else {
+ for (int j = 0; j < b.length; j++) {
+ b[j] = upto++;
+ }
+ }
+ doc.removeFields("id");
+ doc.add(new Field("id", idBase + i, Store.YES,
+ Index.NOT_ANALYZED_NO_NORMS));
+ w.addDocument(doc);
+
+ if (i % 7 == 0) {
+ if (withDeletions && random.nextBoolean()) {
+ Values val = valueVarList.get(random.nextInt(1 + valueVarList
+ .indexOf(value)));
+ final int randInt = val == value ? random.nextInt(1 + i) : random
+ .nextInt(numValues);
+ w.deleteDocuments(new Term("id", val.name() + "_" + randInt));
+ if (val == value) {
+ deleted.set(randInt);
+ }
+ }
+ w.commit();
+
+ }
+ }
+ w.commit();
+
+ // TODO test unoptimized with deletions
+ if (withDeletions || random.nextBoolean())
+ w.optimize();
+ return deleted;
+ }
+
+ public void runTestIndexBytes(IndexWriterConfig cfg, boolean withDeletions)
+ throws CorruptIndexException, LockObtainFailedException, IOException {
+ Directory d = newDirectory();
+ IndexWriter w = new IndexWriter(d, cfg);
+ final List<Values> byteVariantList = new ArrayList<Values>(BYTES);
+ // run in random order to test if fill works correctly during merges
+ Collections.shuffle(byteVariantList, random);
+ final int numValues = 179 + random.nextInt(151);
+ for (Values byteIndexValue : byteVariantList) {
+ List<Closeable> closeables = new ArrayList<Closeable>();
+
+ int bytesSize = 7 + random.nextInt(128);
+ OpenBitSet deleted = indexValues(w, numValues, byteIndexValue,
+ byteVariantList, withDeletions, bytesSize);
+ final IndexReader r = IndexReader.open(w);
+ assertEquals(0, r.numDeletedDocs());
+ final int numRemainingValues = (int) (numValues - deleted.cardinality());
+ final int base = r.numDocs() - numRemainingValues;
+ DocValues bytesReader = getDocValues(r, byteIndexValue.name());
+ assertNotNull("field " + byteIndexValue.name()
+ + " returned null reader - maybe merged failed", bytesReader);
+ Source bytes = getSource(bytesReader);
+ ValuesEnum bytesEnum = bytesReader.getEnum();
+ assertNotNull(bytesEnum);
+ final ValuesAttribute attr = bytesEnum
+ .addAttribute(ValuesAttribute.class);
+ byte upto = 0;
+ // test the filled up slots for correctness
+ for (int i = 0; i < base; i++) {
+ final BytesRef br = bytes.getBytes(i);
+ String msg = " field: " + byteIndexValue.name() + " at index: " + i
+ + " base: " + base + " numDocs:" + r.numDocs();
+ switch (byteIndexValue) {
+ case BYTES_VAR_STRAIGHT:
+ case BYTES_FIXED_STRAIGHT:
+ assertEquals(i, bytesEnum.advance(i));
+ // fixed straight returns bytesref with zero bytes all of fixed
+ // length
+ assertNotNull("expected none null - " + msg, br);
+ if (br.length != 0) {
+ assertEquals("expected zero bytes of length " + bytesSize + " - "
+ + msg, bytesSize, br.length);
+ for (int j = 0; j < br.length; j++) {
+ assertEquals("Byte at index " + j + " doesn't match - " + msg, 0,
+ br.bytes[br.offset + j]);
+ }
+ }
+ break;
+ case BYTES_VAR_SORTED:
+ case BYTES_FIXED_SORTED:
+ case BYTES_VAR_DEREF:
+ case BYTES_FIXED_DEREF:
+ default:
+ assertNotNull("expected none null - " + msg, br);
+ if (br.length != 0) {
+ bytes.getBytes(i);
+ }
+ assertEquals("expected empty bytes - " + br.utf8ToString() + msg, 0,
+ br.length);
+ }
+ }
+ final BytesRef enumRef = attr.bytes();
+
+ // test the actual doc values added in this iteration
+ assertEquals(base + numRemainingValues, r.numDocs());
+ int v = 0;
+ for (int i = base; i < r.numDocs(); i++) {
+
+ String msg = " field: " + byteIndexValue.name() + " at index: " + i
+ + " base: " + base + " numDocs:" + r.numDocs() + " bytesSize: "
+ + bytesSize;
+ while (withDeletions && deleted.get(v++)) {
+ upto += bytesSize;
+ }
+
+ BytesRef br = bytes.getBytes(i);
+ if (bytesEnum.docID() != i)
+ assertEquals("seek failed for index " + i + " " + msg, i, bytesEnum
+ .advance(i));
+ for (int j = 0; j < br.length; j++, upto++) {
+ assertEquals(
+ "EnumRef Byte at index " + j + " doesn't match - " + msg, upto,
+ enumRef.bytes[enumRef.offset + j]);
+ assertEquals("SourceRef Byte at index " + j + " doesn't match - "
+ + msg, upto, br.bytes[br.offset + j]);
+ }
+ }
+
+ // clean up
+ closeables.add(r);
+ for (Closeable toClose : closeables) {
+ toClose.close();
+ }
+ }
+
+ w.close();
+ d.close();
+ }
+
+ private DocValues getDocValues(IndexReader reader, String field)
+ throws IOException {
+ boolean optimized = reader.isOptimized();
+ Fields fields = optimized ? reader.getSequentialSubReaders()[0].fields()
+ : MultiFields.getFields(reader);
+ switch (random.nextInt(optimized ? 3 : 2)) { // case 2 only if optimized
+ case 0:
+ return fields.docValues(field);
+ case 1:
+ FieldsEnum iterator = fields.iterator();
+ String name;
+ while ((name = iterator.next()) != null) {
+ if (name.equals(field))
+ return iterator.docValues();
+ }
+ throw new RuntimeException("no such field " + field);
+ case 2:// this only works if we are on an optimized index!
+ return reader.getSequentialSubReaders()[0].docValues(field);
+ }
+ throw new RuntimeException();
+ }
+
+ private Source getSource(DocValues values) throws IOException {
+ // getSource uses cache internally
+ return random.nextBoolean() ? values.load() : values.getSource();
+ }
+ private SortedSource getSortedSource(DocValues values, Comparator<BytesRef> comparator) throws IOException {
+ // getSortedSource uses cache internally
+ return random.nextBoolean() ? values.loadSorted(comparator) : values.getSortedSorted(comparator);
+ }
+}