Apache Lucene open-source search software
- Catch up with trunk - Removed usage of ValuesAttribute entirely and exposed Float, Bytes & LongRef directly via ValuesEnum - Made ValueField lean and prevent unnecessary object creation during indexing
Simon Willnauerfc29610b1dbb
diff --cc lucene/src/java/org/apache/lucene/document/AbstractField.javaindex 0bbd6841265,8f025aca33c..a45fc075076--- a/lucene/src/java/org/apache/lucene/document/AbstractField.java+++ b/lucene/src/java/org/apache/lucene/document/AbstractField.java@@@ -19,7 -19,6 +19,7 @@@ import org.apache.lucene.search.PhraseQimport org.apache.lucene.search.spans.SpanQuery; // for javadocsimport org.apache.lucene.analysis.TokenStream;import org.apache.lucene.index.FieldInvertState;- import org.apache.lucene.util.AttributeSource;++import org.apache.lucene.index.values.PerDocFieldValues;import org.apache.lucene.util.StringHelper; // for javadocs@@@ -293,16 -292,4 +293,13 @@@ public abstract class AbstractField impresult.append('>');return result.toString();}- private AttributeSource source;++ protected PerDocFieldValues docValues;+- public boolean hasFieldAttribute() {- return source != null;++ public PerDocFieldValues getDocValues() {++ return docValues;+ }+- public AttributeSource getFieldAttributes() {- if(source == null)- source = new AttributeSource();- return source;++ public void setDocValues(PerDocFieldValues docValues) {++ this.docValues = docValues;+ }-}diff --cc lucene/src/java/org/apache/lucene/document/ValuesField.javaindex d71a273a3d9,00000000000..5acb6f272c7mode 100644,000000..100644--- a/lucene/src/java/org/apache/lucene/document/ValuesField.java+++ b/lucene/src/java/org/apache/lucene/document/ValuesField.java@@@ -1,133 -1,0 +1,156 @@@+package org.apache.lucene.document;++/**+ * 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.Reader;+import java.util.Comparator;++import org.apache.lucene.analysis.TokenStream;+import org.apache.lucene.document.Field.Index;+import org.apache.lucene.document.Field.Store;+import org.apache.lucene.document.Field.TermVector;++import org.apache.lucene.index.values.PerDocFieldValues;+import org.apache.lucene.index.values.Values;- import org.apache.lucene.index.values.ValuesAttribute;- import org.apache.lucene.util.AttributeSource;+import org.apache.lucene.util.BytesRef;++/**+ *+ */+@SuppressWarnings("serial")- public class ValuesField extends AbstractField {- private final ValuesAttribute attr;- private final AttributeSource fieldAttributes;-++public class ValuesField extends AbstractField implements PerDocFieldValues {+++ protected BytesRef bytes;++ protected double doubleValue;++ protected long longValue;++ protected Values type;++ protected Comparator<BytesRef> bytesComparator;+++ public ValuesField(String name) {+ super(name, Store.NO, Index.NO, TermVector.NO);- fieldAttributes = getFieldAttributes();- attr = fieldAttributes.addAttribute(ValuesAttribute.class);++ setDocValues(this);+ }-+++ ValuesField() {+ this("");+ }++++ public void setInt(long value) {++ type = Values.PACKED_INTS;++ longValue = value;++ }+- public Reader readerValue() {- return null;++ public void setFloat(float value) {++ type = Values.SIMPLE_FLOAT_4BYTE;++ doubleValue = value;+ }+- public String stringValue() {- return null;++ public void setFloat(double value) {++ type = Values.SIMPLE_FLOAT_8BYTE;++ doubleValue = value;+ }+- public TokenStream tokenStreamValue() {- return tokenStream;++ public void setBytes(BytesRef value, Values type) {++ setBytes(value, type, null);+++ }+- public void setInt(long value) {- attr.setType(Values.PACKED_INTS);- attr.ints().set(value);++ public void setBytes(BytesRef value, Values type, Comparator<BytesRef> comp) {++ this.type = type;++ if (bytes == null) {++ this.bytes = new BytesRef();++ }++ bytes.copy(value);++ bytesComparator = comp;+ }+- public void setFloat(float value) {- attr.setType(Values.SIMPLE_FLOAT_4BYTE);- attr.floats().set(value);++ public BytesRef getBytes() {++ return bytes;+ }+- public void setFloat(double value) {- attr.setType(Values.SIMPLE_FLOAT_8BYTE);- attr.floats().set(value);++ public Comparator<BytesRef> bytesComparator() {++ return bytesComparator;+ }+- public void setBytes(BytesRef value, Values type) {- setBytes(value, type, null);++ public double getFloat() {++ return doubleValue;++ }+++ public long getInt() {++ return longValue;+ }+- public void setBytes(BytesRef value, Values type, Comparator<BytesRef> comp) {- attr.setType(type);- attr.bytes().copy(value);- attr.setBytesComparator(comp);++ public void setBytesComparator(Comparator<BytesRef> comp) {++ this.bytesComparator = comp;+ }+- public ValuesAttribute values() {- return attr;++ public void setType(Values type) {++ this.type = type;+ }-- public <T extends Fieldable> T set(T field) {- AttributeSource src = field.getFieldAttributes();- src.addAttribute(ValuesAttribute.class);- fieldAttributes.copyTo(field.getFieldAttributes());- return field;++++ public Values type() {++ return type;+ }-- public static ValuesAttribute values(Fieldable fieldable) {- return fieldable.getFieldAttributes().addAttribute(ValuesAttribute.class);++++ public Reader readerValue() {++ return null;+ }+- public static <T extends Fieldable> T set(T field, Values type) {- if(field instanceof ValuesField)++ public String stringValue() {++ return null;++ }++++ public TokenStream tokenStreamValue() {++ return tokenStream;++ }++++ public <T extends AbstractField> T set(T field) {++ field.setDocValues(this);++ return field;++ }++++ public static <T extends AbstractField> T set(T field, Values type) {++ if (field instanceof ValuesField)+ return field;+ final ValuesField valField = new ValuesField();+ switch (type) {+ case BYTES_FIXED_DEREF:+ case BYTES_FIXED_SORTED:+ case BYTES_FIXED_STRAIGHT:+ case BYTES_VAR_DEREF:+ case BYTES_VAR_SORTED:+ case BYTES_VAR_STRAIGHT:+ BytesRef ref = field.isBinary() ? new BytesRef(field.getBinaryValue(),- field.getBinaryOffset(), field.getBinaryLength()) : new BytesRef(field- .stringValue());++ field.getBinaryOffset(), field.getBinaryLength()) : new BytesRef(++ field.stringValue());+ valField.setBytes(ref, type);+ break;+ case PACKED_INTS:+ valField.setInt(Long.parseLong(field.stringValue()));+ break;+ case SIMPLE_FLOAT_4BYTE:+ valField.setFloat(Float.parseFloat(field.stringValue()));+ break;+ case SIMPLE_FLOAT_8BYTE:+ valField.setFloat(Double.parseDouble(field.stringValue()));+ break;+ default:+ throw new IllegalArgumentException("unknown type: " + type);+ }+ return valField.set(field);+ }+++}diff --cc lucene/src/java/org/apache/lucene/index/DocFieldProcessor.javaindex 4b37b0481c0,6e4d71ab499..c10473deab1--- a/lucene/src/java/org/apache/lucene/index/DocFieldProcessor.java+++ b/lucene/src/java/org/apache/lucene/index/DocFieldProcessor.java@@@ -19,13 -19,9 +19,13 @@@ package org.apache.lucene.indeximport java.io.IOException;import java.util.Collection;-import java.util.Map;import java.util.HashMap;+import java.util.Map;+import org.apache.lucene.index.codecs.FieldsConsumer;+import org.apache.lucene.index.codecs.docvalues.DocValuesConsumer;- import org.apache.lucene.index.values.ValuesAttribute;++import org.apache.lucene.index.values.PerDocFieldValues;+import org.apache.lucene.store.Directory;/*** This is a DocConsumer that gathers all fields under the@@@ -41,40 -37,11 +41,40 @@@ final class DocFieldProcessor extends Dfinal 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+ private SegmentWriteState docValuesConsumerState; // TODO this should be encapsulated in DocumentsWriter+++ synchronized DocValuesConsumer docValuesConsumer(Directory dir,- String segment, String name, ValuesAttribute attr, FieldInfo fieldInfo)++ String segment, String name, PerDocFieldValues values, FieldInfo fieldInfo)+ throws IOException {+ DocValuesConsumer valuesConsumer;+ if ((valuesConsumer = docValues.get(name)) == null) {- fieldInfo.setDocValues(attr.type());++ fieldInfo.setDocValues(values.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.+ */+ docValuesConsumerState = docWriter.segWriteState();+ fieldsConsumer = docValuesConsumerState.segmentCodecs.codec().fieldsConsumer(docValuesConsumerState);+ }+ 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;+ fieldInfos = docWriter.getFieldInfos();consumer.setFieldInfos(fieldInfos);fieldsWriter = new StoredFieldsWriter(docWriter, fieldInfos);}diff --cc lucene/src/java/org/apache/lucene/index/DocFieldProcessorPerThread.javaindex a12bbd3255b,298b3bd2b75..5eaddfcae25--- a/lucene/src/java/org/apache/lucene/index/DocFieldProcessorPerThread.java+++ b/lucene/src/java/org/apache/lucene/index/DocFieldProcessorPerThread.java@@@ -22,13 -22,9 +22,13 @@@ import java.util.Collectionimport java.util.HashSet;import java.util.List;import java.io.IOException;+++import org.apache.lucene.document.AbstractField;import org.apache.lucene.document.Document;import org.apache.lucene.document.Fieldable;+import org.apache.lucene.index.codecs.docvalues.DocValuesConsumer;- import org.apache.lucene.index.values.ValuesAttribute;++import org.apache.lucene.index.values.PerDocFieldValues;import org.apache.lucene.util.ArrayUtil;- import org.apache.lucene.util.AttributeSource;import org.apache.lucene.util.RamUsageEstimator;/**@@@ -247,23 -243,10 +247,24 @@@ final class DocFieldProcessorPerThread// enabled; we could save [small amount of] CPU// here.ArrayUtil.quickSort(fields, 0, fieldCount, fieldsComp);-- for(int i=0;i<fieldCount;i++)- fields[i].consumer.processFields(fields[i].fields, fields[i].fieldCount);-+++ for(int i=0;i<fieldCount;i++) {+ final DocFieldProcessorPerField perField = fields[i];+ final Fieldable fieldable = perField.fields[0];+ perField.consumer.processFields(perField.fields, perField.fieldCount);+- if(!fieldable.hasFieldAttribute())++ if (!(fieldable instanceof AbstractField)) {+ continue;- final AttributeSource attrSource = fieldable.getFieldAttributes();- if(!attrSource.hasAttribute(ValuesAttribute.class))++ }++ final PerDocFieldValues docValues = ((AbstractField)fieldable).getDocValues();++ if (docValues == null) {+ continue;- final ValuesAttribute attribute = attrSource.getAttribute(ValuesAttribute.class);++ }+ final DocValuesConsumer consumer = docFieldProcessor.docValuesConsumer(docState.docWriter.directory,- docState.docWriter.segment, fieldable.name(), attribute, perField.fieldInfo);- consumer.add(docState.docID, attribute);++ docState.docWriter.segment, fieldable.name(), docValues, perField.fieldInfo);++ consumer.add(docState.docID, docValues);+ }if (docState.maxTermPrefix != null && docState.infoStream != null) {docState.infoStream.println("WARNING: document contains at least one immense term (whose UTF8 encoding is longer than the max length " + DocumentsWriter.MAX_TERM_LENGTH_UTF8 + "), all of which were skipped. Please correct the analyzer to not produce such terms. The prefix of the first immense term is: '" + docState.maxTermPrefix + "...'");docState.maxTermPrefix = null;diff --cc lucene/src/java/org/apache/lucene/index/DocumentsWriter.javaindex 296c57af867,8f7ce5b17ad..960bc2d9b6e--- a/lucene/src/java/org/apache/lucene/index/DocumentsWriter.java+++ b/lucene/src/java/org/apache/lucene/index/DocumentsWriter.java@@@ -602,16 -608,9 +608,16 @@@ final class DocumentsWritersynchronized private void initFlushState(boolean onlyDocStore) {initSegmentName(onlyDocStore);- final SegmentCodecs info = SegmentCodecs.build(docFieldProcessor.fieldInfos, writer.codecs);- flushState = new SegmentWriteState(infoStream, directory, segment, docFieldProcessor.fieldInfos,+ final SegmentCodecs info = SegmentCodecs.build(fieldInfos, writer.codecs);+ flushState = new SegmentWriteState(infoStream, directory, segment, fieldInfos,- docStoreSegment, numDocsInRAM, numDocsInStore, writer.getConfig().getTermIndexInterval(), info);+ docStoreSegment, numDocsInRAM, numDocsInStore, writer.getConfig().getTermIndexInterval(), info, bytesUsed);+ }++ 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(),+ info, bytesUsed);}/** Returns the SegmentCodecs used to flush the last segment */diff --cc lucene/src/java/org/apache/lucene/index/codecs/docvalues/DocValuesCodec.javaindex 43264f67b84,00000000000..935e3247229mode 100644,000000..100644--- a/lucene/src/java/org/apache/lucene/index/codecs/docvalues/DocValuesCodec.java+++ b/lucene/src/java/org/apache/lucene/index/codecs/docvalues/DocValuesCodec.java@@@ -1,295 -1,0 +1,295 @@@+package org.apache.lucene.index.codecs.docvalues;++/**+ * 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.Comparator;+import java.util.HashSet;+import java.util.Iterator;+import java.util.Set;+import java.util.Map.Entry;- import java.util.concurrent.atomic.AtomicLong;++import org.apache.lucene.index.FieldInfo;+import org.apache.lucene.index.FieldsEnum;+import org.apache.lucene.index.SegmentInfo;+import org.apache.lucene.index.SegmentReadState;+import org.apache.lucene.index.SegmentWriteState;+import org.apache.lucene.index.Terms;+import org.apache.lucene.index.TermsEnum;+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.values.DocValues;+import org.apache.lucene.index.values.Writer;+import org.apache.lucene.store.Directory;+import org.apache.lucene.util.AttributeSource;+import org.apache.lucene.util.BytesRef;++/**+ * A codec that adds DocValues support to a given codec transparently.++ * @lucene.experimental+ */+public class DocValuesCodec extends Codec {+ private final Codec other;+ private final Comparator<BytesRef> comparator;++ public DocValuesCodec(Codec other, Comparator<BytesRef> comparator) {+ this.name = "docvalues_" + other.name;+ this.other = other;+ this.comparator = comparator;+ }++ public DocValuesCodec(Codec other) {+ this(other, null);+ }++ @Override+ public FieldsConsumer fieldsConsumer(SegmentWriteState state)+ throws IOException {+ final WrappingFieldsConsumer consumer;+ consumer = new WrappingFieldsConsumer(other, comparator, state);+ // nocommit this is a hack and only necessary since+ // we want to initialized the wrapped+ // fieldsConsumer lazily with a SegmentWriteState created after the docvalue+ // ones is. We should fix this in DocumentWriter I guess. See+ // DocFieldProcessor too!+ return consumer;+ }++ private static class WrappingFieldsConsumer extends FieldsConsumer {+ private final SegmentWriteState state;+ private FieldsConsumer wrappedConsumer;+ private final Codec other;+ private final Comparator<BytesRef> comparator;+ private DocValuesCodecInfo info;++ public WrappingFieldsConsumer(Codec other, Comparator<BytesRef> comparator, SegmentWriteState state) {+ this.other = other;+ this.comparator = comparator;+ this.state = state;+ }++ @Override+ public void close() throws IOException {+ synchronized (this) {+ if (info != null) {+ info.write(state);+ info = null;+ }+ if (wrappedConsumer != null) {+ wrappedConsumer.close();+ }+ }++ }++ @Override+ public synchronized DocValuesConsumer addValuesField(FieldInfo field)+ throws IOException {+ if(info == null) {+ info = new DocValuesCodecInfo();+ }+ final DocValuesConsumer consumer = DocValuesConsumer.create(info.docValuesId(state.segmentName, state.codecId, ""+ + field.number),+ // TODO can we have a compound file per segment and codec for+ // docvalues?+ state.directory, field, comparator, state.bytesUsed);+ info.add(field.number);+ return consumer;+ }++ @Override+ public TermsConsumer addField(FieldInfo field) throws IOException {+ synchronized (this) {+ if (wrappedConsumer == null)+ wrappedConsumer = other.fieldsConsumer(state);+ }+ return wrappedConsumer.addField(field);+ }+ }++ @Override+ public FieldsProducer fieldsProducer(SegmentReadState state)+ throws IOException {+ Directory dir = state.dir;+ Set<String> files = new HashSet<String>();++ other.files(dir, state.segmentInfo, state.codecId, files);+ for (String string : files) { // for now we just check if one of the files+ // exists and open the producer+ if (dir.fileExists(string))+ return new WrappingFielsdProducer(state, other.fieldsProducer(state));+ }+ return new WrappingFielsdProducer(state, FieldsProducer.EMPTY);+ }++ @Override+ public void files(Directory dir, SegmentInfo segmentInfo, String codecId,+ Set<String> files) throws IOException {+ other.files(dir, segmentInfo, codecId, files);+ // TODO can we have a compound file per segment and codec for docvalues?+ DocValuesCodecInfo info = new DocValuesCodecInfo(); // TODO can we do that+ // only once?+ info.read(dir, segmentInfo, codecId);+ info.files(dir, segmentInfo, codecId, files);+ }++ @Override+ public void getExtensions(Set<String> extensions) {+ other.getExtensions(extensions);+ extensions.add(Writer.DATA_EXTENSION);+ extensions.add(Writer.INDEX_EXTENSION);+ extensions.add(DocValuesCodecInfo.INFO_FILE_EXT);+ }++ static class WrappingFielsdProducer extends DocValuesProducerBase {++ private final FieldsProducer other;++ WrappingFielsdProducer(SegmentReadState state, FieldsProducer other)+ throws IOException {+ super(state.segmentInfo, state.dir, state.fieldInfos, state.codecId);+ this.other = other;+ }++ @Override+ public void close() throws IOException {+ try {+ other.close();+ } finally {+ super.close();+ }+ }++ @Override+ public void loadTermsIndex(int indexDivisor) throws IOException {+ other.loadTermsIndex(indexDivisor);+ }++ @Override+ public FieldsEnum iterator() throws IOException {+ return new WrappingFieldsEnum(other.iterator(), docValues.entrySet()+ .iterator());+ }++ @Override+ public Terms terms(String field) throws IOException {+ return other.terms(field);+ }+ }++ static abstract class NameValue<V> {+ String name;+ V value;++ NameValue<?> smaller(NameValue<?> other) throws IOException {+ if (other.name == null) {+ if (this.name == null) {+ return null;+ }+ return this;+ } else if (this.name == null) {+ return other;+ }+ final int res = this.name.compareTo(other.name);+ if (res < 0)+ return this;+ if (res == 0)+ other.name = this.name;+ return other;+ }++ abstract NameValue<V> next() throws IOException;+ }++ static class FieldsEnumNameValue extends NameValue<FieldsEnum> {+ @Override+ NameValue<FieldsEnum> next() throws IOException {+ name = value.next();+ return this;+ }+ }++ static class DocValueNameValue extends NameValue<DocValues> {+ Iterator<Entry<String, DocValues>> iter;++ @Override+ NameValue<DocValues> next() {+ if (iter.hasNext()) {+ Entry<String, DocValues> next = iter.next();+ value = next.getValue();+ name = next.getKey();+ } else {+ name = null;+ }+ return this;+ }+ }++ static class WrappingFieldsEnum extends FieldsEnum {+ private final DocValueNameValue docValues = new DocValueNameValue();+ private final NameValue<FieldsEnum> fieldsEnum = new FieldsEnumNameValue();+ private NameValue<?> coordinator;++ @Override+ public AttributeSource attributes() {+ return fieldsEnum.value.attributes();+ }++ public WrappingFieldsEnum(FieldsEnum wrapped,+ Iterator<Entry<String, DocValues>> docValues) {+ this.docValues.iter = docValues;+ this.fieldsEnum.value = wrapped;+ coordinator = null;+ }++ @Override+ public DocValues docValues() throws IOException {+ if (docValues.name == coordinator.name)+ return docValues.value;+ return null;+ }++ @Override+ public String next() throws IOException {+ if (coordinator == null) {+ coordinator = fieldsEnum.next().smaller(docValues.next());+ } else {+ String current = coordinator.name;+ if (current == docValues.name) {+ docValues.next();+ }+ if (current == fieldsEnum.name) {+ fieldsEnum.next();+ }+ coordinator = docValues.smaller(fieldsEnum);++ }+ return coordinator == null ? null : coordinator.name;+ }++ @Override+ public TermsEnum terms() throws IOException {+ if (fieldsEnum.name == coordinator.name) {+ return fieldsEnum.value.terms();+ }+ return null;+ }+ }++}diff --cc lucene/src/java/org/apache/lucene/index/codecs/docvalues/DocValuesConsumer.javaindex 2a6a7c7a88f,00000000000..b89e7ace246mode 100644,000000..100644--- a/lucene/src/java/org/apache/lucene/index/codecs/docvalues/DocValuesConsumer.java+++ b/lucene/src/java/org/apache/lucene/index/codecs/docvalues/DocValuesConsumer.java@@@ -1,107 -1,0 +1,107 @@@+package org.apache.lucene.index.codecs.docvalues;++/**+ * 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.Collection;+import java.util.Comparator;+import java.util.concurrent.atomic.AtomicLong;++import org.apache.lucene.index.FieldInfo;+import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.values.DocValues;- import org.apache.lucene.index.values.ValuesAttribute;++import org.apache.lucene.index.values.PerDocFieldValues;+import org.apache.lucene.index.values.Writer;+import org.apache.lucene.store.Directory;+import org.apache.lucene.util.Bits;+import org.apache.lucene.util.BytesRef;++/**+ * @lucene.experimental+ */+// TODO this might need to go in the codec package since is a direct relative to+// TermsConsumer+public abstract class DocValuesConsumer {++ protected AtomicLong bytesUsed = new AtomicLong(0);++ protected DocValuesConsumer(AtomicLong bytesUsed) {+ this.bytesUsed = bytesUsed;+ }++ public final long bytesUsed() {+ return this.bytesUsed.get();+ }+- public abstract void add(int docID, ValuesAttribute attr) throws IOException;++ public abstract void add(int docID, PerDocFieldValues docValues) throws IOException;++ public abstract void finish(int docCount) throws IOException;++ public abstract void files(Collection<String> files) throws IOException;++ public void merge(org.apache.lucene.index.codecs.MergeState mergeState,+ DocValues values) throws IOException {+ // TODO we need some kind of compatibility notation for values such+ // that two slightly different segments can be merged eg. fixed vs.+ // variable byte len or float32 vs. float64+ int docBase = 0;+ boolean merged = false;+ /*+ * We ignore the given DocValues here and merge from the subReaders directly+ * to support bulk copies on the DocValues Writer level. if this gets merged+ * with MultiDocValues the writer can not optimize for bulk-copyable data+ */+ for (final IndexReader reader : mergeState.readers) {+ final DocValues r = reader.docValues(mergeState.fieldInfo.name);+ if (r != null) {+ merged = true;+ merge(new Writer.MergeState(r, docBase, reader.maxDoc(), reader+ .getDeletedDocs()));+ }+ docBase += reader.numDocs();+ }+ if (merged)+ finish(mergeState.mergedDocCount);+ }++ protected abstract void merge(MergeState mergeState) throws IOException;++ /*+ * specialized auxiliary MergeState is necessary since we don't want to+ * exploit internals up to the codec ones+ */+ public static class MergeState {+ public final DocValues reader;+ public final int docBase;+ public final int docCount;+ public final Bits bits;++ public MergeState(DocValues reader, int docBase, int docCount, Bits bits) {+ assert reader != null;+ this.reader = reader;+ this.docBase = docBase;+ this.docCount = docCount;+ this.bits = bits;+ }+ }++ public static DocValuesConsumer create(String id,+ Directory directory, FieldInfo field, Comparator<BytesRef> comp, AtomicLong bytesUsed)+ throws IOException {+ return Writer.create(field.getDocValues(), id, directory, comp, bytesUsed);+ }+}diff --cc lucene/src/java/org/apache/lucene/index/codecs/docvalues/DocValuesProducerBase.javaindex adf9349e766,00000000000..08307d4dd97mode 100644,000000..100644--- a/lucene/src/java/org/apache/lucene/index/codecs/docvalues/DocValuesProducerBase.java+++ b/lucene/src/java/org/apache/lucene/index/codecs/docvalues/DocValuesProducerBase.java@@@ -1,99 -1,0 +1,100 @@@+package org.apache.lucene.index.codecs.docvalues;+/**+ * 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.Collection;+import java.util.TreeMap;++import org.apache.lucene.index.FieldInfo;+import org.apache.lucene.index.FieldInfos;- import org.apache.lucene.index.IndexFileNames;+import org.apache.lucene.index.SegmentInfo;+import org.apache.lucene.index.codecs.FieldsProducer;+import org.apache.lucene.index.values.Bytes;+import org.apache.lucene.index.values.DocValues;+import org.apache.lucene.index.values.Floats;+import org.apache.lucene.index.values.Ints;+import org.apache.lucene.index.values.Values;- import org.apache.lucene.index.values.Writer;+import org.apache.lucene.store.Directory;+import org.apache.lucene.util.IntsRef;+++/**++ * @lucene.experimental++ */+public abstract class DocValuesProducerBase extends FieldsProducer{++ protected final TreeMap<String, DocValues> docValues = new TreeMap<String, DocValues>();+ private final DocValuesCodecInfo info = new DocValuesCodecInfo();++ protected DocValuesProducerBase(SegmentInfo si, Directory dir, FieldInfos fieldInfo, String codecId) throws IOException {+ info.read(dir, si, codecId);+ load(fieldInfo, si.name, si.docCount, dir, codecId);+ }++ @Override+ public DocValues docValues(String field) throws IOException {+ return docValues.get(field);+ }++ // Only opens files... doesn't actually load any values+ protected void load(FieldInfos fieldInfos, String segment, int docCount,+ Directory dir, String codecId) throws IOException {+ final IntsRef valueFields = info.fieldIDs();+ for (int i = valueFields.offset; i < valueFields.length; i++) {+ final int fieldNumber = valueFields.ints[i];+ final FieldInfo fieldInfo = fieldInfos.fieldInfo(fieldNumber);+ assert fieldInfo.hasDocValues();+ final String field = fieldInfo.name;+ //TODO can we have a compound file per segment and codec for docvalues?+ final String id = info.docValuesId( segment, codecId, fieldNumber+"");+ docValues.put(field, loadDocValues(docCount, dir, id, fieldInfo.getDocValues()));+ }+ }++ protected DocValues loadDocValues(int docCount, Directory dir, String id,+ Values v) throws IOException {+ switch (v) {+ case PACKED_INTS:+ return Ints.getValues(dir, id, false);+ case SIMPLE_FLOAT_4BYTE:+ return Floats.getValues(dir, id, docCount);+ case SIMPLE_FLOAT_8BYTE:+ return Floats.getValues(dir, id, docCount);+ case BYTES_FIXED_STRAIGHT:+ return Bytes.getValues(dir, id, Bytes.Mode.STRAIGHT, true, docCount);+ case BYTES_FIXED_DEREF:+ return Bytes.getValues(dir, id, Bytes.Mode.DEREF, true, docCount);+ case BYTES_FIXED_SORTED:+ return Bytes.getValues(dir, id, Bytes.Mode.SORTED, true, docCount);+ case BYTES_VAR_STRAIGHT:+ return Bytes.getValues(dir, id, Bytes.Mode.STRAIGHT, false, docCount);+ case BYTES_VAR_DEREF:+ return Bytes.getValues(dir, id, Bytes.Mode.DEREF, false, docCount);+ case BYTES_VAR_SORTED:+ return Bytes.getValues(dir, id, Bytes.Mode.SORTED, false, docCount);+ default:+ throw new IllegalStateException("unrecognized index values mode " + v);+ }+ }++ @Override+ public void close() throws IOException {+ Collection<DocValues> values = docValues.values();+ for (DocValues docValues : values) {+ docValues.close();+ }+ }+}diff --cc lucene/src/java/org/apache/lucene/index/values/Bytes.javaindex 89cd3441c51,00000000000..e54e575f4c0mode 100644,000000..100644--- a/lucene/src/java/org/apache/lucene/index/values/Bytes.java+++ b/lucene/src/java/org/apache/lucene/index/values/Bytes.java@@@ -1,413 -1,0 +1,411 @@@+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.+ */++/** Base class for specific Bytes Reader/Writer implementations */+import java.io.IOException;+import java.util.Collection;+import java.util.Comparator;+import java.util.concurrent.atomic.AtomicLong;++import org.apache.lucene.index.IndexFileNames;+import org.apache.lucene.index.values.DocValues.MissingValue;+import org.apache.lucene.index.values.DocValues.SortedSource;+import org.apache.lucene.index.values.DocValues.Source;+import org.apache.lucene.index.values.DocValues.SourceEnum;+import org.apache.lucene.store.Directory;+import org.apache.lucene.store.IndexInput;+import org.apache.lucene.store.IndexOutput;+import org.apache.lucene.util.AttributeSource;+import org.apache.lucene.util.ByteBlockPool;+import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.CodecUtil;+import org.apache.lucene.util.PagedBytes;++/**+ * Provides concrete Writer/Reader impls for byte[] value per document. There+ * are 6 package-private impls of this, for all combinations of+ * STRAIGHT/DEREF/SORTED X fixed/not fixed.+ *+ * <p>+ * NOTE: The total amount of byte[] data stored (across a single segment) cannot+ * exceed 2GB.+ * </p>+ * <p>+ * NOTE: Each byte[] must be <= 32768 bytes in length+ * </p>++ * @lucene.experimental+ */+// TODO - add bulk copy where possible+public final class Bytes {++ // don't instantiate!+ private Bytes() {+ }++ public static enum Mode {+ STRAIGHT, DEREF, SORTED+ };++ // TODO -- i shouldn't have to specify fixed? can+ // track itself & do the write thing at write time?+ public static Writer getWriter(Directory dir, String id, Mode mode,+ Comparator<BytesRef> comp, boolean fixedSize, AtomicLong bytesUsed) throws IOException {++ if (comp == null) {+ comp = BytesRef.getUTF8SortedAsUnicodeComparator();+ }++ if (fixedSize) {+ if (mode == Mode.STRAIGHT) {+ return new FixedStraightBytesImpl.Writer(dir, id);+ } else if (mode == Mode.DEREF) {+ return new FixedDerefBytesImpl.Writer(dir, id, bytesUsed);+ } else if (mode == Mode.SORTED) {+ return new FixedSortedBytesImpl.Writer(dir, id, comp, bytesUsed);+ }+ } else {+ if (mode == Mode.STRAIGHT) {+ return new VarStraightBytesImpl.Writer(dir, id, bytesUsed);+ } else if (mode == Mode.DEREF) {+ return new VarDerefBytesImpl.Writer(dir, id, bytesUsed);+ } else if (mode == Mode.SORTED) {+ return new VarSortedBytesImpl.Writer(dir, id, comp, bytesUsed);+ }+ }++ throw new IllegalArgumentException("");+ }++ // TODO -- I can peek @ header to determing fixed/mode?+ public static DocValues getValues(Directory dir, String id, Mode mode,+ boolean fixedSize, int maxDoc) throws IOException {+ if (fixedSize) {+ if (mode == Mode.STRAIGHT) {+ try {+ return new FixedStraightBytesImpl.Reader(dir, id, maxDoc);+ } catch (IOException e) {+ throw e;+ }+ } else if (mode == Mode.DEREF) {+ try {+ return new FixedDerefBytesImpl.Reader(dir, id, maxDoc);+ } catch (IOException e) {+ throw e;+ }+ } else if (mode == Mode.SORTED) {+ return new FixedSortedBytesImpl.Reader(dir, id, maxDoc);+ }+ } else {+ if (mode == Mode.STRAIGHT) {+ return new VarStraightBytesImpl.Reader(dir, id, maxDoc);+ } else if (mode == Mode.DEREF) {+ return new VarDerefBytesImpl.Reader(dir, id, maxDoc);+ } else if (mode == Mode.SORTED) {+ return new VarSortedBytesImpl.Reader(dir, id, maxDoc);+ }+ }++ throw new IllegalArgumentException("");+ }++ static abstract class BytesBaseSource extends Source {+ protected final IndexInput datIn;+ protected final IndexInput idxIn;+ protected final static int PAGED_BYTES_BITS = 15;+ private final PagedBytes pagedBytes;+ protected final PagedBytes.Reader data;+ protected final long totalLengthInBytes;++ protected BytesBaseSource(IndexInput datIn, IndexInput idxIn,+ PagedBytes pagedBytes, long bytesToRead) throws IOException {+ assert bytesToRead <= datIn.length() : " file size is less than the expected size diff: "+ + (bytesToRead - datIn.length()) + " pos: " + datIn.getFilePointer();+ this.datIn = datIn;+ this.totalLengthInBytes = bytesToRead;+ this.pagedBytes = pagedBytes;+ this.pagedBytes.copy(datIn, bytesToRead);+ data = pagedBytes.freeze(true);+ this.idxIn = idxIn;+ }++ public void close() throws IOException {+ data.close();+ try {+ if (datIn != null)+ datIn.close();+ } finally {+ if (idxIn != null) // if straight - no index needed+ idxIn.close();+ }+ }++ protected abstract int maxDoc();++ public long ramBytesUsed() {+ return 0; // TODO+ }++ @Override+ public ValuesEnum getEnum(AttributeSource attrSource) throws IOException {+ final MissingValue missing = getMissing();+ return new SourceEnum(attrSource, type(), this, maxDoc()) {- final BytesRef bytesRef = attr.bytes();-+ @Override+ public int advance(int target) throws IOException {+ if (target >= numDocs) {+ return pos = NO_MORE_DOCS;+ }+ while (source.getBytes(target, bytesRef) == missing.bytesValue) {+ if (++target >= numDocs) {+ return pos = NO_MORE_DOCS;+ }+ }+ return pos = target;+ }+ };+ }++ }++ static abstract class BytesBaseSortedSource extends SortedSource {+ protected final IndexInput datIn;+ protected final IndexInput idxIn;+ protected final BytesRef defaultValue = new BytesRef();+ protected final static int PAGED_BYTES_BITS = 15;+ private final PagedBytes pagedBytes;+ protected final PagedBytes.Reader data;+ protected final LookupResult lookupResult = new LookupResult();+ private final Comparator<BytesRef> comp;++ protected BytesBaseSortedSource(IndexInput datIn, IndexInput idxIn,+ Comparator<BytesRef> comp, PagedBytes pagedBytes, long bytesToRead)+ throws IOException {+ assert bytesToRead <= datIn.length() : " file size is less than the expected size diff: "+ + (bytesToRead - datIn.length()) + " pos: " + datIn.getFilePointer();+ this.datIn = datIn;+ this.pagedBytes = pagedBytes;+ this.pagedBytes.copy(datIn, bytesToRead);+ data = pagedBytes.freeze(true);+ this.idxIn = idxIn;+ this.comp = comp == null ? BytesRef.getUTF8SortedAsUnicodeComparator()+ : comp;++ }++ @Override+ public BytesRef getByOrd(int ord, BytesRef bytesRef) {+ return ord == 0 ? null : deref(--ord, bytesRef);+ }++ public void close() throws IOException {+ if (datIn != null)+ datIn.close();+ if (idxIn != null) // if straight+ idxIn.close();+ }++ protected abstract int maxDoc();++ protected abstract BytesRef deref(int ord, BytesRef bytesRef);++ protected LookupResult binarySearch(BytesRef b, BytesRef bytesRef, int low,+ int high) {+ while (low <= high) {+ int mid = (low + high) >>> 1;+ deref(mid, bytesRef);+ final int cmp = comp.compare(bytesRef, b);+ if (cmp < 0) {+ low = mid + 1;+ } else if (cmp > 0) {+ high = mid - 1;+ } else {+ lookupResult.ord = mid + 1;+ lookupResult.found = true;+ return lookupResult;+ }+ }+ assert comp.compare(bytesRef, b) != 0;+ lookupResult.ord = low;+ lookupResult.found = false;+ return lookupResult;+ }++ @Override+ public ValuesEnum getEnum(AttributeSource attrSource) throws IOException {+ final MissingValue missing = getMissing();+ return new SourceEnum(attrSource, type(), this, maxDoc()) {- final BytesRef bytesRef = attr.bytes();++ @Override+ public int advance(int target) throws IOException {+ if (target >= numDocs) {+ return pos = NO_MORE_DOCS;+ }+ while (source.getBytes(target, bytesRef) == missing.bytesValue) {+ if (++target >= numDocs) {+ return pos = NO_MORE_DOCS;+ }+ }+ return pos = target;+ }+ };+ }+ }++ static abstract class BytesWriterBase extends Writer {++ private final Directory dir;+ private final String id;+ protected IndexOutput idxOut;+ protected IndexOutput datOut;+ protected BytesRef bytesRef;+ private final String codecName;+ private final int version;+ protected final ByteBlockPool pool;++ protected BytesWriterBase(Directory dir, String id, String codecName,+ int version, boolean initIndex, boolean initData, ByteBlockPool pool,+ AtomicLong bytesUsed) throws IOException {+ super(bytesUsed);+ this.dir = dir;+ this.id = id;+ this.codecName = codecName;+ this.version = version;+ this.pool = pool;+ if (initData)+ initDataOut();+ if (initIndex)+ initIndexOut();+ }++ protected void initDataOut() throws IOException {+ datOut = dir.createOutput(IndexFileNames.segmentFileName(id, "",+ DATA_EXTENSION));+ CodecUtil.writeHeader(datOut, codecName, version);+ }++ protected void initIndexOut() throws IOException {+ idxOut = dir.createOutput(IndexFileNames.segmentFileName(id, "",+ INDEX_EXTENSION));+ CodecUtil.writeHeader(idxOut, codecName, version);+ }++ public long ramBytesUsed() {+ return bytesUsed.get();+ }++ /**+ * Must be called only with increasing docIDs. It's OK for some docIDs to be+ * skipped; they will be filled with 0 bytes.+ */+ @Override+ public abstract void add(int docID, BytesRef bytes) throws IOException;++ @Override+ public synchronized void finish(int docCount) throws IOException {+ if (datOut != null)+ datOut.close();+ if (idxOut != null)+ idxOut.close();+ if (pool != null)+ pool.reset();+ }++ @Override+ protected void add(int docID) throws IOException {+ add(docID, bytesRef);+ }+- @Override- protected void setNextAttribute(ValuesAttribute attr) {- bytesRef = attr.bytes();- assert bytesRef != null;- }++ @Override- public void add(int docID, ValuesAttribute attr) throws IOException {++ public void add(int docID, PerDocFieldValues docValues) throws IOException {+ final BytesRef ref;- if ((ref = attr.bytes()) != null) {++ if ((ref = docValues.getBytes()) != null) {+ add(docID, ref);+ }+ }++++ @Override++ protected void setNextEnum(ValuesEnum valuesEnum) {++ bytesRef = valuesEnum.bytes();++ }++ @Override+ public void files(Collection<String> files) throws IOException {+ assert datOut != null;+ files.add(IndexFileNames.segmentFileName(id, "", DATA_EXTENSION));+ if (idxOut != null) { // called after flush - so this must be initialized+ // if needed or present+ final String idxFile = IndexFileNames.segmentFileName(id, "",+ INDEX_EXTENSION);+ files.add(idxFile);+ }+ }+ }++ /**+ * Opens all necessary files, but does not read any data in until you call+ * {@link #load}.+ */+ static abstract class BytesReaderBase extends DocValues {+ protected final IndexInput idxIn;+ protected final IndexInput datIn;+ protected final int version;+ protected final String id;++ protected BytesReaderBase(Directory dir, String id, String codecName,+ int maxVersion, boolean doIndex) throws IOException {+ this.id = id;+ datIn = dir.openInput(IndexFileNames.segmentFileName(id, "",+ Writer.DATA_EXTENSION));+ version = CodecUtil.checkHeader(datIn, codecName, maxVersion, maxVersion);++ if (doIndex) {+ idxIn = dir.openInput(IndexFileNames.segmentFileName(id, "",+ Writer.INDEX_EXTENSION));+ final int version2 = CodecUtil.checkHeader(idxIn, codecName,+ maxVersion, maxVersion);+ assert version == version2;+ } else {+ idxIn = null;+ }++ }++ protected final IndexInput cloneData() {+ assert datIn != null;+ return (IndexInput) datIn.clone();+ }++ protected final IndexInput cloneIndex() { // TODO assert here for null+ // rather than return null+ return idxIn == null ? null : (IndexInput) idxIn.clone();+ }++ @Override+ public void close() throws IOException {+ super.close();+ if (datIn != null) {+ datIn.close();+ }+ if (idxIn != null) {+ idxIn.close();+ }+ }+ }++}diff --cc lucene/src/java/org/apache/lucene/index/values/DocValues.javaindex d734d5e7b0b,00000000000..39d21ac4398mode 100644,000000..100644--- a/lucene/src/java/org/apache/lucene/index/values/DocValues.java+++ b/lucene/src/java/org/apache/lucene/index/values/DocValues.java@@@ -1,184 -1,0 +1,186 @@@+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.Comparator;++import org.apache.lucene.util.AttributeSource;+import org.apache.lucene.util.BytesRef;-++/**++ *++ * @lucene.experimental++ */+public abstract class DocValues implements Closeable {++ public static final DocValues[] EMPTY_ARRAY = new DocValues[0];+ private SourceCache cache = new SourceCache.DirectSourceCache();++ public ValuesEnum getEnum() throws IOException {+ return getEnum(null);+ }++ public abstract ValuesEnum getEnum(AttributeSource attrSource)+ throws IOException;++ public abstract Source load() throws IOException;++ public Source getSource() throws IOException {+ return cache.load(this);+ }++ public SortedSource getSortedSorted(Comparator<BytesRef> comparator)+ throws IOException {+ return cache.laodSorted(this, comparator);+ }++ public SortedSource loadSorted(Comparator<BytesRef> comparator)+ throws IOException {+ throw new UnsupportedOperationException();+ }++ public abstract Values type();++ public void close() throws IOException {+ this.cache.close(this);+ }++ public void setCache(SourceCache cache) {+ synchronized (this.cache) {+ this.cache.close(this);+ this.cache = cache;+ }+ }++ /**+ * Source of integer (returned as java long), per document. The underlying+ * implementation may use different numbers of bits per value; long is only+ * used since it can handle all precisions.+ */+ public static abstract class Source {+ protected final MissingValue missingValue = new MissingValue();++ public long getInt(int docID) {+ throw new UnsupportedOperationException("ints are not supported");+ }++ public double getFloat(int docID) {+ throw new UnsupportedOperationException("floats are not supported");+ }++ public BytesRef getBytes(int docID, BytesRef ref) {+ throw new UnsupportedOperationException("bytes are not supported");+ }++ /**+ * Returns number of unique values. Some impls may throw+ * UnsupportedOperationException.+ */+ public int getValueCount() {+ throw new UnsupportedOperationException();+ }++ public ValuesEnum getEnum() throws IOException {- return getEnum(new AttributeSource());++ return getEnum(null);+ }++ public MissingValue getMissing() {+ return missingValue;+ }++ public abstract Values type();++ public abstract ValuesEnum getEnum(AttributeSource attrSource)+ throws IOException;++ }++ abstract static class SourceEnum extends ValuesEnum {+ protected final Source source;+ protected final int numDocs;+ protected int pos = -1;++ SourceEnum(AttributeSource attrs, Values type, Source source, int numDocs) {+ super(attrs, type);-+ this.source = source;+ this.numDocs = numDocs;+ }++ @Override+ public void close() throws IOException {+ }++ @Override+ public int docID() {+ return pos;+ }++ @Override+ public int nextDoc() throws IOException {+ if(pos == NO_MORE_DOCS)+ return NO_MORE_DOCS;+ return advance(pos + 1);+ }+ }++ public static abstract class SortedSource extends Source {++ @Override+ public BytesRef getBytes(int docID, BytesRef bytesRef) {+ return getByOrd(ord(docID), bytesRef);+ }++ /**+ * Returns ord for specified docID. If this docID had not been added to the+ * Writer, the ord is 0. Ord is dense, ie, starts at 0, then increments by 1+ * for the next (as defined by {@link Comparator} value.+ */+ public abstract int ord(int docID);++ /** Returns value for specified ord. */+ public abstract BytesRef getByOrd(int ord, BytesRef bytesRef);++ public static class LookupResult {+ public boolean found;+ public int ord;+ }++ /**+ * Finds the largest ord whose value is <= the requested value. If+ * {@link LookupResult#found} is true, then ord is an exact match. The+ * returned {@link LookupResult} may be reused across calls.+ */+ public final LookupResult getByValue(BytesRef value) {+ return getByValue(value, new BytesRef());+ }+ public abstract LookupResult getByValue(BytesRef value, BytesRef tmpRef);+ }++ public final static class MissingValue {+ public long longValue;+ public double doubleValue;+ public BytesRef bytesValue;++ public final void copy(MissingValue values) {+ longValue = values.longValue;+ doubleValue = values.doubleValue;+ bytesValue = values.bytesValue;+ }+ }++}diff --cc lucene/src/java/org/apache/lucene/index/values/FixedDerefBytesImpl.javaindex f5df15dd7d6,00000000000..c987ca37816mode 100644,000000..100644--- a/lucene/src/java/org/apache/lucene/index/values/FixedDerefBytesImpl.java+++ b/lucene/src/java/org/apache/lucene/index/values/FixedDerefBytesImpl.java@@@ -1,268 -1,0 +1,278 @@@+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.IOException;+import java.util.concurrent.atomic.AtomicLong;++import org.apache.lucene.index.values.Bytes.BytesBaseSource;+import org.apache.lucene.index.values.Bytes.BytesReaderBase;+import org.apache.lucene.index.values.Bytes.BytesWriterBase;+import org.apache.lucene.store.Directory;+import org.apache.lucene.store.IndexInput;+import org.apache.lucene.util.ArrayUtil;+import org.apache.lucene.util.AttributeSource;+import org.apache.lucene.util.ByteBlockPool;+import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.BytesRefHash;+import org.apache.lucene.util.PagedBytes;+import org.apache.lucene.util.RamUsageEstimator;+import org.apache.lucene.util.ByteBlockPool.Allocator;+import org.apache.lucene.util.ByteBlockPool.DirectAllocator;+import org.apache.lucene.util.BytesRefHash.TrackingDirectBytesStartArray;+import org.apache.lucene.util.packed.PackedInts;++// Stores fixed-length byte[] by deref, ie when two docs+// have the same value, they store only 1 byte[]-++/**++ * @lucene.experimental++ */+class FixedDerefBytesImpl {++ static final String CODEC_NAME = "FixedDerefBytes";+ static final int VERSION_START = 0;+ static final int VERSION_CURRENT = VERSION_START;++ static class Writer extends BytesWriterBase {+ private int size = -1;+ private int[] docToID;+ private final BytesRefHash hash = new BytesRefHash(pool, BytesRefHash.DEFAULT_CAPACITY,+ new TrackingDirectBytesStartArray(BytesRefHash.DEFAULT_CAPACITY, bytesUsed));++ public Writer(Directory dir, String id, AtomicLong bytesUsed) throws IOException {+ this(dir, id, new DirectAllocator(ByteBlockPool.BYTE_BLOCK_SIZE),+ bytesUsed);+ }++ public Writer(Directory dir, String id, Allocator allocator,+ AtomicLong bytesUsed) throws IOException {+ super(dir, id, CODEC_NAME, VERSION_CURRENT, false, false,+ new ByteBlockPool(allocator), bytesUsed);+ docToID = new int[1];+ bytesUsed.addAndGet(RamUsageEstimator.NUM_BYTES_INT); // TODO BytesRefHash uses bytes too!+ }++ @Override+ synchronized public void add(int docID, BytesRef bytes) throws IOException {+ if (bytes.length == 0) // default value - skip it+ return;+ if (size == -1) {+ size = bytes.length;+ initDataOut();+ datOut.writeInt(size);+ } else if (bytes.length != size) {+ throw new IllegalArgumentException("expected bytes size=" + size+ + " but got " + bytes.length);+ }+ int ord = hash.add(bytes);++ if (ord >= 0) {+ // new added entry+ datOut.writeBytes(bytes.bytes, bytes.offset, bytes.length);+ } else {+ ord = (-ord) - 1;+ }++ if (docID >= docToID.length) {+ final int size = docToID.length;+ docToID = ArrayUtil.grow(docToID, 1 + docID);+ bytesUsed.addAndGet((docToID.length - size)+ * RamUsageEstimator.NUM_BYTES_INT);+ }+ docToID[docID] = 1 + ord;+ }++ // Important that we get docCount, in case there were+ // some last docs that we didn't see+ @Override+ synchronized public void finish(int docCount) throws IOException {+ if (datOut == null) // no added data+ return;+ initIndexOut();+ final int count = 1 + hash.size();+ idxOut.writeInt(count - 1);+ // write index+ final PackedInts.Writer w = PackedInts.getWriter(idxOut, docCount,+ PackedInts.bitsRequired(count - 1));+ final int limit = docCount > docToID.length ? docToID.length : docCount;+ for (int i = 0; i < limit; i++) {+ w.add(docToID[i]);+ }+ // fill up remaining doc with zeros+ for (int i = limit; i < docCount; i++) {+ w.add(0);+ }+ w.finish();+ hash.close();+ super.finish(docCount);+ bytesUsed.addAndGet((-docToID.length)+ * RamUsageEstimator.NUM_BYTES_INT);+ docToID = null;+ }+ }++ public static class Reader extends BytesReaderBase {+ private final int size;++ Reader(Directory dir, String id, int maxDoc) throws IOException {+ super(dir, id, CODEC_NAME, VERSION_START, true);+ try {+ size = datIn.readInt();+ } catch (IOException e) {+ throw e;+ }+ }++ @Override+ public Source load() throws IOException {+ final IndexInput index = cloneIndex();+ return new Source(cloneData(), index, size, index.readInt());+ }++ private static class Source extends BytesBaseSource {+ private final PackedInts.Reader index;+ private final int size;+ private final int numValues;++ protected Source(IndexInput datIn, IndexInput idxIn, int size,+ int numValues) throws IOException {+ super(datIn, idxIn, new PagedBytes(PAGED_BYTES_BITS), size * numValues);+ this.size = size;+ this.numValues = numValues;+ index = PackedInts.getReader(idxIn);+ }++ @Override+ public BytesRef getBytes(int docID, BytesRef bytesRef) {+ final int id = (int) index.get(docID);+ if (id == 0) {+ return null;+ }- return data.fill(bytesRef, ((id - 1) * size), size);++ return data.fillSlice(bytesRef, ((id - 1) * size), size);+ }++ @Override+ public int getValueCount() {+ return numValues;+ }++ @Override+ public Values type() {+ return Values.BYTES_FIXED_DEREF;+ }++ @Override+ protected int maxDoc() {+ return index.size();+ }+ }++ @Override+ public ValuesEnum getEnum(AttributeSource source) throws IOException {+ return new DerefBytesEnum(source, cloneData(), cloneIndex(),+ size);+ }++ static class DerefBytesEnum extends ValuesEnum {+ protected final IndexInput datIn;+ private final PackedInts.ReaderIterator idx;+ protected final long fp;+ private final int size;- protected final BytesRef ref;+ private final int valueCount;+ private int pos = -1;++ public DerefBytesEnum(AttributeSource source, IndexInput datIn,+ IndexInput idxIn, int size) throws IOException {+ this(source, datIn, idxIn, size, Values.BYTES_FIXED_DEREF);+ }++ protected DerefBytesEnum(AttributeSource source, IndexInput datIn,+ IndexInput idxIn, int size, Values enumType)+ throws IOException {+ super(source, enumType);- ref = attr.bytes();+ this.datIn = datIn;- this.size = size == -1 ? 128 : size;++ this.size = size;+ idxIn.readInt();// read valueCount+ idx = PackedInts.getReaderIterator(idxIn);+ fp = datIn.getFilePointer();- ref.grow(this.size);- ref.length = this.size;- ref.offset = 0;++ bytesRef.grow(this.size);++ bytesRef.length = this.size;++ bytesRef.offset = 0;+ valueCount = idx.size();+ }++++++ protected void copyReferences(ValuesEnum valuesEnum) {++ bytesRef = valuesEnum.bytesRef;++ if(bytesRef.bytes.length < size) {++ bytesRef.grow(size);++ }++ bytesRef.length = size;++ bytesRef.offset = 0;++ }++ @Override+ public int advance(int target) throws IOException {+ if (target < valueCount) {+ long address;+ while ((address = idx.advance(target)) == 0) {+ if (++target >= valueCount) {+ return pos = NO_MORE_DOCS;+ }+ }+ pos = idx.ord();- fill(address, ref);++ fill(address, bytesRef);+ return pos;+ }+ return pos = NO_MORE_DOCS;+ }++ @Override+ public int nextDoc() throws IOException {+ if (pos < valueCount) {+ return pos = NO_MORE_DOCS;+ }+ return advance(pos + 1);+ }++ public void close() throws IOException {+ datIn.close();+ idx.close();+ }++ protected void fill(long address, BytesRef ref) throws IOException {+ datIn.seek(fp + ((address - 1) * size));+ datIn.readBytes(ref.bytes, 0, size);+ ref.length = size;+ ref.offset = 0;+ }++ @Override+ public int docID() {+ return pos;+ }++ }++ @Override+ public Values type() {+ return Values.BYTES_FIXED_DEREF;+ }+ }++}diff --cc lucene/src/java/org/apache/lucene/index/values/FixedSortedBytesImpl.javaindex f19ac893f49,00000000000..adf1c2167c2mode 100644,000000..100644--- a/lucene/src/java/org/apache/lucene/index/values/FixedSortedBytesImpl.java+++ b/lucene/src/java/org/apache/lucene/index/values/FixedSortedBytesImpl.java@@@ -1,237 -1,0 +1,240 @@@+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.IOException;+import java.util.Comparator;+import java.util.concurrent.atomic.AtomicLong;++import org.apache.lucene.index.values.Bytes.BytesBaseSortedSource;+import org.apache.lucene.index.values.Bytes.BytesReaderBase;+import org.apache.lucene.index.values.Bytes.BytesWriterBase;+import org.apache.lucene.index.values.FixedDerefBytesImpl.Reader.DerefBytesEnum;+import org.apache.lucene.store.Directory;+import org.apache.lucene.store.IndexInput;+import org.apache.lucene.util.ArrayUtil;+import org.apache.lucene.util.AttributeSource;+import org.apache.lucene.util.ByteBlockPool;+import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.BytesRefHash;+import org.apache.lucene.util.CodecUtil;+import org.apache.lucene.util.PagedBytes;+import org.apache.lucene.util.RamUsageEstimator;+import org.apache.lucene.util.ByteBlockPool.Allocator;+import org.apache.lucene.util.ByteBlockPool.DirectAllocator;+import org.apache.lucene.util.BytesRefHash.TrackingDirectBytesStartArray;+import org.apache.lucene.util.packed.PackedInts;++// Stores fixed-length byte[] by deref, ie when two docs+// have the same value, they store only 1 byte[]+++/**++ * @lucene.experimental++ */+class FixedSortedBytesImpl {++ static final String CODEC_NAME = "FixedSortedBytes";+ static final int VERSION_START = 0;+ static final int VERSION_CURRENT = VERSION_START;++ static class Writer extends BytesWriterBase {+ private int size = -1;+ private int[] docToEntry;+ private final Comparator<BytesRef> comp;++ private final BytesRefHash hash = new BytesRefHash(pool, BytesRefHash.DEFAULT_CAPACITY,+ new TrackingDirectBytesStartArray(BytesRefHash.DEFAULT_CAPACITY, bytesUsed));++ public Writer(Directory dir, String id, Comparator<BytesRef> comp, AtomicLong bytesUsed)+ throws IOException {+ this(dir, id, comp, new DirectAllocator(ByteBlockPool.BYTE_BLOCK_SIZE),+ bytesUsed);+ }++ public Writer(Directory dir, String id, Comparator<BytesRef> comp,+ Allocator allocator, AtomicLong bytesUsed) throws IOException {+ super(dir, id, CODEC_NAME, VERSION_CURRENT, false, false,+ new ByteBlockPool(allocator), bytesUsed);+ docToEntry = new int[1];+ // docToEntry[0] = -1;+ bytesUsed.addAndGet(RamUsageEstimator.NUM_BYTES_INT);+ this.comp = comp;+ }++ @Override+ synchronized public void add(int docID, BytesRef bytes) throws IOException {+ if (bytes.length == 0)+ return; // default - skip it+ if (size == -1) {+ size = bytes.length;+ initDataOut();+ datOut.writeInt(size);+ } else if (bytes.length != size) {+ throw new IllegalArgumentException("expected bytes size=" + size+ + " but got " + bytes.length);+ }+ if (docID >= docToEntry.length) {+ int[] newArray = new int[ArrayUtil.oversize(1 + docID,+ RamUsageEstimator.NUM_BYTES_INT)];+ System.arraycopy(docToEntry, 0, newArray, 0, docToEntry.length);+ // Arrays.fill(newArray, docToEntry.length, newArray.length, -1);++ bytesUsed.addAndGet((newArray.length - docToEntry.length)+ * RamUsageEstimator.NUM_BYTES_INT);+ docToEntry = newArray;+ }+ int e = hash.add(bytes);+ docToEntry[docID] = 1 + (e < 0 ? (-e) - 1 : e);+ }++ // Important that we get docCount, in case there were+ // some last docs that we didn't see+ @Override+ synchronized public void finish(int docCount) throws IOException {+ if (datOut == null)// no data added+ return;+ initIndexOut();+ final int[] sortedEntries = hash.sort(comp);+ final int count = hash.size();+ int[] address = new int[count];+ // first dump bytes data, recording address as we go+ for (int i = 0; i < count; i++) {+ final int e = sortedEntries[i];+ final BytesRef bytes = hash.get(e, new BytesRef());+ assert bytes.length == size;+ datOut.writeBytes(bytes.bytes, bytes.offset, bytes.length);+ address[e] = 1 + i;+ }++ idxOut.writeInt(count);++ // next write index+ PackedInts.Writer w = PackedInts.getWriter(idxOut, docCount, PackedInts+ .bitsRequired(count));+ final int limit;+ if (docCount > docToEntry.length) {+ limit = docToEntry.length;+ } else {+ limit = docCount;+ }+ for (int i = 0; i < limit; i++) {+ final int e = docToEntry[i];+ if (e == 0) {+ // null is encoded as zero+ w.add(0);+ } else {+ assert e > 0 && e <= count : "index must 0 > && <= " + count+ + " was: " + e;+ w.add(address[e - 1]);+ }+ }++ for (int i = limit; i < docCount; i++) {+ w.add(0);+ }+ w.finish();++ super.finish(docCount);+ bytesUsed.addAndGet((-docToEntry.length)+ * RamUsageEstimator.NUM_BYTES_INT);+ docToEntry = null;+ hash.close();+ }+ }++ public static class Reader extends BytesReaderBase {+ private final int size;++ public Reader(Directory dir, String id, int maxDoc) throws IOException {+ super(dir, id, CODEC_NAME, VERSION_START, true);+ size = datIn.readInt();+ }++ @Override+ public org.apache.lucene.index.values.DocValues.Source load()+ throws IOException {+ return loadSorted(null);+ }++ @Override+ public SortedSource loadSorted(Comparator<BytesRef> comp)+ throws IOException {+ final IndexInput idxInput = cloneIndex();+ final IndexInput datInput = cloneData();+ datInput.seek(CodecUtil.headerLength(CODEC_NAME) + 4);+ idxInput.seek(CodecUtil.headerLength(CODEC_NAME));+ return new Source(datInput, idxInput, size, idxInput.readInt(), comp);+ }++ private static class Source extends BytesBaseSortedSource {++ private final PackedInts.Reader index;+ private final int numValue;+ private final int size;++ public Source(IndexInput datIn, IndexInput idxIn, int size, int numValues,+ Comparator<BytesRef> comp) throws IOException {+ super(datIn, idxIn, comp, new PagedBytes(PAGED_BYTES_BITS), size*numValues );+ this.size = size;+ this.numValue = numValues;+ index = PackedInts.getReader(idxIn);+ }++ @Override+ public int ord(int docID) {+ return (int) index.get(docID);+ }++ @Override+ public LookupResult getByValue(BytesRef bytes, BytesRef tmpRef) {+ return binarySearch(bytes, tmpRef, 0, numValue - 1);+ }++ @Override+ public int getValueCount() {+ return numValue;+ }+ @Override+ protected BytesRef deref(int ord, BytesRef bytesRef) {- return data.fill(bytesRef, (ord* size), size);++ return data.fillSlice(bytesRef, (ord* size), size);+ }++ @Override+ public Values type() {+ return Values.BYTES_FIXED_SORTED;+ }++ @Override+ protected int maxDoc() {+ return index.size();+ }+ }++ @Override+ public ValuesEnum getEnum(AttributeSource source) throws IOException {+ // do unsorted+ return new DerefBytesEnum(source, cloneData(), cloneIndex(),+ size);+ }++ @Override+ public Values type() {+ return Values.BYTES_FIXED_SORTED;+ }+ }+}diff --cc lucene/src/java/org/apache/lucene/index/values/FixedStraightBytesImpl.javaindex ef760835b64,00000000000..9f8047304camode 100644,000000..100644--- a/lucene/src/java/org/apache/lucene/index/values/FixedStraightBytesImpl.java+++ b/lucene/src/java/org/apache/lucene/index/values/FixedStraightBytesImpl.java@@@ -1,226 -1,0 +1,235 @@@+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.IOException;++import org.apache.lucene.index.values.Bytes.BytesBaseSource;+import org.apache.lucene.index.values.Bytes.BytesReaderBase;+import org.apache.lucene.index.values.Bytes.BytesWriterBase;+import org.apache.lucene.store.Directory;+import org.apache.lucene.store.IndexInput;+import org.apache.lucene.util.AttributeSource;+import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.PagedBytes;++// Simplest storage: stores fixed length byte[] per+// document, with no dedup and no sorting.-++/**++ * @lucene.experimental++ */+class FixedStraightBytesImpl {++ static final String CODEC_NAME = "FixedStraightBytes";+ static final int VERSION_START = 0;+ static final int VERSION_CURRENT = VERSION_START;++ static class Writer extends BytesWriterBase {+ private int size = -1;+ // start at -1 if the first added value is > 0+ private int lastDocID = -1;+ private byte[] oneRecord;++ protected Writer(Directory dir, String id) throws IOException {+ super(dir, id, CODEC_NAME, VERSION_CURRENT, false, false, null, null);+ }++ // TODO - impl bulk copy here!++ @Override+ synchronized public void add(int docID, BytesRef bytes) throws IOException {+ if (size == -1) {+ size = bytes.length;+ initDataOut();+ datOut.writeInt(size);+ oneRecord = new byte[size];+ } else if (bytes.length != size) {+ throw new IllegalArgumentException("expected bytes size=" + size + " but got " + bytes.length);+ }+ fill(docID);+ assert bytes.bytes.length >= bytes.length;+ datOut.writeBytes(bytes.bytes, bytes.offset, bytes.length);+ }++ /* (non-Javadoc)+ * @see org.apache.lucene.index.values.Writer#merge(org.apache.lucene.index.values.Writer.MergeState)+ */+ @Override+ protected void merge(MergeState state) throws IOException {+ if(state.bits == null && state.reader instanceof Reader){+ Reader reader = (Reader) state.reader;+ final int maxDocs = reader.maxDoc;+ if(maxDocs == 0)+ return;+ if(size == -1) {+ size = reader.size;+ initDataOut();+ datOut.writeInt(size);+ oneRecord = new byte[size];+ }+ fill(state.docBase);+ // TODO should we add a transfer to API to each reader?+ datOut.copyBytes(reader.cloneData(), size * maxDocs);+ lastDocID += maxDocs-1;+ } else+ super.merge(state);+ }++ // Fills up to but not including this docID+ private void fill(int docID) throws IOException {+ assert size >= 0;+ for(int i=lastDocID+1;i<docID;i++) {+ datOut.writeBytes(oneRecord, size);+ }+ lastDocID = docID;+ }++ @Override+ synchronized public void finish(int docCount) throws IOException {+ if(datOut == null) // no data added+ return;+ fill(docCount);+ super.finish(docCount);+ }++ public long ramBytesUsed() {+ return 0;+ }++ }++ public static class Reader extends BytesReaderBase {+ private final int size;+ private final int maxDoc;++ Reader(Directory dir, String id, int maxDoc)+ throws IOException {+ super(dir, id, CODEC_NAME, VERSION_START, false);+ size = datIn.readInt();+ this.maxDoc = maxDoc;+ }++ @Override+ public Source load() throws IOException {+ return new Source(cloneData(), cloneIndex(), size, maxDoc);+ }++ @Override+ public void close() throws IOException {+ datIn.close();+ }++ private static class Source extends BytesBaseSource {+ private final int size;+ private final int maxDoc;++ public Source(IndexInput datIn, IndexInput idxIn, int size, int maxDoc) throws IOException {+ super(datIn, idxIn, new PagedBytes(PAGED_BYTES_BITS), size*maxDoc);+ this.size = size;+ this.missingValue.bytesValue = new BytesRef(size);+ this.maxDoc = maxDoc;+ }++ @Override+ public BytesRef getBytes(int docID, BytesRef bytesRef) {- return data.fill(bytesRef, docID * size, size);++ return data.fillSlice(bytesRef, docID * size, size);+ }++ @Override+ public int getValueCount() {+ throw new UnsupportedOperationException();+ }++ @Override+ public Values type() {+ return Values.BYTES_FIXED_STRAIGHT;+ }++ @Override+ protected int maxDoc() {+ return maxDoc;+ }+ }++ @Override+ public ValuesEnum getEnum(AttributeSource source) throws IOException {+ return new FixedStraightBytesEnum(source, cloneData(), size, maxDoc);+ }++ private static final class FixedStraightBytesEnum extends ValuesEnum {+ private final IndexInput datIn;+ private final int size;+ private final int maxDoc;+ private int pos = -1;+ private final long fp;- private final BytesRef ref;++ public FixedStraightBytesEnum(AttributeSource source, IndexInput datIn, int size, int maxDoc) throws IOException{+ super(source, Values.BYTES_FIXED_STRAIGHT);+ this.datIn = datIn;+ this.size = size;+ this.maxDoc = maxDoc;- ref = attr.bytes();- ref.grow(size);- ref.length = size;- ref.offset = 0;++ bytesRef.grow(size);++ bytesRef.length = size;++ bytesRef.offset = 0;+ fp = datIn.getFilePointer();+ }++++ protected void copyReferences(ValuesEnum valuesEnum) {++ bytesRef = valuesEnum.bytesRef;++ if(bytesRef.bytes.length < size) {++ bytesRef.grow(size);++ }++ bytesRef.length = size;++ bytesRef.offset = 0;++ }++ public void close() throws IOException {+ datIn.close();+ }++ @Override+ public int advance(int target) throws IOException {+ if(target >= maxDoc){+ return pos = NO_MORE_DOCS;+ }+ if((target-1) != pos) // pos inc == 1+ datIn.seek(fp + target * size);- datIn.readBytes(ref.bytes, 0, size);++ datIn.readBytes(bytesRef.bytes, 0, size);+ return pos = target;+ }++ @Override+ public int docID() {+ return pos;+ }++ @Override+ public int nextDoc() throws IOException {+ if(pos >= maxDoc){+ return pos = NO_MORE_DOCS;+ }+ return advance(pos+1);+ }+ }++ @Override+ public Values type() {+ return Values.BYTES_FIXED_STRAIGHT;+ }+ }+}diff --cc lucene/src/java/org/apache/lucene/index/values/Floats.javaindex f53345c9c3d,00000000000..d2d3fe6a500mode 100644,000000..100644--- a/lucene/src/java/org/apache/lucene/index/values/Floats.java+++ b/lucene/src/java/org/apache/lucene/index/values/Floats.java@@@ -1,489 -1,0 +1,473 @@@+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.IOException;+import java.nio.ByteBuffer;+import java.nio.DoubleBuffer;+import java.nio.FloatBuffer;+import java.util.Collection;+import java.util.concurrent.atomic.AtomicLong;++import org.apache.lucene.index.IndexFileNames;+import org.apache.lucene.store.Directory;+import org.apache.lucene.store.IndexInput;+import org.apache.lucene.store.IndexOutput;+import org.apache.lucene.util.AttributeSource;+import org.apache.lucene.util.CodecUtil;+import org.apache.lucene.util.FloatsRef;- import org.apache.lucene.util.RamUsageEstimator;++/**+ * Exposes writer/reader for floating point values. You can specify 4 (java+ * float) or 8 (java double) byte precision.++ * @lucene.experimental+ */+// TODO - add bulk copy where possible+public class Floats {+ private static final String CODEC_NAME = "SimpleFloats";+ static final int VERSION_START = 0;+ static final int VERSION_CURRENT = VERSION_START;+ private static final int INT_DEFAULT = Float+ .floatToRawIntBits(Float.NEGATIVE_INFINITY);+ private static final long LONG_DEFAULT = Double+ .doubleToRawLongBits(Double.NEGATIVE_INFINITY);++ public static Writer getWriter(Directory dir, String id, int precisionBytes, AtomicLong bytesUsed)+ throws IOException {+ if (precisionBytes != 4 && precisionBytes != 8) {+ throw new IllegalArgumentException("precisionBytes must be 4 or 8; got "+ + precisionBytes);+ }+ if (precisionBytes == 4) {+ return new Float4Writer(dir, id, bytesUsed);+ } else {+ return new Float8Writer(dir, id, bytesUsed);+ }+ }++ public static DocValues getValues(Directory dir, String id, int maxDoc)+ throws IOException {+ return new FloatsReader(dir, id, maxDoc);+ }++ abstract static class FloatsWriter extends Writer {+ private final Directory dir;+ private final String id;+ private FloatsRef floatsRef;+ protected int lastDocId = -1;+ protected IndexOutput datOut;+ private final byte precision;++ protected FloatsWriter(Directory dir, String id, int precision, AtomicLong bytesUsed)+ throws IOException {+ super(bytesUsed);+ this.dir = dir;+ this.id = id;+ this.precision = (byte) precision;+ }++ protected void initDatOut() throws IOException {+ datOut = dir.createOutput(IndexFileNames.segmentFileName(id, "",+ Writer.DATA_EXTENSION));+ CodecUtil.writeHeader(datOut, CODEC_NAME, VERSION_CURRENT);+ assert datOut.getFilePointer() == CodecUtil.headerLength(CODEC_NAME);+ datOut.writeByte(precision);+ }++ public long ramBytesUsed() {+ return 0;+ }++ @Override+ protected void add(int docID) throws IOException {+ add(docID, floatsRef.get());+ }++ @Override- public void add(int docID, ValuesAttribute attr) throws IOException {- final FloatsRef ref;- if ((ref = attr.floats()) != null)- add(docID, ref.get());++ public void add(int docID, PerDocFieldValues docValues) throws IOException {++ add(docID, docValues.getFloat());+ }++ @Override- protected void setNextAttribute(ValuesAttribute attr) {- floatsRef = attr.floats();++ protected void setNextEnum(ValuesEnum valuesEnum) {++ floatsRef = valuesEnum.getFloat();+ }++ protected abstract int fillDefault(int num) throws IOException;++ @Override+ protected void merge(MergeState state) throws IOException {+ if (state.bits == null && state.reader instanceof FloatsReader) {+ // no deletes - bulk copy+ // TODO: should be do bulks with deletes too?+ final FloatsReader reader = (FloatsReader) state.reader;+ assert reader.precisionBytes == (int) precision;+ if (reader.maxDoc == 0)+ return;+ if (datOut == null)+ initDatOut();+ final int docBase = state.docBase;+ if (docBase - lastDocId > 1) {+ // fill with default values+ lastDocId += fillDefault(docBase - lastDocId - 1);+ }+ lastDocId += reader.transferTo(datOut);+ } else+ super.merge(state);+ }++ @Override+ public void files(Collection<String> files) throws IOException {+ files.add(IndexFileNames.segmentFileName(id, "", Writer.DATA_EXTENSION));+ }++ }++ // Writes 4 bytes (float) per value+ static class Float4Writer extends FloatsWriter {++ protected Float4Writer(Directory dir, String id, AtomicLong bytesUsed) throws IOException {+ super(dir, id, 4, bytesUsed);+ }++ @Override+ synchronized public void add(final int docID, final double v)+ throws IOException {+ assert docID > lastDocId : "docID: " + docID+ + " must be greater than the last added doc id: " + lastDocId;+ if (datOut == null) {+ initDatOut();+ }+ if (docID - lastDocId > 1) {+ // fill with default values+ lastDocId += fillDefault(docID - lastDocId - 1);+ }+ assert datOut != null;+ datOut.writeInt(Float.floatToRawIntBits((float) v));+ ++lastDocId;+ }++ @Override+ synchronized public void finish(int docCount) throws IOException {+ if (datOut == null)+ return; // no data added - don't create file!+ if (docCount > lastDocId + 1)+ for (int i = lastDocId; i < docCount; i++) {+ datOut.writeInt(INT_DEFAULT); // default value+ }+ datOut.close();+ }++ @Override+ protected int fillDefault(int numValues) throws IOException {+ for (int i = 0; i < numValues; i++) {+ datOut.writeInt(INT_DEFAULT);+ }+ return numValues;+ }+ }++ // Writes 8 bytes (double) per value+ static class Float8Writer extends FloatsWriter {++ protected Float8Writer(Directory dir, String id, AtomicLong bytesUsed) throws IOException {+ super(dir, id, 8, bytesUsed);+ }++ @Override+ synchronized public void add(int docID, double v) throws IOException {+ assert docID > lastDocId : "docID: " + docID+ + " must be greater than the last added doc id: " + lastDocId;+ if (datOut == null) {+ initDatOut();+ }+ if (docID - lastDocId > 1) {+ // fill with default values+ lastDocId += fillDefault(docID - lastDocId - 1);+ }+ assert datOut != null;+ datOut.writeLong(Double.doubleToRawLongBits(v));+ ++lastDocId;+ }++ @Override+ synchronized public void finish(int docCount) throws IOException {+ if (datOut == null)+ return; // no data added - don't create file!+ if (docCount > lastDocId + 1)+ for (int i = lastDocId; i < docCount; i++) {+ datOut.writeLong(LONG_DEFAULT); // default value+ }+ datOut.close();+ }++ @Override+ protected int fillDefault(int numValues) throws IOException {+ for (int i = 0; i < numValues; i++) {+ datOut.writeLong(LONG_DEFAULT);+ }+ return numValues;+ }+ }++ /**+ * Opens all necessary files, but does not read any data in until you call+ * {@link #load}.+ */+ static class FloatsReader extends DocValues {++ private final IndexInput datIn;+ private final int precisionBytes;+ // TODO(simonw) is ByteBuffer the way to go here?+ private final int maxDoc;++ protected FloatsReader(Directory dir, String id, int maxDoc)+ throws IOException {+ datIn = dir.openInput(IndexFileNames.segmentFileName(id, "",+ Writer.DATA_EXTENSION));+ CodecUtil.checkHeader(datIn, CODEC_NAME, VERSION_START, VERSION_START);+ precisionBytes = datIn.readByte();+ assert precisionBytes == 4 || precisionBytes == 8;+ this.maxDoc = maxDoc;+ }++ int transferTo(IndexOutput out) throws IOException {+ IndexInput indexInput = (IndexInput) datIn.clone();+ try {+ indexInput.seek(CodecUtil.headerLength(CODEC_NAME));+ // skip precision:+ indexInput.readByte();+ out.copyBytes(indexInput, precisionBytes * maxDoc);+ } finally {+ indexInput.close();+ }+ return maxDoc;+ }++ /**+ * Loads the actual values. You may call this more than once, eg if you+ * already previously loaded but then discarded the Source.+ */+ @Override+ public Source load() throws IOException {+ ByteBuffer buffer = ByteBuffer.allocate(precisionBytes * maxDoc);+ IndexInput indexInput = (IndexInput) datIn.clone();+ indexInput.seek(CodecUtil.headerLength(CODEC_NAME));+ // skip precision:+ indexInput.readByte();+ assert buffer.hasArray() : "Buffer must support Array";+ final byte[] arr = buffer.array();+ indexInput.readBytes(arr, 0, arr.length);+ return precisionBytes == 4 ? new Source4(buffer) : new Source8(buffer);+ }++ private class Source4 extends Source {+ private final FloatBuffer values;++ Source4(ByteBuffer buffer) {+ values = buffer.asFloatBuffer();+ missingValue.doubleValue = Float.NEGATIVE_INFINITY;+ }++ @Override+ public double getFloat(int docID) {+ return values.get(docID);+ }+- public long ramBytesUsed() {- return RamUsageEstimator.NUM_BYTES_ARRAY_HEADER + values.limit()- * RamUsageEstimator.NUM_BYTES_FLOAT;- }-+ @Override+ public ValuesEnum getEnum(AttributeSource attrSource) throws IOException {+ final MissingValue missing = getMissing();+ return new SourceEnum(attrSource, Values.SIMPLE_FLOAT_4BYTE, this, maxDoc) {- private final FloatsRef ref = attr.floats();+ @Override+ public int advance(int target) throws IOException {+ if (target >= numDocs)+ return pos = NO_MORE_DOCS;+ while (missing.doubleValue == source.getFloat(target)) {+ if (++target >= numDocs) {+ return pos = NO_MORE_DOCS;+ }+ }- ref.floats[ref.offset] = source.getFloat(target);++ floatsRef.floats[floatsRef.offset] = source.getFloat(target);+ return pos = target;+ }+ };+ }++ @Override+ public Values type() {+ return Values.SIMPLE_FLOAT_4BYTE;+ }+ }++ private class Source8 extends Source {+ private final DoubleBuffer values;++ Source8(ByteBuffer buffer) {+ values = buffer.asDoubleBuffer();+ missingValue.doubleValue = Double.NEGATIVE_INFINITY;++ }++ @Override+ public double getFloat(int docID) {+ return values.get(docID);+ }+- public long ramBytesUsed() {- return RamUsageEstimator.NUM_BYTES_ARRAY_HEADER + values.limit()- * RamUsageEstimator.NUM_BYTES_DOUBLE;- }-+ @Override+ public ValuesEnum getEnum(AttributeSource attrSource) throws IOException {+ final MissingValue missing = getMissing();+ return new SourceEnum(attrSource, type(), this, maxDoc) {- private final FloatsRef ref = attr.floats();+ @Override+ public int advance(int target) throws IOException {+ if (target >= numDocs)+ return pos = NO_MORE_DOCS;+ while (missing.doubleValue == source.getFloat(target)) {+ if (++target >= numDocs) {+ return pos = NO_MORE_DOCS;+ }+ }- ref.floats[ref.offset] = source.getFloat(target);++ floatsRef.floats[floatsRef.offset] = source.getFloat(target);+ return pos = target;+ }+ };+ }++ @Override+ public Values type() {+ return Values.SIMPLE_FLOAT_8BYTE;+ }+ }++ @Override+ public void close() throws IOException {+ super.close();+ datIn.close();+ }++ @Override+ public ValuesEnum getEnum(AttributeSource source) throws IOException {+ IndexInput indexInput = (IndexInput) datIn.clone();+ indexInput.seek(CodecUtil.headerLength(CODEC_NAME));+ // skip precision:+ indexInput.readByte();+ return precisionBytes == 4 ? new Floats4Enum(source, indexInput, maxDoc)+ : new Floats8EnumImpl(source, indexInput, maxDoc);+ }++ @Override+ public Values type() {+ return precisionBytes == 4 ? Values.SIMPLE_FLOAT_4BYTE+ : Values.SIMPLE_FLOAT_8BYTE;+ }+ }++ static final class Floats4Enum extends FloatsEnumImpl {++ Floats4Enum(AttributeSource source, IndexInput dataIn, int maxDoc)+ throws IOException {+ super(source, dataIn, 4, maxDoc, Values.SIMPLE_FLOAT_4BYTE);+ }++ @Override+ public int advance(int target) throws IOException {+ if (target >= maxDoc)+ return pos = NO_MORE_DOCS;+ dataIn.seek(fp + (target * precision));+ int intBits;+ while ((intBits = dataIn.readInt()) == INT_DEFAULT) {+ if (++target >= maxDoc)+ return pos = NO_MORE_DOCS;+ }- ref.floats[0] = Float.intBitsToFloat(intBits);- ref.offset = 0;++ floatsRef.floats[0] = Float.intBitsToFloat(intBits);++ floatsRef.offset = 0;+ return pos = target;+ }++ @Override+ public int docID() {+ return pos;+ }++ @Override+ public int nextDoc() throws IOException {+ if (pos >= maxDoc) {+ return pos = NO_MORE_DOCS;+ }+ return advance(pos + 1);+ }+ }++ private static final class Floats8EnumImpl extends FloatsEnumImpl {++ Floats8EnumImpl(AttributeSource source, IndexInput dataIn, int maxDoc)+ throws IOException {+ super(source, dataIn, 8, maxDoc, Values.SIMPLE_FLOAT_8BYTE);+ }++ @Override+ public int advance(int target) throws IOException {+ if (target >= maxDoc) {+ return pos = NO_MORE_DOCS;+ }+ dataIn.seek(fp + (target * precision));+ long value;+ while ((value = dataIn.readLong()) == LONG_DEFAULT) {+ if (++target >= maxDoc)+ return pos = NO_MORE_DOCS;+ }- ref.floats[0] = Double.longBitsToDouble(value);- ref.offset = 0;++ floatsRef.floats[0] = Double.longBitsToDouble(value);++ floatsRef.offset = 0;+ return pos = target;+ }++ @Override+ public int docID() {+ return pos;+ }++ @Override+ public int nextDoc() throws IOException {+ if (pos >= maxDoc) {+ return pos = NO_MORE_DOCS;+ }+ return advance(pos + 1);+ }+ }++ static abstract class FloatsEnumImpl extends ValuesEnum {+ protected final IndexInput dataIn;+ protected int pos = -1;+ protected final int precision;+ protected final int maxDoc;+ protected final long fp;- protected final FloatsRef ref;++ FloatsEnumImpl(AttributeSource source, IndexInput dataIn, int precision,+ int maxDoc, Values type) throws IOException {+ super(source, precision == 4 ? Values.SIMPLE_FLOAT_4BYTE+ : Values.SIMPLE_FLOAT_8BYTE);+ this.dataIn = dataIn;+ this.precision = precision;+ this.maxDoc = maxDoc;+ fp = dataIn.getFilePointer();- this.ref = attr.floats();- this.ref.offset = 0;++ floatsRef.offset = 0;+ }++ @Override+ public void close() throws IOException {+ dataIn.close();+ }+ }+}diff --cc lucene/src/java/org/apache/lucene/index/values/Ints.javaindex 7955d7c7753,00000000000..b374b039571mode 100644,000000..100644--- a/lucene/src/java/org/apache/lucene/index/values/Ints.java+++ b/lucene/src/java/org/apache/lucene/index/values/Ints.java@@@ -1,42 -1,0 +1,46 @@@+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.IOException;+import java.util.concurrent.atomic.AtomicLong;++import org.apache.lucene.index.values.PackedIntsImpl.IntsReader;+import org.apache.lucene.index.values.PackedIntsImpl.IntsWriter;+import org.apache.lucene.store.Directory;+- //TODO - add bulk copy where possible++/**++ * @lucene.experimental++ */+public class Ints {++//TODO - add bulk copy where possible++ private Ints() {+ }+- public static Writer getWriter(Directory dir, String id, boolean useFixedArray, AtomicLong bytesUsed)- throws IOException {++ public static Writer getWriter(Directory dir, String id,++ boolean useFixedArray, AtomicLong bytesUsed) throws IOException {+ // TODO - implement fixed?!+ return new IntsWriter(dir, id, bytesUsed);+ }++ public static DocValues getValues(Directory dir, String id,+ boolean useFixedArray) throws IOException {+ return new IntsReader(dir, id);+ }+}diff --cc lucene/src/java/org/apache/lucene/index/values/MultiDocValues.javaindex 0e81c25d725,00000000000..dfd7478a106mode 100644,000000..100644--- a/lucene/src/java/org/apache/lucene/index/values/MultiDocValues.java+++ b/lucene/src/java/org/apache/lucene/index/values/MultiDocValues.java@@@ -1,272 -1,0 +1,274 @@@+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.IOException;+import java.util.Arrays;++import org.apache.lucene.util.AttributeSource;+import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.ReaderUtil;+++/**++ * @lucene.experimental++ */+public class MultiDocValues extends DocValues {++ public static class DocValuesIndex {+ public final static DocValuesIndex[] EMPTY_ARRAY = new DocValuesIndex[0];+ final int start;+ final int length;+ final DocValues docValues;++ public DocValuesIndex(DocValues docValues, int start, int length) {+ this.docValues = docValues;+ this.start = start;+ this.length = length;+ }+ }++ private DocValuesIndex[] docValuesIdx;+ private int[] starts;++ public MultiDocValues() {+ starts = new int[0];+ docValuesIdx = new DocValuesIndex[0];+ }++ public MultiDocValues(DocValuesIndex[] docValuesIdx) {+ reset(docValuesIdx);+ }++ @Override+ public ValuesEnum getEnum(AttributeSource source) throws IOException {+ return new MultiValuesEnum(docValuesIdx, starts);+ }++ @Override+ public Source load() throws IOException {+ return new MultiSource(docValuesIdx, starts);+ }++ public void close() throws IOException {+ super.close();+ }++ public DocValues reset(DocValuesIndex[] docValuesIdx) {+ int[] start = new int[docValuesIdx.length];+ for (int i = 0; i < docValuesIdx.length; i++) {+ start[i] = docValuesIdx[i].start;+ }+ this.starts = start;+ this.docValuesIdx = docValuesIdx;+ return this;+ }++ public static class DummyDocValues extends DocValues {+ final int maxDoc;+ final Source emptySoruce;++ public DummyDocValues(int maxDoc, Values type) {+ this.maxDoc = maxDoc;+ this.emptySoruce = new EmptySource(type);+ }++ @Override+ public ValuesEnum getEnum(AttributeSource attrSource) throws IOException {+ return emptySoruce.getEnum(attrSource);+ }++ @Override+ public Source load() throws IOException {+ return emptySoruce;+ }++ @Override+ public Values type() {+ return emptySoruce.type();+ }++ public void close() throws IOException {+ super.close();+ }++ }++ private static class MultiValuesEnum extends ValuesEnum {+ private DocValuesIndex[] docValuesIdx;+ private final int maxDoc;+ private int currentStart;+ private int currentMax;+ private int currentDoc = -1;+ private ValuesEnum currentEnum;+ private final int[] starts;++ public MultiValuesEnum(DocValuesIndex[] docValuesIdx, int[] starts)+ throws IOException {+ super(docValuesIdx[0].docValues.type());+ this.docValuesIdx = docValuesIdx;+ final DocValuesIndex last = docValuesIdx[docValuesIdx.length - 1];+ maxDoc = last.start + last.length;+ final DocValuesIndex idx = docValuesIdx[0];+ currentEnum = idx.docValues.getEnum(this.attributes());++ currentEnum.copyReferences(this);++ intsRef = currentEnum.intsRef;+ currentMax = idx.length;+ currentStart = 0;+ this.starts = starts;+ }++ @Override+ public void close() throws IOException {+ currentEnum.close();+ }++ @Override+ public int advance(int target) throws IOException {+ assert target > currentDoc : "target " + target+ + " must be > than the current doc " + currentDoc;+ int relativeDoc = target - currentStart;+ do {+ if (target >= maxDoc) // we are beyond max doc+ return currentDoc = NO_MORE_DOCS;+ if (target >= currentMax) {+ final int idx = ReaderUtil.subIndex(target, starts);+ currentEnum.close();+ currentEnum = docValuesIdx[idx].docValues.getEnum(this.attributes());++ currentEnum.copyReferences(this);+ currentStart = docValuesIdx[idx].start;+ currentMax = currentStart + docValuesIdx[idx].length;+ relativeDoc = target - currentStart;+ } else {+ return currentDoc = currentStart + currentEnum.advance(relativeDoc);+ }+ } while ((relativeDoc = currentEnum.advance(relativeDoc)) == NO_MORE_DOCS);+ return currentDoc = currentStart + relativeDoc;+ }++ @Override+ public int docID() {+ return currentDoc;+ }++ @Override+ public int nextDoc() throws IOException {+ return advance(currentDoc + 1);+ }+ }++ private static class MultiSource extends Source {+ private int numDocs = 0;+ private int start = 0;+ private Source current;+ private final int[] starts;+ private final DocValuesIndex[] docValuesIdx;++ public MultiSource(DocValuesIndex[] docValuesIdx, int[] starts) {+ this.docValuesIdx = docValuesIdx;+ this.starts = starts;+ assert docValuesIdx.length != 0;++ }++ public long getInt(int docID) {+ final int doc = ensureSource(docID);+ return current.getInt(doc);+ }++ private final int ensureSource(int docID) {+ int n = docID - start;+ if (n >= numDocs) {+ final int idx = ReaderUtil.subIndex(docID, starts);+ assert idx >= 0 && idx < docValuesIdx.length : "idx was " + idx+ + " for doc id: " + docID + " slices : " + Arrays.toString(starts);+ assert docValuesIdx[idx] != null;+ try {+ current = docValuesIdx[idx].docValues.getSource();+ missingValue.copy(current.getMissing());+ } catch (IOException e) {+ throw new RuntimeException("load failed", e); // TODO how should we+ // handle this+ }++ start = docValuesIdx[idx].start;+ numDocs = docValuesIdx[idx].length;+ n = docID - start;+ }+ return n;+ }++ public double getFloat(int docID) {+ final int doc = ensureSource(docID);+ return current.getFloat(doc);+ }++ public BytesRef getBytes(int docID, BytesRef bytesRef) {+ final int doc = ensureSource(docID);+ return current.getBytes(doc, bytesRef);+ }++ @Override+ public ValuesEnum getEnum(AttributeSource attrSource) throws IOException {+ throw new UnsupportedOperationException(); // TODO+ }++ @Override+ public Values type() {+ return docValuesIdx[0].docValues.type();+ }++ }++ private static class EmptySource extends Source {+ private final Values type;++ public EmptySource(Values type) {+ this.type = type;+ }++ @Override+ public BytesRef getBytes(int docID, BytesRef ref) {+ return this.missingValue.bytesValue;++ }++ @Override+ public double getFloat(int docID) {+ return missingValue.doubleValue;+ }++ @Override+ public long getInt(int docID) {+ return missingValue.longValue;+ }+- public long ramBytesUsed() {- return 0;- }-+ @Override+ public ValuesEnum getEnum(AttributeSource attrSource) throws IOException {+ return ValuesEnum.emptyEnum(type);+ }++ @Override+ public Values type() {+ return type;+ }+ }++ @Override+ public Values type() {+ return this.docValuesIdx[0].docValues.type();+ }+}diff --cc lucene/src/java/org/apache/lucene/index/values/PackedIntsImpl.javaindex 61f19e7cb5a,00000000000..9842352c571mode 100644,000000..100644--- a/lucene/src/java/org/apache/lucene/index/values/PackedIntsImpl.java+++ b/lucene/src/java/org/apache/lucene/index/values/PackedIntsImpl.java@@@ -1,302 -1,0 +1,293 @@@+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.IOException;+import java.util.Collection;+import java.util.concurrent.atomic.AtomicLong;++import org.apache.lucene.index.IndexFileNames;+import org.apache.lucene.store.Directory;+import org.apache.lucene.store.IndexInput;+import org.apache.lucene.store.IndexOutput;+import org.apache.lucene.util.ArrayUtil;+import org.apache.lucene.util.AttributeSource;+import org.apache.lucene.util.CodecUtil;+import org.apache.lucene.util.LongsRef;+import org.apache.lucene.util.OpenBitSet;+import org.apache.lucene.util.RamUsageEstimator;+import org.apache.lucene.util.packed.PackedInts;+- /** Stores ints packed with fixed-bit precision. */++/** Stores ints packed with fixed-bit precision.++ *++ * @lucene.experimental++ * */+class PackedIntsImpl {++ private static final String CODEC_NAME = "PackedInts";++ static final int VERSION_START = 0;+ static final int VERSION_CURRENT = VERSION_START;++ static class IntsWriter extends Writer {++ // TODO: can we bulkcopy this on a merge?+ private LongsRef intsRef;+ private long[] docToValue;+ private long minValue;+ private long maxValue;+ private boolean started;+ private final Directory dir;+ private final String id;+ private final OpenBitSet defaultValues = new OpenBitSet(1);+ private int lastDocId = -1;++ protected IntsWriter(Directory dir, String id, AtomicLong bytesUsed) throws IOException {+ super(bytesUsed);+ this.dir = dir;+ this.id = id;+ docToValue = new long[1];+ bytesUsed.addAndGet(RamUsageEstimator.NUM_BYTES_LONG); // TODO the bitset needs memory too+ }++ @Override+ public synchronized void add(int docID, long v) throws IOException {+ assert lastDocId < docID;+ if (!started) {+ started = true;+ minValue = maxValue = v;+ } else {+ if (v < minValue) {+ minValue = v;+ } else if (v > maxValue) {+ maxValue = v;+ }+ }+ defaultValues.set(docID);+ lastDocId = docID;++ if (docID >= docToValue.length) {+ final long len = docToValue.length ;+ docToValue = ArrayUtil.grow(docToValue, 1 + docID);+ defaultValues.ensureCapacity(docToValue.length);+ bytesUsed.addAndGet(RamUsageEstimator.NUM_BYTES_LONG * ((docToValue.length) - len));+ }+ docToValue[docID] = v;+ }++ @Override+ public synchronized void finish(int docCount) throws IOException {+ if (!started)+ return;+ final IndexOutput datOut = dir.createOutput(IndexFileNames+ .segmentFileName(id, "", DATA_EXTENSION));+ CodecUtil.writeHeader(datOut, CODEC_NAME, VERSION_CURRENT);++ // TODO -- long can't work right since it's signed+ datOut.writeLong(minValue);+ // write a default value to recognize docs without a value for that field+ final long defaultValue = ++maxValue - minValue;+ datOut.writeLong(defaultValue);+ PackedInts.Writer w = PackedInts.getWriter(datOut, docCount, PackedInts+ .bitsRequired(maxValue - minValue));+ final int firstDoc = defaultValues.nextSetBit(0);+ assert firstDoc >= 0; // we have at lest one value!+ for (int i = 0; i < firstDoc; i++) {+ w.add(defaultValue); // fill with defaults until first bit set+ }+ lastDocId++;+ for (int i = firstDoc; i < lastDocId;) {+ w.add(docToValue[i] - minValue);+ final int nextValue = defaultValues.nextSetBit(i);+ for (i++; i < nextValue; i++) {+ w.add(defaultValue); // fill all gaps+ }+ }+ for (int i = lastDocId; i < docCount; i++) {+ w.add(defaultValue);+ }+ w.finish();+ datOut.close();+ bytesUsed.addAndGet(-(RamUsageEstimator.NUM_BYTES_LONG * docToValue.length ));+ docToValue = null;++ }++ @Override+ protected void add(int docID) throws IOException {+ add(docID, intsRef.get());+ }++ @Override- protected void setNextAttribute(ValuesAttribute attr) {- intsRef = attr.ints();++ protected void setNextEnum(ValuesEnum valuesEnum) {++ intsRef = valuesEnum.getInt();+ }++ @Override- public void add(int docID, ValuesAttribute attr) throws IOException {- final LongsRef ref;- if ((ref = attr.ints()) != null) {- add(docID, ref.get());- }++ public void add(int docID, PerDocFieldValues docValues) throws IOException {++ add(docID, docValues.getInt());+ }++ @Override+ public void files(Collection<String> files) throws IOException {+ files.add(IndexFileNames.segmentFileName(id, "", DATA_EXTENSION));+ }+ }++ /**+ * Opens all necessary files, but does not read any data in until you call+ * {@link #load}.+ */+ static class IntsReader extends DocValues {+ private final IndexInput datIn;++ protected IntsReader(Directory dir, String id) throws IOException {+ datIn = dir.openInput(IndexFileNames.segmentFileName(id, "",+ Writer.DATA_EXTENSION));+ CodecUtil.checkHeader(datIn, CODEC_NAME, VERSION_START, VERSION_START);+ }++ /**+ * Loads the actual values. You may call this more than once, eg if you+ * already previously loaded but then discarded the Source.+ */+ @Override+ public Source load() throws IOException {+ return new IntsSource((IndexInput) datIn.clone());+ }++ private static class IntsSource extends Source {+ private final long minValue;+ private final long defaultValue;+ private final PackedInts.Reader values;++ public IntsSource(IndexInput dataIn) throws IOException {+ dataIn.seek(CodecUtil.headerLength(CODEC_NAME));+ minValue = dataIn.readLong();+ defaultValue = dataIn.readLong();+ values = PackedInts.getReader(dataIn);+ missingValue.longValue = minValue + defaultValue;+ }++ @Override+ public long getInt(int docID) {+ // TODO -- can we somehow avoid 2X method calls+ // on each get? must push minValue down, and make+ // PackedInts implement Ints.Source+ return minValue + values.get(docID);+ }+- public long ramBytesUsed() {- // TODO(simonw): move that to PackedInts?- return RamUsageEstimator.NUM_BYTES_ARRAY_HEADER- + values.getBitsPerValue() * values.size();- }-+ @Override+ public ValuesEnum getEnum(AttributeSource attrSource) throws IOException {+ final MissingValue missing = getMissing();+ return new SourceEnum(attrSource, type(), this, values.size()) {- private final LongsRef ref = attr.ints();+ @Override+ public int advance(int target) throws IOException {+ if (target >= numDocs)+ return pos = NO_MORE_DOCS;+ while (source.getInt(target) == missing.longValue) {+ if (++target >= numDocs) {+ return pos = NO_MORE_DOCS;+ }+ }- ref.ints[ref.offset] = source.getInt(target);++ intsRef.ints[intsRef.offset] = source.getInt(target);+ return pos = target;+ }+ };+ }++ @Override+ public Values type() {+ return Values.PACKED_INTS;+ }+ }++ @Override+ public void close() throws IOException {+ super.close();+ datIn.close();+ }++ @Override+ public ValuesEnum getEnum(AttributeSource source) throws IOException {+ return new IntsEnumImpl(source, (IndexInput) datIn.clone());+ }++ @Override+ public Values type() {+ return Values.PACKED_INTS;+ }++ }++ private static final class IntsEnumImpl extends ValuesEnum {+ private final PackedInts.ReaderIterator ints;+ private long minValue;+ private final IndexInput dataIn;+ private final long defaultValue;- private LongsRef ref;+ private final int maxDoc;+ private int pos = -1;++ private IntsEnumImpl(AttributeSource source, IndexInput dataIn)+ throws IOException {+ super(source, Values.PACKED_INTS);- this.ref = attr.ints();- this.ref.offset = 0;++ intsRef.offset = 0;+ this.dataIn = dataIn;+ dataIn.seek(CodecUtil.headerLength(CODEC_NAME));+ minValue = dataIn.readLong();+ defaultValue = dataIn.readLong();+ this.ints = PackedInts.getReaderIterator(dataIn);+ maxDoc = ints.size();+ }++ @Override+ public void close() throws IOException {+ ints.close();+ dataIn.close();+ }++ @Override+ public int advance(int target) throws IOException {+ if (target >= maxDoc) {+ return pos = NO_MORE_DOCS;+ }+ long val = ints.advance(target);+ while (val == defaultValue) {+ if (++target >= maxDoc) {+ return pos = NO_MORE_DOCS;+ }+ val = ints.advance(target);+ }- ref.ints[0] = minValue + val;- ref.offset = 0; // can we skip this?++ intsRef.ints[0] = minValue + val;++ intsRef.offset = 0; // can we skip this?+ return pos = target;+ }++ @Override+ public int docID() {+ return pos;+ }++ @Override+ public int nextDoc() throws IOException {+ if (pos >= maxDoc) {+ return pos = NO_MORE_DOCS;+ }+ return advance(pos + 1);+ }+ }+}diff --cc lucene/src/java/org/apache/lucene/index/values/PerDocFieldValues.javaindex 35299482360,00000000000..e94b7d5505fmode 100644,000000..100644--- a/lucene/src/java/org/apache/lucene/index/values/PerDocFieldValues.java+++ b/lucene/src/java/org/apache/lucene/index/values/PerDocFieldValues.java@@@ -1,34 -1,0 +1,53 @@@+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.util.Comparator;+- import org.apache.lucene.util.Attribute;+import org.apache.lucene.util.BytesRef;- import org.apache.lucene.util.FloatsRef;- import org.apache.lucene.util.LongsRef;+- public interface ValuesAttribute extends Attribute {- public Values type();- public BytesRef bytes();- public FloatsRef floats();- public LongsRef ints();- public void setType(Values type);++/**++ *++ * @lucene.experimental++ */++public interface PerDocFieldValues {++++ public void setInt(long value);++++ public void setFloat(float value);++++ public void setFloat(double value);++++ public void setBytes(BytesRef value, Values type);++++ public void setBytes(BytesRef value, Values type, Comparator<BytesRef> comp);++++ public BytesRef getBytes();+++ public Comparator<BytesRef> bytesComparator();++++ public double getFloat();++++ public long getInt();+++ public void setBytesComparator(Comparator<BytesRef> comp);-++++ public void setType(Values type);++++ public Values type();+++}diff --cc lucene/src/java/org/apache/lucene/index/values/SourceCache.javaindex 69037b28a68,00000000000..e2f4c63c9aamode 100644,000000..100644--- a/lucene/src/java/org/apache/lucene/index/values/SourceCache.java+++ b/lucene/src/java/org/apache/lucene/index/values/SourceCache.java@@@ -1,65 -1,0 +1,65 @@@+package org.apache.lucene.index.values;+- import java.io.IOException;- import java.util.Comparator;-- import org.apache.lucene.index.values.DocValues.SortedSource;- import org.apache.lucene.index.values.DocValues.Source;- import org.apache.lucene.util.BytesRef;-+/**+ * 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.Comparator;++++import org.apache.lucene.index.values.DocValues.SortedSource;++import org.apache.lucene.index.values.DocValues.Source;++import org.apache.lucene.util.BytesRef;+++/**+ * Per {@link DocValues} {@link Source} cache.+ */+public abstract class SourceCache {+ public abstract Source load(DocValues values) throws IOException;++ public abstract SortedSource laodSorted(DocValues values,+ Comparator<BytesRef> comp) throws IOException;++ public abstract void invalidate(DocValues values);++ public synchronized void close(DocValues values) {+ invalidate(values);+ }++ public static final class DirectSourceCache extends SourceCache {+ private Source ref;+ private SortedSource sortedRef;++ public synchronized Source load(DocValues values) throws IOException {+ if (ref == null)+ ref = values.load();+ return ref;+ }++ public synchronized SortedSource laodSorted(DocValues values,+ Comparator<BytesRef> comp) throws IOException {+ if (sortedRef == null)+ sortedRef = values.loadSorted(comp);+ return sortedRef;+ }++ public synchronized void invalidate(DocValues values) {+ ref = null;+ sortedRef = null;+ }+ }++}diff --cc lucene/src/java/org/apache/lucene/index/values/Values.javaindex 56921dd36c2,00000000000..31adfd2a51amode 100644,000000..100644--- a/lucene/src/java/org/apache/lucene/index/values/Values.java+++ b/lucene/src/java/org/apache/lucene/index/values/Values.java@@@ -1,47 -1,0 +1,47 @@@+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.+ */++/** Controls whether per-field values are stored into+ * index. This storage is non-sparse, so it's best to+ * use this when all docs have the field, and loads all+ * values into RAM, exposing a random access API, when+ * loaded.+ *- * @lucene.experimenta++ * @lucene.experimental+ */+public enum Values {++ /** Integral value is stored as packed ints. The bit+ * precision is fixed across the segment, and+ * determined by the min/max values in the field. */+ PACKED_INTS,+ SIMPLE_FLOAT_4BYTE,+ SIMPLE_FLOAT_8BYTE,++ // TODO(simonw): -- shouldn't lucene decide/detect straight vs+ // deref, as well fixed vs var?+ BYTES_FIXED_STRAIGHT,+ BYTES_FIXED_DEREF,+ BYTES_FIXED_SORTED,++ BYTES_VAR_STRAIGHT,+ BYTES_VAR_DEREF,+ BYTES_VAR_SORTED++ // TODO(simonw): -- need STRING variants as well+}diff --cc lucene/src/java/org/apache/lucene/index/values/ValuesEnum.javaindex 54bc8bf2c7e,00000000000..8008929dabcmode 100644,000000..100644--- a/lucene/src/java/org/apache/lucene/index/values/ValuesEnum.java+++ b/lucene/src/java/org/apache/lucene/index/values/ValuesEnum.java@@@ -1,104 -1,0 +1,130 @@@+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.IOException;++import org.apache.lucene.search.DocIdSetIterator;+import org.apache.lucene.util.Attribute;+import org.apache.lucene.util.AttributeSource;+import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.FloatsRef;+import org.apache.lucene.util.LongsRef;-++/**++ *++ * @lucene.experimental++ */+public abstract class ValuesEnum extends DocIdSetIterator {+ private AttributeSource source;- protected final ValuesAttribute attr;++ private Values enumType;++ protected BytesRef bytesRef;++ protected FloatsRef floatsRef;++ protected LongsRef intsRef;++ protected ValuesEnum(Values enumType) {+ this(null, enumType);+ }++ protected ValuesEnum(AttributeSource source, Values enumType) {+ this.source = source;- boolean setType = !hasAttribute(ValuesAttribute.class);- attr = addAttribute(ValuesAttribute.class);- if (setType)- attr.setType(enumType);++ this.enumType = enumType;++ switch (enumType) {++ case BYTES_FIXED_DEREF:++ case BYTES_FIXED_SORTED:++ case BYTES_FIXED_STRAIGHT:++ case BYTES_VAR_DEREF:++ case BYTES_VAR_SORTED:++ case BYTES_VAR_STRAIGHT:++ bytesRef = new BytesRef();++ break;++ case PACKED_INTS:++ intsRef = new LongsRef(1);++ break;++ case SIMPLE_FLOAT_4BYTE:++ case SIMPLE_FLOAT_8BYTE:++ floatsRef = new FloatsRef(1);++ break;++ }+ }++ public Values type() {- return attr.type();++ return enumType;+ }++ public BytesRef bytes() {- return attr.bytes();++ return bytesRef;+ }++ public FloatsRef getFloat() {- return attr.floats();++ return floatsRef;+ }++ public LongsRef getInt() {- return attr.ints();++ return intsRef;++ }++++ protected void copyReferences(ValuesEnum valuesEnum) {++ intsRef = valuesEnum.intsRef;++ floatsRef = valuesEnum.floatsRef;++ bytesRef = valuesEnum.bytesRef;+ }++ public AttributeSource attributes() {+ if (source == null)+ source = new AttributeSource();+ return source;+ }++ public <T extends Attribute> T addAttribute(Class<T> attr) {+ return attributes().addAttribute(attr);+ }++ public <T extends Attribute> T getAttribute(Class<T> attr) {+ return attributes().getAttribute(attr);+ }++ public <T extends Attribute> boolean hasAttribute(Class<T> attr) {+ return attributes().hasAttribute(attr);+ }++ public abstract void close() throws IOException;++ public static ValuesEnum emptyEnum(Values type) {+ return new ValuesEnum(type) {+ @Override+ public int nextDoc() throws IOException {+ return NO_MORE_DOCS;+ }++ @Override+ public int docID() {+ return NO_MORE_DOCS;+ }++ @Override+ public int advance(int target) throws IOException {+ return NO_MORE_DOCS;+ }++ @Override+ public void close() throws IOException {++ }+ };+ }++}diff --cc lucene/src/java/org/apache/lucene/index/values/VarDerefBytesImpl.javaindex b0e89ce92cd,00000000000..985b960c5a2mode 100644,000000..100644--- a/lucene/src/java/org/apache/lucene/index/values/VarDerefBytesImpl.java+++ b/lucene/src/java/org/apache/lucene/index/values/VarDerefBytesImpl.java@@@ -1,277 -1,0 +1,280 @@@+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.IOException;+import java.util.concurrent.atomic.AtomicLong;++import org.apache.lucene.index.values.Bytes.BytesBaseSource;+import org.apache.lucene.index.values.Bytes.BytesReaderBase;+import org.apache.lucene.index.values.Bytes.BytesWriterBase;+import org.apache.lucene.index.values.FixedDerefBytesImpl.Reader.DerefBytesEnum;+import org.apache.lucene.store.DataOutput;+import org.apache.lucene.store.Directory;+import org.apache.lucene.store.IndexInput;+import org.apache.lucene.util.ArrayUtil;+import org.apache.lucene.util.AttributeSource;+import org.apache.lucene.util.ByteBlockPool;+import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.BytesRefHash;+import org.apache.lucene.util.CodecUtil;+import org.apache.lucene.util.PagedBytes;+import org.apache.lucene.util.RamUsageEstimator;+import org.apache.lucene.util.ByteBlockPool.Allocator;+import org.apache.lucene.util.ByteBlockPool.DirectAllocator;+import org.apache.lucene.util.BytesRefHash.TrackingDirectBytesStartArray;+import org.apache.lucene.util.packed.PackedInts;++// Stores variable-length byte[] by deref, ie when two docs+// have the same value, they store only 1 byte[] and both+// docs reference that single source+++/**++ * @lucene.experimental++ */+class VarDerefBytesImpl {++ static final String CODEC_NAME = "VarDerefBytes";+ static final int VERSION_START = 0;+ static final int VERSION_CURRENT = VERSION_START;++ private static final class AddressByteStartArray extends+ TrackingDirectBytesStartArray {+ int[] address;++ AddressByteStartArray(int size, AtomicLong bytesUsed) {+ super(size, bytesUsed);+ }++ @Override+ public AtomicLong bytesUsed() {+ return bytesUsed;+ }++ @Override+ public int[] clear() {+ if (address != null) {+ bytesUsed.addAndGet(-address.length * RamUsageEstimator.NUM_BYTES_INT);+ address = null;+ }+ return super.clear();+ }++ @Override+ public int[] grow() {+ assert address != null;+ final int oldSize = address.length;+ final int[] retVal = super.grow();+ address = ArrayUtil.grow(address, retVal.length);+ bytesUsed.addAndGet(RamUsageEstimator.NUM_BYTES_INT+ * (address.length - oldSize));+ return retVal;+ }++ @Override+ public int[] init() {+ if (address == null) {+ address = new int[ArrayUtil.oversize(initSize,+ RamUsageEstimator.NUM_BYTES_INT)];+ bytesUsed.addAndGet((address.length) * RamUsageEstimator.NUM_BYTES_INT);+ }+ return super.init();+ }++ }++ static class Writer extends BytesWriterBase {+ private int[] docToAddress;+ private int address = 1;++ private final AddressByteStartArray array = new AddressByteStartArray(1,+ bytesUsed);+ private final BytesRefHash hash = new BytesRefHash(pool, 16, array);++ public Writer(Directory dir, String id, AtomicLong bytesUsed)+ throws IOException {+ this(dir, id, new DirectAllocator(ByteBlockPool.BYTE_BLOCK_SIZE),+ bytesUsed);+ }++ public Writer(Directory dir, String id, Allocator allocator,+ AtomicLong bytesUsed) throws IOException {+ super(dir, id, CODEC_NAME, VERSION_CURRENT, false, false,+ new ByteBlockPool(allocator), bytesUsed);+ docToAddress = new int[1];+ bytesUsed.addAndGet(RamUsageEstimator.NUM_BYTES_INT);+ }++ @Override+ synchronized public void add(int docID, BytesRef bytes) throws IOException {+ if (bytes.length == 0)+ return; // default+ if (datOut == null)+ initDataOut();+ final int e = hash.add(bytes);++ if (docID >= docToAddress.length) {+ final int oldSize = docToAddress.length;+ docToAddress = ArrayUtil.grow(docToAddress, 1 + docID);+ bytesUsed.addAndGet(RamUsageEstimator.NUM_BYTES_INT+ * (docToAddress.length - oldSize));+ }+ final int docAddress;+ if (e >= 0) {+ docAddress = array.address[e] = address;+ address += writePrefixLength(datOut, bytes);+ datOut.writeBytes(bytes.bytes, bytes.offset, bytes.length);+ address += bytes.length;+ } else {+ docAddress = array.address[(-e) - 1];+ }+ docToAddress[docID] = docAddress;+ }++ private static int writePrefixLength(DataOutput datOut, BytesRef bytes)+ throws IOException {+ if (bytes.length < 128) {+ datOut.writeByte((byte) bytes.length);+ return 1;+ } else {+ datOut.writeByte((byte) (0x80 | (bytes.length >> 8)));+ datOut.writeByte((byte) (bytes.length & 0xff));+ return 2;+ }+ }++ // Important that we get docCount, in case there were+ // some last docs that we didn't see+ @Override+ synchronized public void finish(int docCount) throws IOException {+ if (datOut == null)+ return;+ initIndexOut();+ idxOut.writeInt(address - 1);++ // write index+ // TODO(simonw): -- allow forcing fixed array (not -1)+ // TODO(simonw): check the address calculation / make it more intuitive+ final PackedInts.Writer w = PackedInts.getWriter(idxOut, docCount,+ PackedInts.bitsRequired(address - 1));+ final int limit;+ if (docCount > docToAddress.length) {+ limit = docToAddress.length;+ } else {+ limit = docCount;+ }+ for (int i = 0; i < limit; i++) {+ w.add(docToAddress[i]);+ }+ for (int i = limit; i < docCount; i++) {+ w.add(0);+ }+ w.finish();+ hash.close();+ super.finish(docCount);+ bytesUsed.addAndGet(RamUsageEstimator.NUM_BYTES_INT+ * (-docToAddress.length));+ docToAddress = null;+ }+ }++ public static class Reader extends BytesReaderBase {++ Reader(Directory dir, String id, int maxDoc) throws IOException {+ super(dir, id, CODEC_NAME, VERSION_START, true);+ }++ @Override+ public Source load() throws IOException {+ final IndexInput data = cloneData();+ final IndexInput index = cloneIndex();+ data.seek(CodecUtil.headerLength(CODEC_NAME));+ index.seek(CodecUtil.headerLength(CODEC_NAME));+ final long totalBytes = index.readInt(); // should be long+ return new Source(data, index, totalBytes);+ }++ private static class Source extends BytesBaseSource {+ private final PackedInts.Reader index;++ public Source(IndexInput datIn, IndexInput idxIn, long totalBytes)+ throws IOException {+ super(datIn, idxIn, new PagedBytes(PAGED_BYTES_BITS), totalBytes);+ index = PackedInts.getReader(idxIn);+ }++ @Override+ public BytesRef getBytes(int docID, BytesRef bytesRef) {+ long address = index.get(docID);+ return address == 0 ? null : data.fillSliceWithPrefix(bytesRef,+ --address);+ }++ @Override+ public int getValueCount() {+ throw new UnsupportedOperationException();+ }++ @Override+ public Values type() {+ return Values.BYTES_VAR_DEREF;+ }++ @Override+ protected int maxDoc() {+ return index.size();+ }+ }++ @Override+ public ValuesEnum getEnum(AttributeSource source) throws IOException {+ return new VarDerefBytesEnum(source, cloneData(), cloneIndex());+ }++ static class VarDerefBytesEnum extends DerefBytesEnum {++ public VarDerefBytesEnum(AttributeSource source, IndexInput datIn,+ IndexInput idxIn) throws IOException {+ super(source, datIn, idxIn, -1, Values.BYTES_VAR_DEREF);+ }++ @Override+ protected void fill(long address, BytesRef ref) throws IOException {+ datIn.seek(fp + --address);+ final byte sizeByte = datIn.readByte();+ final int size;+ if ((sizeByte & 128) == 0) {+ // length is 1 byte+ size = sizeByte;+ } else {+ size = ((sizeByte & 0x7f) << 8) | ((datIn.readByte() & 0xff));+ }+ if (ref.bytes.length < size)+ ref.grow(size);+ ref.length = size;+ ref.offset = 0;+ datIn.readBytes(ref.bytes, 0, size);+ }+ }++ @Override+ public Values type() {+ return Values.BYTES_VAR_DEREF;+ }+ }+}diff --cc lucene/src/java/org/apache/lucene/index/values/VarSortedBytesImpl.javaindex 0c22fd8ae54,00000000000..53dddf31c73mode 100644,000000..100644--- a/lucene/src/java/org/apache/lucene/index/values/VarSortedBytesImpl.java+++ b/lucene/src/java/org/apache/lucene/index/values/VarSortedBytesImpl.java@@@ -1,316 -1,0 +1,316 @@@+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.IOException;+import java.util.Arrays;+import java.util.Comparator;+import java.util.concurrent.atomic.AtomicLong;++import org.apache.lucene.index.values.Bytes.BytesBaseSortedSource;+import org.apache.lucene.index.values.Bytes.BytesReaderBase;+import org.apache.lucene.index.values.Bytes.BytesWriterBase;+import org.apache.lucene.store.Directory;+import org.apache.lucene.store.IndexInput;+import org.apache.lucene.util.ArrayUtil;+import org.apache.lucene.util.AttributeSource;+import org.apache.lucene.util.ByteBlockPool;+import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.BytesRefHash;+import org.apache.lucene.util.PagedBytes;+import org.apache.lucene.util.RamUsageEstimator;+import org.apache.lucene.util.ByteBlockPool.Allocator;+import org.apache.lucene.util.ByteBlockPool.DirectAllocator;+import org.apache.lucene.util.BytesRefHash.TrackingDirectBytesStartArray;+import org.apache.lucene.util.packed.PackedInts;++// Stores variable-length byte[] by deref, ie when two docs+// have the same value, they store only 1 byte[] and both+// docs reference that single source+++/**++ * @lucene.experimental++ */+class VarSortedBytesImpl {++ static final String CODEC_NAME = "VarDerefBytes";+ static final int VERSION_START = 0;+ static final int VERSION_CURRENT = VERSION_START;++ static class Writer extends BytesWriterBase {+ private int[] docToEntry;+ private final Comparator<BytesRef> comp;++ private final BytesRefHash hash = new BytesRefHash(pool, BytesRefHash.DEFAULT_CAPACITY,+ new TrackingDirectBytesStartArray(BytesRefHash.DEFAULT_CAPACITY, bytesUsed));++ public Writer(Directory dir, String id, Comparator<BytesRef> comp, AtomicLong bytesUsed)+ throws IOException {+ this(dir, id, comp, new DirectAllocator(ByteBlockPool.BYTE_BLOCK_SIZE), bytesUsed);+ }++ public Writer(Directory dir, String id, Comparator<BytesRef> comp,+ Allocator allocator, AtomicLong bytesUsed) throws IOException {+ super(dir, id, CODEC_NAME, VERSION_CURRENT, false, false,+ new ByteBlockPool(allocator), bytesUsed);+ this.comp = comp;+ docToEntry = new int[1];+ docToEntry[0] = -1;+ bytesUsed.addAndGet(RamUsageEstimator.NUM_BYTES_INT);++ }++ @Override+ synchronized public void add(int docID, BytesRef bytes) throws IOException {+ if (bytes.length == 0)+ return;// default+ if (docID >= docToEntry.length) {+ int[] newArray = new int[ArrayUtil.oversize(1 + docID,+ RamUsageEstimator.NUM_BYTES_OBJECT_REF)];+ System.arraycopy(docToEntry, 0, newArray, 0, docToEntry.length);+ Arrays.fill(newArray, docToEntry.length, newArray.length, -1);+ bytesUsed.addAndGet((newArray.length - docToEntry.length)+ * RamUsageEstimator.NUM_BYTES_INT);+ docToEntry = newArray;+ }+ final int e = hash.add(bytes);+ docToEntry[docID] = e < 0 ? (-e) - 1 : e;+ }++ // Important that we get docCount, in case there were+ // some last docs that we didn't see+ @Override+ synchronized public void finish(int docCount) throws IOException {+ final int count = hash.size();+ if (count == 0)+ return;+ initIndexOut();+ initDataOut();+ int[] sortedEntries = hash.sort(comp);++ // first dump bytes data, recording index & offset as+ // we go+ long offset = 0;+ long lastOffset = 0;+ final int[] index = new int[count];+ final long[] offsets = new long[count];+ for (int i = 0; i < count; i++) {+ final int e = sortedEntries[i];+ offsets[i] = offset;+ index[e] = 1 + i;++ final BytesRef bytes = hash.get(e, new BytesRef());+ // TODO: we could prefix code...+ datOut.writeBytes(bytes.bytes, bytes.offset, bytes.length);+ lastOffset = offset;+ offset += bytes.length;+ }++ // total bytes of data+ idxOut.writeLong(offset);++ // write index -- first doc -> 1+ord+ // TODO(simonw): allow not -1:+ final PackedInts.Writer indexWriter = PackedInts.getWriter(idxOut,+ docCount, PackedInts.bitsRequired(count));+ final int limit = docCount > docToEntry.length ? docToEntry.length+ : docCount;+ for (int i = 0; i < limit; i++) {+ final int e = docToEntry[i];+ indexWriter.add(e == -1 ? 0 : index[e]);+ }+ for (int i = limit; i < docCount; i++) {+ indexWriter.add(0);+ }+ indexWriter.finish();++ // next ord (0-based) -> offset+ // TODO(simonw): -- allow not -1:+ PackedInts.Writer offsetWriter = PackedInts.getWriter(idxOut, count,+ PackedInts.bitsRequired(lastOffset));+ for (int i = 0; i < count; i++) {+ offsetWriter.add(offsets[i]);+ }+ offsetWriter.finish();++ super.finish(docCount);+ bytesUsed.addAndGet((-docToEntry.length)+ * RamUsageEstimator.NUM_BYTES_INT);+ hash.close();++ }+ }++ public static class Reader extends BytesReaderBase {++ Reader(Directory dir, String id, int maxDoc) throws IOException {+ super(dir, id, CODEC_NAME, VERSION_START, true);+ }++ @Override+ public org.apache.lucene.index.values.DocValues.Source load()+ throws IOException {+ return loadSorted(null);+ }++ @Override+ public SortedSource loadSorted(Comparator<BytesRef> comp)+ throws IOException {+ IndexInput indexIn = cloneIndex();+ return new Source(cloneData(), indexIn , comp, indexIn.readLong());+ }++ private static class Source extends BytesBaseSortedSource {+ private final PackedInts.Reader docToOrdIndex;+ private final PackedInts.Reader ordToOffsetIndex; // 0-based+ private final long totBytes;+ private final int valueCount;++ public Source(IndexInput datIn, IndexInput idxIn,+ Comparator<BytesRef> comp, long dataLength) throws IOException {+ super(datIn, idxIn, comp, new PagedBytes(PAGED_BYTES_BITS), dataLength);+ totBytes = dataLength;+ docToOrdIndex = PackedInts.getReader(idxIn);+ ordToOffsetIndex = PackedInts.getReader(idxIn);+ valueCount = ordToOffsetIndex.size();+ }++ @Override+ public int ord(int docID) {+ return (int) docToOrdIndex.get(docID);+ }++ @Override+ public LookupResult getByValue(BytesRef bytes, BytesRef tmpRef) {+ return binarySearch(bytes, tmpRef, 0, valueCount - 1);+ }++ @Override+ public int getValueCount() {+ return valueCount;+ }++ // ord is 0-based+ @Override+ protected BytesRef deref(int ord, BytesRef bytesRef) {+ final long nextOffset;+ if (ord == valueCount - 1) {+ nextOffset = totBytes;+ } else {+ nextOffset = ordToOffsetIndex.get(1 + ord);+ }+ final long offset = ordToOffsetIndex.get(ord);- data.fill(bytesRef, offset , (int)(nextOffset - offset));++ data.fillSlice(bytesRef, offset , (int)(nextOffset - offset));+ return bytesRef;+ }++ @Override+ public Values type() {+ return Values.BYTES_VAR_SORTED;+ }++ @Override+ protected int maxDoc() {+ return docToOrdIndex.size();+ }+ }++ @Override+ public ValuesEnum getEnum(AttributeSource source) throws IOException {+ return new VarSortedBytesEnum(source, cloneData(), cloneIndex());+ }++ private static class VarSortedBytesEnum extends ValuesEnum {-+ private PackedInts.Reader docToOrdIndex;+ private PackedInts.Reader ordToOffsetIndex;+ private IndexInput idxIn;+ private IndexInput datIn;- private final BytesRef bytesRef;+ private int valueCount;+ private long totBytes;+ private int docCount;+ private int pos = -1;+ private final long fp;++ protected VarSortedBytesEnum(AttributeSource source, IndexInput datIn,+ IndexInput idxIn) throws IOException {+ super(source, Values.BYTES_VAR_SORTED);- bytesRef = attr.bytes();+ totBytes = idxIn.readLong();+ // keep that in memory to prevent lots of disk seeks+ docToOrdIndex = PackedInts.getReader(idxIn);+ ordToOffsetIndex = PackedInts.getReader(idxIn);+ valueCount = ordToOffsetIndex.size();+ docCount = docToOrdIndex.size();+ fp = datIn.getFilePointer();+ this.idxIn = idxIn;+ this.datIn = datIn;+ }++ @Override+ public void close() throws IOException {+ idxIn.close();+ datIn.close();+ }++ @Override+ public int advance(int target) throws IOException {+ if (target >= docCount) {+ return pos = NO_MORE_DOCS;+ }+ int ord;+ while((ord =(int) docToOrdIndex.get(target)) == 0) {+ if(++target >= docCount) {+ return pos = NO_MORE_DOCS;+ }+ }+ final long offset = ordToOffsetIndex.get(--ord);+ final long nextOffset;+ if (ord == valueCount - 1) {+ nextOffset = totBytes;+ } else {+ nextOffset = ordToOffsetIndex.get(1 + ord);+ }+ final int length = (int) (nextOffset - offset);+ datIn.seek(fp + offset);+ if (bytesRef.bytes.length < length)+ bytesRef.grow(length);+ datIn.readBytes(bytesRef.bytes, 0, length);+ bytesRef.length = length;+ bytesRef.offset = 0;+ return pos = target;+ }++ @Override+ public int docID() {+ return pos;+ }++ @Override+ public int nextDoc() throws IOException {+ if (pos >= docCount) {+ return pos = NO_MORE_DOCS;+ }+ return advance(pos + 1);+ }+ }++ @Override+ public Values type() {+ return Values.BYTES_VAR_SORTED;+ }+ }+}diff --cc lucene/src/java/org/apache/lucene/index/values/VarStraightBytesImpl.javaindex ccff45e1c5b,00000000000..c259fe2c242mode 100644,000000..100644--- a/lucene/src/java/org/apache/lucene/index/values/VarStraightBytesImpl.java+++ b/lucene/src/java/org/apache/lucene/index/values/VarStraightBytesImpl.java@@@ -1,226 -1,0 +1,227 @@@+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.IOException;+import java.util.concurrent.atomic.AtomicLong;++import org.apache.lucene.index.values.Bytes.BytesBaseSource;+import org.apache.lucene.index.values.Bytes.BytesReaderBase;+import org.apache.lucene.index.values.Bytes.BytesWriterBase;+import org.apache.lucene.store.Directory;+import org.apache.lucene.store.IndexInput;+import org.apache.lucene.util.ArrayUtil;+import org.apache.lucene.util.AttributeSource;+import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.PagedBytes;+import org.apache.lucene.util.RamUsageEstimator;+import org.apache.lucene.util.packed.PackedInts;++// Variable length byte[] per document, no sharing+++/**++ * @lucene.experimental++ */+class VarStraightBytesImpl {++ static final String CODEC_NAME = "VarStraightBytes";+ static final int VERSION_START = 0;+ static final int VERSION_CURRENT = VERSION_START;++ static class Writer extends BytesWriterBase {+ private long address;+ // start at -1 if the first added value is > 0+ private int lastDocID = -1;+ private long[] docToAddress;++ public Writer(Directory dir, String id, AtomicLong bytesUsed)+ throws IOException {+ super(dir, id, CODEC_NAME, VERSION_CURRENT, false, false, null, bytesUsed);+ docToAddress = new long[1];+ bytesUsed.addAndGet(RamUsageEstimator.NUM_BYTES_INT);+ }++ public Writer(Directory dir, String id) throws IOException {+ this(dir, id, new AtomicLong());+ }++ // Fills up to but not including this docID+ private void fill(final int docID) {+ if (docID >= docToAddress.length) {+ int oldSize = docToAddress.length;+ docToAddress = ArrayUtil.grow(docToAddress, 1 + docID);+ bytesUsed.addAndGet((docToAddress.length - oldSize)+ * RamUsageEstimator.NUM_BYTES_INT);+ }+ for (int i = lastDocID + 1; i < docID; i++) {+ docToAddress[i] = address;+ }+ lastDocID = docID;+ }++ @Override+ synchronized public void add(int docID, BytesRef bytes) throws IOException {+ if (bytes.length == 0)+ return; // default+ if (datOut == null)+ initDataOut();+ fill(docID);+ docToAddress[docID] = address;+ datOut.writeBytes(bytes.bytes, bytes.offset, bytes.length);+ address += bytes.length;+ }++ @Override+ synchronized public void finish(int docCount) throws IOException {+ if (datOut == null) {+ return;+ }+ initIndexOut();+ fill(docCount);+ idxOut.writeVLong(address);+ final PackedInts.Writer w = PackedInts.getWriter(idxOut, docCount,+ PackedInts.bitsRequired(address));+ for (int i = 0; i < docCount; i++) {+ w.add(docToAddress[i]);+ }+ w.finish();+ bytesUsed.addAndGet(-(docToAddress.length)+ * RamUsageEstimator.NUM_BYTES_INT);+ docToAddress = null;+ super.finish(docCount);+ }++ public long ramBytesUsed() {+ return bytesUsed.get();+ }+ }++ public static class Reader extends BytesReaderBase {+ private final int maxDoc;++ Reader(Directory dir, String id, int maxDoc) throws IOException {+ super(dir, id, CODEC_NAME, VERSION_START, true);+ this.maxDoc = maxDoc;+ }++ @Override+ public Source load() throws IOException {+ return new Source(cloneData(), cloneIndex());+ }++ private class Source extends BytesBaseSource {+ private final PackedInts.Reader addresses;++ public Source(IndexInput datIn, IndexInput idxIn) throws IOException {+ super(datIn, idxIn, new PagedBytes(PAGED_BYTES_BITS), idxIn.readVLong());+ addresses = PackedInts.getReader(idxIn);+ missingValue.bytesValue = new BytesRef(0); // empty+ }++ @Override+ public BytesRef getBytes(int docID, BytesRef bytesRef) {+ final long address = addresses.get(docID);+ final int length = docID == maxDoc - 1 ? (int) (totalLengthInBytes - address)+ : (int) (addresses.get(1 + docID) - address);- return data.fill(bytesRef, address, length);++ return data.fillSlice(bytesRef, address, length);+ }++ @Override+ public int getValueCount() {+ throw new UnsupportedOperationException();+ }++ @Override+ public Values type() {+ return Values.BYTES_VAR_STRAIGHT;+ }++ @Override+ protected int maxDoc() {+ return addresses.size();+ }+ }++ @Override+ public ValuesEnum getEnum(AttributeSource source) throws IOException {+ return new VarStraightBytesEnum(source, cloneData(), cloneIndex());+ }++ private class VarStraightBytesEnum extends ValuesEnum {+ private final PackedInts.Reader addresses;+ private final IndexInput datIn;+ private final IndexInput idxIn;+ private final long fp;+ private final int totBytes;- private final BytesRef ref;+ private int pos = -1;++ protected VarStraightBytesEnum(AttributeSource source, IndexInput datIn,+ IndexInput idxIn) throws IOException {+ super(source, Values.BYTES_VAR_STRAIGHT);+ totBytes = idxIn.readVInt();+ fp = datIn.getFilePointer();+ addresses = PackedInts.getReader(idxIn);+ this.datIn = datIn;+ this.idxIn = idxIn;- ref = attr.bytes();-+ }++ @Override+ public void close() throws IOException {+ datIn.close();+ idxIn.close();+ }++ @Override+ public int advance(final int target) throws IOException {+ if (target >= maxDoc) {+ return pos = NO_MORE_DOCS;+ }+ final long addr = addresses.get(target);+ if (addr == totBytes) { // empty values at the end- ref.length = 0;- ref.offset = 0;++ bytesRef.length = 0;++ bytesRef.offset = 0;+ return pos = target;+ }+ datIn.seek(fp + addr);+ final int size = (int) (target == maxDoc - 1 ? totBytes - addr+ : addresses.get(target + 1) - addr);- if (ref.bytes.length < size)- ref.grow(size);- ref.length = size;- datIn.readBytes(ref.bytes, 0, size);++ if (bytesRef.bytes.length < size) {++ bytesRef.grow(size);++ }++ bytesRef.length = size;++ datIn.readBytes(bytesRef.bytes, 0, size);+ return pos = target;+ }++ @Override+ public int docID() {+ return pos;+ }++ @Override+ public int nextDoc() throws IOException {+ return advance(pos + 1);+ }+ }++ @Override+ public Values type() {+ return Values.BYTES_VAR_STRAIGHT;+ }+ }+}diff --cc lucene/src/java/org/apache/lucene/index/values/Writer.javaindex 82dc03b6f2b,00000000000..376c09291ffmode 100644,000000..100644--- a/lucene/src/java/org/apache/lucene/index/values/Writer.java+++ b/lucene/src/java/org/apache/lucene/index/values/Writer.java@@@ -1,117 -1,0 +1,119 @@@+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.IOException;+import java.util.Comparator;+import java.util.concurrent.atomic.AtomicLong;++import org.apache.lucene.index.codecs.docvalues.DocValuesConsumer;+import org.apache.lucene.store.Directory;+import org.apache.lucene.util.Bits;+import org.apache.lucene.util.BytesRef;+++/**++ * @lucene.experimental++ */+public abstract class Writer extends DocValuesConsumer {++ protected Writer(AtomicLong bytesUsed) {+ super(bytesUsed);+ }++ public static final String INDEX_EXTENSION = "idx";+ public static final String DATA_EXTENSION = "dat";++ /** Records the specfied value for the docID */+ public void add(int docID, long value) throws IOException {+ throw new UnsupportedOperationException();+ }++ /** Records the specfied value for the docID */+ public void add(int docID, double value) throws IOException {+ throw new UnsupportedOperationException();+ }++ /** Records the specfied value for the docID */+ public void add(int docID, BytesRef value) throws IOException {+ throw new UnsupportedOperationException();+ }++ /** Records the specfied value for the docID */+ protected abstract void add(int docID) throws IOException;-- protected abstract void setNextAttribute(ValuesAttribute attr);++++ protected abstract void setNextEnum(ValuesEnum valuesEnum);++ /** Finish writing, close any files */+ public abstract void finish(int docCount) throws IOException;++ // enables bulk copies in subclasses per MergeState+ @Override+ protected void merge(MergeState state) throws IOException {+ final ValuesEnum valEnum = state.reader.getEnum();+ assert valEnum != null;+ try {- final ValuesAttribute attr = valEnum.addAttribute(ValuesAttribute.class);- setNextAttribute(attr);++ setNextEnum(valEnum);+ int docID = state.docBase;+ final Bits bits = state.bits;+ final int docCount = state.docCount;+ int currentDocId;+ if ((currentDocId = valEnum.advance(0)) != ValuesEnum.NO_MORE_DOCS) {+ for (int i = 0; i < docCount; i++) {+ if (bits == null || !bits.get(i)) {+ if (currentDocId < i) {+ if ((currentDocId = valEnum.advance(i)) == ValuesEnum.NO_MORE_DOCS) {+ break; // advance can jump over default values+ }+ }+ if (currentDocId == i) { // we are on the doc to merge+ add(docID);+ }+ ++docID;+ }+ }+ }+ } finally {+ valEnum.close();+ }+ }++ public static Writer create(Values v, String id, Directory directory,+ Comparator<BytesRef> comp, AtomicLong bytesUsed) throws IOException {+ switch (v) {+ case PACKED_INTS:+ return Ints.getWriter(directory, id, true, bytesUsed);+ case SIMPLE_FLOAT_4BYTE:+ return Floats.getWriter(directory, id, 4, bytesUsed);+ case SIMPLE_FLOAT_8BYTE:+ return Floats.getWriter(directory, id, 8, bytesUsed);+ case BYTES_FIXED_STRAIGHT:+ return Bytes.getWriter(directory, id, Bytes.Mode.STRAIGHT, comp, true, bytesUsed);+ case BYTES_FIXED_DEREF:+ return Bytes.getWriter(directory, id, Bytes.Mode.DEREF, comp, true, bytesUsed);+ case BYTES_FIXED_SORTED:+ return Bytes.getWriter(directory, id, Bytes.Mode.SORTED, comp, true, bytesUsed);+ case BYTES_VAR_STRAIGHT:+ return Bytes.getWriter(directory, id, Bytes.Mode.STRAIGHT, comp, false, bytesUsed);+ case BYTES_VAR_DEREF:+ return Bytes.getWriter(directory, id, Bytes.Mode.DEREF, comp, false, bytesUsed);+ case BYTES_VAR_SORTED:+ return Bytes.getWriter(directory, id, Bytes.Mode.SORTED, comp, false, bytesUsed);+ default:+ throw new IllegalArgumentException("Unknown Values: " + v);+ }+ }+}diff --cc lucene/src/java/org/apache/lucene/search/SortField.javaindex 0e512de4a9f,e058002f374..316b097165f--- a/lucene/src/java/org/apache/lucene/search/SortField.java+++ b/lucene/src/java/org/apache/lucene/search/SortField.java@@@ -19,22 -19,10 +19,16 @@@ package org.apache.lucene.searchimport java.io.IOException;import java.io.Serializable;+import java.util.Comparator;import java.util.Locale;- import org.apache.lucene.search.cache.ByteValuesCreator;- import org.apache.lucene.search.cache.CachedArrayCreator;- import org.apache.lucene.search.cache.DoubleValuesCreator;- import org.apache.lucene.search.cache.FloatValuesCreator;- import org.apache.lucene.search.cache.IntValuesCreator;- import org.apache.lucene.search.cache.LongValuesCreator;- import org.apache.lucene.search.cache.ShortValuesCreator;+ import org.apache.lucene.search.cache.*;import org.apache.lucene.util.StringHelper;+import org.apache.lucene.util.BytesRef;++// TODO(simonw) -- for cleaner transition, maybe we should make+// a new SortField that subclasses this one and always uses+// index values?/*** Stores information about how to sort documents by terms in an individualdiff --cc lucene/src/java/org/apache/lucene/util/PagedBytes.javaindex 331d066d8b3,c537459c577..d53e9b3140d--- a/lucene/src/java/org/apache/lucene/util/PagedBytes.java+++ b/lucene/src/java/org/apache/lucene/util/PagedBytes.java@@@ -90,9 -99,19 +99,19 @@@ public final class PagedBytes}return b;}-+- /** Reads length as 1 or 2 byte vInt prefix, starting @ start */- public BytesRef fillUsingLengthPrefix(BytesRef b, long start) {+ /**+ * Reads length as 1 or 2 byte vInt prefix, starting at <i>start</i>.+ * <p>+ * <b>Note:</b> this method does not support slices spanning across block+ * borders.+ * </p>+ *+ * @return the given {@link BytesRef}+ *+ * @lucene.internal+ **/+ public BytesRef fill(BytesRef b, long start) {final int index = (int) (start >> blockBits);final int offset = (int) (start & blockMask);final byte[] block = b.bytes = blocks[index];diff --cc lucene/src/test/org/apache/lucene/index/values/TestDocValues.javaindex 02a49ccd847,00000000000..94b247e3c36mode 100644,000000..100644--- a/lucene/src/test/org/apache/lucene/index/values/TestDocValues.java+++ b/lucene/src/test/org/apache/lucene/index/values/TestDocValues.java@@@ -1,325 -1,0 +1,319 @@@+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.IOException;+import java.util.Comparator;+import java.util.concurrent.atomic.AtomicLong;++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.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.UnicodeUtil;+import org.apache.lucene.util._TestUtil;++public class TestDocValues extends LuceneTestCase {++ // TODO -- for sorted test, do our own Sort of the+ // values and verify it's identical++ 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);+ }++ 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();+ final AtomicLong trackBytes = new AtomicLong(0);+ Writer w = Bytes.getWriter(dir, "test", mode, comp, fixedSize, trackBytes);+ 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);+ assertEquals(0, trackBytes.get());++ 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);++ BytesRef ref = bytesEnum.bytes();++ 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,+ bytesRef));+ assertEquals("doc " + idx, values[idx], s.getBytes(idx, bytesRef)+ .utf8ToString());+ if (ss != null) {+ assertEquals("doc " + idx, values[idx], ss.getByOrd(ss.ord(idx),+ bytesRef).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, bytesRef)));+ 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, bytesRef);+ // random string was before our first+ assertTrue(firstRef.compareTo(bytesValue) > 0);+ } else if (result.ord == numValues) {+ final BytesRef lastRef = ss.getByOrd(numValues, bytesRef);+ // 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,+ bytesRef).clone();+ final BytesRef after = ss.getByOrd(result.ord + 1, bytesRef);+ 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 = 777 + random.nextInt(777);+ final long[] values = new long[NUM_VALUES];+ for (int rx = 1; rx < 63; rx++, maxV *= 2) {+ Directory dir = newDirectory();+ final AtomicLong trackBytes = new AtomicLong(0);+ Writer w = Ints.getWriter(dir, "test", false, trackBytes);+ 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);+ assertEquals(0, trackBytes.get());+++ DocValues r = Ints.getValues(dir, "test", false);+ 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, values[i], v);+ }+ }++ for (int iter = 0; iter < 2; iter++) {+ ValuesEnum iEnum = r.getEnum();- ValuesAttribute attr = iEnum.addAttribute(ValuesAttribute.class);- LongsRef ints = attr.ints();++ LongsRef ints = iEnum.getInt();+ for (int i = 0; i < NUM_VALUES; i++) {+ assertEquals(i, iEnum.nextDoc());+ assertEquals(values[i], ints.get());+ }+ if (iEnum.docID() < NUM_VALUES - 1) {+ assertEquals(NUM_VALUES - 1, iEnum.advance(NUM_VALUES - 1));+ }+ for (int i = NUM_VALUES; i < NUM_VALUES + additionalDocs; i++) {+ assertEquals(ValuesEnum.NO_MORE_DOCS, iEnum.nextDoc());+ }++ iEnum.close();+ }++ for (int iter = 0; iter < 2; iter++) {+ ValuesEnum iEnum = r.getEnum();- ValuesAttribute attr = iEnum.addAttribute(ValuesAttribute.class);- LongsRef ints = attr.ints();++ LongsRef ints = iEnum.getInt();+ for (int i = 0; i < NUM_VALUES; i += 1 + random.nextInt(25)) {+ assertEquals(i, iEnum.advance(i));+ assertEquals(values[i], ints.get());+ }+ if (iEnum.docID() < NUM_VALUES - 1) {+ assertEquals(NUM_VALUES - 1, iEnum.advance(NUM_VALUES - 1));+ }+ for (int i = NUM_VALUES; i < NUM_VALUES + additionalDocs; i++) {+ assertEquals(ValuesEnum.NO_MORE_DOCS, iEnum.nextDoc());+ }++ 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();+ final AtomicLong trackBytes = new AtomicLong(0);+ Writer w = Floats.getWriter(dir, "test", precision, trackBytes);+ final int NUM_VALUES = 777 + random.nextInt(777);;+ 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);+ assertEquals(0, trackBytes.get());++ 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();+ FloatsRef floats = fEnum.getFloat();+ 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(ValuesEnum.NO_MORE_DOCS, fEnum.nextDoc());+ }+ fEnum.close();+ }+ for (int iter = 0; iter < 2; iter++) {+ ValuesEnum fEnum = r.getEnum();+ FloatsRef floats = fEnum.getFloat();+ 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(ValuesEnum.NO_MORE_DOCS, fEnum.advance(i));+ }+ fEnum.close();+ }++ r.close();+ dir.close();+ }++ public void testFloats8() throws IOException {+ runTestFloats(8, 0.0);+ }++ 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);+ }+}diff --cc lucene/src/test/org/apache/lucene/index/values/TestDocValuesIndexing.javaindex 9cca81fbec1,00000000000..5600b005bacmode 100644,000000..100644--- a/lucene/src/test/org/apache/lucene/index/values/TestDocValuesIndexing.java+++ b/lucene/src/test/org/apache/lucene/index/values/TestDocValuesIndexing.java@@@ -1,533 -1,0 +1,526 @@@+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.EnumSet;+import java.util.List;++import org.apache.lucene.analysis.MockAnalyzer;++import org.apache.lucene.document.AbstractField;+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.MissingValue;+import org.apache.lucene.index.values.DocValues.Source;+import org.apache.lucene.queryParser.ParseException;+import org.apache.lucene.queryParser.QueryParser;+import org.apache.lucene.search.IndexSearcher;+import org.apache.lucene.search.ScoreDoc;+import org.apache.lucene.search.TopDocs;+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._TestUtil;- import org.junit.AfterClass;- import org.junit.BeforeClass;++import org.junit.Before;++/**+ *+ * Tests DocValues integration into IndexWriter & Codecs+ *+ */+public class TestDocValuesIndexing extends LuceneTestCase {+ /*+ * TODO:+ * Roadmap to land on trunk- * - Cut over to a direct API on ValuesEnum vs. ValuesAttribute++ *+ * - Add documentation for:+ * - Source and ValuesEnum+ * - DocValues+ * - ValuesField+ * - ValuesAttribute+ * - Values+ * - Add @lucene.experimental to all necessary classes- * - Try to make ValuesField more lightweight -> AttributeSource+ * - add test for unoptimized case with deletes+ * - add a test for addIndexes+ * - split up existing testcases and give them meaningfull names+ * - use consistent naming throughout DocValues+ * - Values -> DocValueType+ * - PackedIntsImpl -> Ints+ * - run RAT+ * - add tests for FieldComparator FloatIndexValuesComparator vs. FloatValuesComparator etc.+ */+- private static DocValuesCodec docValuesCodec;- private static CodecProvider provider;++ private DocValuesCodec docValuesCodec;++ private CodecProvider provider;+- @BeforeClass- public static void beforeClassLuceneTestCaseJ4() {- LuceneTestCase.beforeClassLuceneTestCaseJ4();++ @Before++ public void setUp() throws Exception {++ super.setUp();++ String defaultFieldCodec = CodecProvider.getDefault().getDefaultFieldCodec();+ provider = new CodecProvider();- docValuesCodec = new DocValuesCodec(CodecProvider.getDefault().lookup(- CodecProvider.getDefaultCodec()));++ docValuesCodec = new DocValuesCodec(CodecProvider.getDefault().lookup(defaultFieldCodec));+ provider.register(docValuesCodec);+ provider.setDefaultFieldCodec(docValuesCodec.name);+ }-- @AfterClass- public static void afterClassLuceneTestCaseJ4() {- LuceneTestCase.afterClassLuceneTestCaseJ4();- }++++ /*+ * Simple test case to show how to use the API+ */+ public void testDocValuesSimple() throws CorruptIndexException, IOException, ParseException {+ Directory dir = newDirectory();+ IndexWriter writer = new IndexWriter(dir, writerConfig(false));+ for (int i = 0; i < 5; i++) {+ Document doc = new Document();+ ValuesField valuesField = new ValuesField("docId");+ valuesField.setInt(i);+ doc.add(valuesField);+ doc.add(new Field("docId", "" + i, Store.NO, Index.ANALYZED));+ writer.addDocument(doc);+ }+ writer.commit();+ writer.optimize(true);++ writer.close();++ IndexReader reader = IndexReader.open(dir, null, true, 1, provider);+ assertTrue(reader.isOptimized());++ IndexSearcher searcher = new IndexSearcher(reader);+ QueryParser parser = new QueryParser(TEST_VERSION_CURRENT, "docId", new MockAnalyzer());+ TopDocs search = searcher.search(parser.parse("0 OR 1 OR 2 OR 3 OR 4"), 10);+ assertEquals(5, search.totalHits);+ ScoreDoc[] scoreDocs = search.scoreDocs;+ DocValues docValues = MultiFields.getDocValues(reader, "docId");+ Source source = docValues.getSource();+ for (int i = 0; i < scoreDocs.length; i++) {+ assertEquals(i, scoreDocs[i].doc);+ assertEquals(i, source.getInt(scoreDocs[i].doc));+ }+ reader.close();+ dir.close();+ }++ /**+ * Tests complete indexing of {@link Values} including deletions, merging and+ * sparse value fields on Compound-File+ */+ public void testIndexBytesNoDeletesCFS() throws IOException {+ runTestIndexBytes(writerConfig(true), false);+ }++ public void testIndexBytesDeletesCFS() throws IOException {+ runTestIndexBytes(writerConfig(true), true);+ }++ public void testIndexNumericsNoDeletesCFS() throws IOException {+ runTestNumerics(writerConfig(true), false);+ }++ public void testIndexNumericsDeletesCFS() throws IOException {+ runTestNumerics(writerConfig(true), true);+ }++ /**+ * Tests complete indexing of {@link Values} including deletions, merging and+ * sparse value fields on None-Compound-File+ */+ public void testIndexBytesNoDeletes() throws IOException {+ runTestIndexBytes(writerConfig(false), false);+ }++ public void testIndexBytesDeletes() throws IOException {+ runTestIndexBytes(writerConfig(false), true);+ }++ public void testIndexNumericsNoDeletes() throws IOException {+ runTestNumerics(writerConfig(false), false);+ }++ public void testIndexNumericsDeletes() throws IOException {+ runTestNumerics(writerConfig(false), 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 = 179 + random.nextInt(151);+ 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: {+ DocValues intsReader = getDocValues(r, val.name());+ assertNotNull(intsReader);++ Source ints = getSource(intsReader);+ MissingValue missing = ints.getMissing();++ for (int i = 0; i < base; i++) {+ long value = ints.getInt(i);+ assertEquals("index " + i, missing.longValue, value);+ }++ ValuesEnum intsEnum = getValuesEnum(intsReader);+ assertTrue(intsEnum.advance(0) >= base);++ intsEnum = getValuesEnum(intsReader);+ LongsRef enumRef = intsEnum.getInt();++ 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);+ MissingValue missing = floats.getMissing();++ for (int i = 0; i < base; i++) {+ double value = floats.getFloat(i);+ assertEquals(" floats failed for doc: " + i + " base: " + base,+ missing.doubleValue, value, 0.0d);+ }+ ValuesEnum floatEnum = getValuesEnum(floatReader);+ assertTrue(floatEnum.advance(0) >= base);++ floatEnum = getValuesEnum(floatReader);+ FloatsRef enumRef = floatEnum.getFloat();+ 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(floatEnum.getClass() + " 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();+ }++ public void runTestIndexBytes(IndexWriterConfig cfg, boolean withDeletions)+ throws CorruptIndexException, LockObtainFailedException, IOException {+ final 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);+ byte upto = 0;++ // test the filled up slots for correctness+ MissingValue missing = bytes.getMissing();+ for (int i = 0; i < base; i++) {++ BytesRef br = bytes.getBytes(i, new BytesRef());+ String msg = " field: " + byteIndexValue.name() + " at index: " + i+ + " base: " + base + " numDocs:" + r.numDocs();+ switch (byteIndexValue) {+ case BYTES_VAR_STRAIGHT:+ case BYTES_FIXED_STRAIGHT:+ // fixed straight returns bytesref with zero bytes all of fixed+ // length+ if (missing.bytesValue != null) {+ 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]);+ }+ }+ } else {+ assertNull("expected null - " + msg + " " + br, br);+ }+ break;+ case BYTES_VAR_SORTED:+ case BYTES_FIXED_SORTED:+ case BYTES_VAR_DEREF:+ case BYTES_FIXED_DEREF:+ default:+ assertNull("expected null - " + msg + " " + br, br);+ // make sure we advance at least until base+ ValuesEnum bytesEnum = getValuesEnum(bytesReader);+ final int advancedTo = bytesEnum.advance(0);+ assertTrue(byteIndexValue.name() + " advanced failed base:" + base+ + " advancedTo: " + advancedTo, base <= advancedTo);++ }+ }++ ValuesEnum bytesEnum = getValuesEnum(bytesReader);+ final BytesRef enumRef = bytesEnum.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, new BytesRef());+ if (bytesEnum.docID() != i) {+ assertEquals("seek failed for index " + i + " " + msg, i, bytesEnum+ .advance(i));+ }+ for (int j = 0; j < br.length; j++, upto++) {++ assertTrue(bytesEnum.getClass() + " enumRef not initialized " + msg, enumRef.bytes.length > 0);+ assertEquals(+ "EnumRef Byte at index " + j + " doesn't match - " + msg, upto,+ enumRef.bytes[enumRef.offset + j]);+ if (!(br.bytes.length > br.offset + j))+ br = bytes.getBytes(i, new BytesRef());+ assertTrue("BytesRef index exceeded [" + msg + "] offset: "+ + br.offset + " length: " + br.length + " index: "+ + (br.offset + j), br.bytes.length > br.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 {+ Source source;+ if (random.nextInt(10) == 0) {+ source = values.load();+ } else {+ // getSource uses cache internally+ source = values.getSource();+ }+ assertNotNull(source);+ return source;+ }++ private ValuesEnum getValuesEnum(DocValues values) throws IOException {+ ValuesEnum valuesEnum;+ if (!(values instanceof MultiDocValues) && random.nextInt(10) == 0) {+ // TODO not supported by MultiDocValues yet!+ valuesEnum = getSource(values).getEnum();+ } else {+ valuesEnum = values.getEnum();++ }+ assertNotNull(valuesEnum);+ return valuesEnum;+ }++ 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.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())++ AbstractField 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();++ ValuesField valField = new ValuesField("prototype");++ final BytesRef bytesRef = new BytesRef();++ 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:- intsRef.set(i);++ valField.setInt(i);+ break;+ case SIMPLE_FLOAT_4BYTE:+ case SIMPLE_FLOAT_8BYTE:- floatsRef.set(2.0f * i);++ valField.setFloat(2.0f * i);+ break;+ default:+ fail("unexpected value " + value);+ }+ } else {+ for (int j = 0; j < b.length; j++) {+ b[j] = upto++;+ }++ valField.setBytes(bytesRef, value);+ }+ doc.removeFields("id");+ doc.add(new Field("id", idBase + i, Store.YES,+ Index.NOT_ANALYZED_NO_NORMS));++ valField.set(field);+ 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);+ }+ }+ if (random.nextInt(10) == 0) {+ w.commit();+ }+ }+ }+ w.commit();++ // TODO test unoptimized with deletions+ if (withDeletions || random.nextBoolean())+ w.optimize();+ return deleted;+ }++}