Apache Solr open-source search software
SOLR-4490: multi-valued dv support
Robert Muird09ba0c912a2
diff --git a/lucene/core/src/java/org/apache/lucene/index/MultiDocValues.java b/lucene/core/src/java/org/apache/lucene/index/MultiDocValues.javaindex 97f2eecf9ff..5a9c76333c6 100644--- a/lucene/core/src/java/org/apache/lucene/index/MultiDocValues.java+++ b/lucene/core/src/java/org/apache/lucene/index/MultiDocValues.java@@ -362,12 +362,19 @@ public class MultiDocValues {}}- /** implements SortedDocValues over n subs, using an OrdinalMap */- static class MultiSortedDocValues extends SortedDocValues {- final int docStarts[];- final SortedDocValues values[];- final OrdinalMap mapping;+ /**+ * Implements SortedDocValues over n subs, using an OrdinalMap+ * @lucene.internal+ */+ public static class MultiSortedDocValues extends SortedDocValues {+ /** docbase for each leaf: parallel with {@link #values} */+ public final int docStarts[];+ /** leaf values */+ public final SortedDocValues values[];+ /** ordinal map mapping ords from <code>values</code> to global ord space */+ public final OrdinalMap mapping;+ /** Creates a new MultiSortedDocValues over <code>values</code> */MultiSortedDocValues(SortedDocValues values[], int docStarts[], OrdinalMap mapping) throws IOException {assert values.length == mapping.ordDeltas.length;assert docStarts.length == values.length + 1;@@ -396,13 +403,20 @@ public class MultiDocValues {}}- /** implements MultiSortedDocValues over n subs, using an OrdinalMap */- static class MultiSortedSetDocValues extends SortedSetDocValues {- final int docStarts[];- final SortedSetDocValues values[];- final OrdinalMap mapping;+ /**+ * Implements MultiSortedSetDocValues over n subs, using an OrdinalMap+ * @lucene.internal+ */+ public static class MultiSortedSetDocValues extends SortedSetDocValues {+ /** docbase for each leaf: parallel with {@link #values} */+ public final int docStarts[];+ /** leaf values */+ public final SortedSetDocValues values[];+ /** ordinal map mapping ords from <code>values</code> to global ord space */+ public final OrdinalMap mapping;int currentSubIndex;+ /** Creates a new MultiSortedSetDocValues over <code>values</code> */MultiSortedSetDocValues(SortedSetDocValues values[], int docStarts[], OrdinalMap mapping) throws IOException {assert values.length == mapping.ordDeltas.length;assert docStarts.length == values.length + 1;diff --git a/lucene/core/src/java/org/apache/lucene/search/DocTermOrdsRangeFilter.java b/lucene/core/src/java/org/apache/lucene/search/DocTermOrdsRangeFilter.javanew file mode 100644index 00000000000..07e2cba9e73--- /dev/null+++ b/lucene/core/src/java/org/apache/lucene/search/DocTermOrdsRangeFilter.java@@ -0,0 +1,167 @@+package org.apache.lucene.search;+/*+ * 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.AtomicReaderContext;+import org.apache.lucene.index.SortedSetDocValues;+import org.apache.lucene.util.Bits;+import org.apache.lucene.util.BytesRef;++/**+ * A range filter built on top of a cached multi-valued term field (in {@link FieldCache}).+ *+ * <p>Like {@link FieldCacheRangeFilter}, this is just a specialized range query versus+ * using a TermRangeQuery with {@link DocTermOrdsRewriteMethod}: it will only do+ * two ordinal to term lookups.</p>+ */++public abstract class DocTermOrdsRangeFilter extends Filter {+ final String field;+ final BytesRef lowerVal;+ final BytesRef upperVal;+ final boolean includeLower;+ final boolean includeUpper;++ private DocTermOrdsRangeFilter(String field, BytesRef lowerVal, BytesRef upperVal, boolean includeLower, boolean includeUpper) {+ this.field = field;+ this.lowerVal = lowerVal;+ this.upperVal = upperVal;+ this.includeLower = includeLower;+ this.includeUpper = includeUpper;+ }++ /** This method is implemented for each data type */+ @Override+ public abstract DocIdSet getDocIdSet(AtomicReaderContext context, Bits acceptDocs) throws IOException;++ /**+ * Creates a BytesRef range filter using {@link FieldCache#getTermsIndex}. This works with all+ * fields containing zero or one term in the field. The range can be half-open by setting one+ * of the values to <code>null</code>.+ */+ public static DocTermOrdsRangeFilter newBytesRefRange(String field, BytesRef lowerVal, BytesRef upperVal, boolean includeLower, boolean includeUpper) {+ return new DocTermOrdsRangeFilter(field, lowerVal, upperVal, includeLower, includeUpper) {+ @Override+ public DocIdSet getDocIdSet(AtomicReaderContext context, Bits acceptDocs) throws IOException {+ final SortedSetDocValues docTermOrds = FieldCache.DEFAULT.getDocTermOrds(context.reader(), field);+ final long lowerPoint = lowerVal == null ? -1 : docTermOrds.lookupTerm(lowerVal);+ final long upperPoint = upperVal == null ? -1 : docTermOrds.lookupTerm(upperVal);++ final long inclusiveLowerPoint, inclusiveUpperPoint;++ // Hints:+ // * binarySearchLookup returns -1, if value was null.+ // * the value is <0 if no exact hit was found, the returned value+ // is (-(insertion point) - 1)+ if (lowerPoint == -1 && lowerVal == null) {+ inclusiveLowerPoint = 0;+ } else if (includeLower && lowerPoint >= 0) {+ inclusiveLowerPoint = lowerPoint;+ } else if (lowerPoint >= 0) {+ inclusiveLowerPoint = lowerPoint + 1;+ } else {+ inclusiveLowerPoint = Math.max(0, -lowerPoint - 1);+ }++ if (upperPoint == -1 && upperVal == null) {+ inclusiveUpperPoint = Long.MAX_VALUE;+ } else if (includeUpper && upperPoint >= 0) {+ inclusiveUpperPoint = upperPoint;+ } else if (upperPoint >= 0) {+ inclusiveUpperPoint = upperPoint - 1;+ } else {+ inclusiveUpperPoint = -upperPoint - 2;+ }++ if (inclusiveUpperPoint < 0 || inclusiveLowerPoint > inclusiveUpperPoint) {+ return DocIdSet.EMPTY_DOCIDSET;+ }++ assert inclusiveLowerPoint >= 0 && inclusiveUpperPoint >= 0;++ return new FieldCacheDocIdSet(context.reader().maxDoc(), acceptDocs) {+ @Override+ protected final boolean matchDoc(int doc) {+ docTermOrds.setDocument(doc);+ long ord;+ while ((ord = docTermOrds.nextOrd()) != SortedSetDocValues.NO_MORE_ORDS) {+ if (ord > inclusiveUpperPoint) {+ return false;+ } else if (ord >= inclusiveLowerPoint) {+ return true;+ }+ }+ return false;+ }+ };+ }+ };+ }++ @Override+ public final String toString() {+ final StringBuilder sb = new StringBuilder(field).append(":");+ return sb.append(includeLower ? '[' : '{')+ .append((lowerVal == null) ? "*" : lowerVal.toString())+ .append(" TO ")+ .append((upperVal == null) ? "*" : upperVal.toString())+ .append(includeUpper ? ']' : '}')+ .toString();+ }++ @Override+ public final boolean equals(Object o) {+ if (this == o) return true;+ if (!(o instanceof DocTermOrdsRangeFilter)) return false;+ DocTermOrdsRangeFilter other = (DocTermOrdsRangeFilter) o;++ if (!this.field.equals(other.field)+ || this.includeLower != other.includeLower+ || this.includeUpper != other.includeUpper+ ) { return false; }+ if (this.lowerVal != null ? !this.lowerVal.equals(other.lowerVal) : other.lowerVal != null) return false;+ if (this.upperVal != null ? !this.upperVal.equals(other.upperVal) : other.upperVal != null) return false;+ return true;+ }++ @Override+ public final int hashCode() {+ int h = field.hashCode();+ h ^= (lowerVal != null) ? lowerVal.hashCode() : 550356204;+ h = (h << 1) | (h >>> 31); // rotate to distinguish lower from upper+ h ^= (upperVal != null) ? upperVal.hashCode() : -1674416163;+ h ^= (includeLower ? 1549299360 : -365038026) ^ (includeUpper ? 1721088258 : 1948649653);+ return h;+ }++ /** Returns the field name for this filter */+ public String getField() { return field; }++ /** Returns <code>true</code> if the lower endpoint is inclusive */+ public boolean includesLower() { return includeLower; }++ /** Returns <code>true</code> if the upper endpoint is inclusive */+ public boolean includesUpper() { return includeUpper; }++ /** Returns the lower value of this range filter */+ public BytesRef getLowerVal() { return lowerVal; }++ /** Returns the upper value of this range filter */+ public BytesRef getUpperVal() { return upperVal; }+}diff --git a/lucene/core/src/java/org/apache/lucene/search/DocTermOrdsRewriteMethod.java b/lucene/core/src/java/org/apache/lucene/search/DocTermOrdsRewriteMethod.javanew file mode 100644index 00000000000..68ef562c7e0--- /dev/null+++ b/lucene/core/src/java/org/apache/lucene/search/DocTermOrdsRewriteMethod.java@@ -0,0 +1,166 @@+package org.apache.lucene.search;++/*+ * 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.AtomicReaderContext;+import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.SortedSetDocValues;+import org.apache.lucene.index.SortedSetDocValuesTermsEnum;+import org.apache.lucene.index.Terms;+import org.apache.lucene.index.TermsEnum;+import org.apache.lucene.util.Bits;+import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.OpenBitSet;++/**+ * Rewrites MultiTermQueries into a filter, using DocTermOrds for term enumeration.+ * <p>+ * This can be used to perform these queries against an unindexed docvalues field.+ * @lucene.experimental+ */+public final class DocTermOrdsRewriteMethod extends MultiTermQuery.RewriteMethod {++ @Override+ public Query rewrite(IndexReader reader, MultiTermQuery query) {+ Query result = new ConstantScoreQuery(new MultiTermQueryDocTermOrdsWrapperFilter(query));+ result.setBoost(query.getBoost());+ return result;+ }++ static class MultiTermQueryDocTermOrdsWrapperFilter extends Filter {++ protected final MultiTermQuery query;++ /**+ * Wrap a {@link MultiTermQuery} as a Filter.+ */+ protected MultiTermQueryDocTermOrdsWrapperFilter(MultiTermQuery query) {+ this.query = query;+ }++ @Override+ public String toString() {+ // query.toString should be ok for the filter, too, if the query boost is 1.0f+ return query.toString();+ }++ @Override+ public final boolean equals(final Object o) {+ if (o==this) return true;+ if (o==null) return false;+ if (this.getClass().equals(o.getClass())) {+ return this.query.equals( ((MultiTermQueryDocTermOrdsWrapperFilter)o).query );+ }+ return false;+ }++ @Override+ public final int hashCode() {+ return query.hashCode();+ }++ /** Returns the field name for this query */+ public final String getField() { return query.getField(); }++ /**+ * Returns a DocIdSet with documents that should be permitted in search+ * results.+ */+ @Override+ public DocIdSet getDocIdSet(AtomicReaderContext context, final Bits acceptDocs) throws IOException {+ final SortedSetDocValues docTermOrds = FieldCache.DEFAULT.getDocTermOrds(context.reader(), query.field);+ // Cannot use FixedBitSet because we require long index (ord):+ final OpenBitSet termSet = new OpenBitSet(docTermOrds.getValueCount());+ TermsEnum termsEnum = query.getTermsEnum(new Terms() {++ @Override+ public Comparator<BytesRef> getComparator() {+ return BytesRef.getUTF8SortedAsUnicodeComparator();+ }++ @Override+ public TermsEnum iterator(TermsEnum reuse) {+ return new SortedSetDocValuesTermsEnum(docTermOrds);+ }++ @Override+ public long getSumTotalTermFreq() {+ return -1;+ }++ @Override+ public long getSumDocFreq() {+ return -1;+ }++ @Override+ public int getDocCount() {+ return -1;+ }++ @Override+ public long size() {+ return -1;+ }++ @Override+ public boolean hasOffsets() {+ return false;+ }++ @Override+ public boolean hasPositions() {+ return false;+ }++ @Override+ public boolean hasPayloads() {+ return false;+ }+ });++ assert termsEnum != null;+ if (termsEnum.next() != null) {+ // fill into a OpenBitSet+ do {+ termSet.set(termsEnum.ord());+ } while (termsEnum.next() != null);+ } else {+ return DocIdSet.EMPTY_DOCIDSET;+ }++ return new FieldCacheDocIdSet(context.reader().maxDoc(), acceptDocs) {+ @Override+ protected final boolean matchDoc(int doc) throws ArrayIndexOutOfBoundsException {+ docTermOrds.setDocument(doc);+ long ord;+ // TODO: we could track max bit set and early terminate (since they come in sorted order)+ while ((ord = docTermOrds.nextOrd()) != SortedSetDocValues.NO_MORE_ORDS) {+ if (termSet.get(ord)) {+ return true;+ }+ }+ return false;+ }+ };+ }+ }+}diff --git a/lucene/core/src/test/org/apache/lucene/search/TestDocTermOrdsRangeFilter.java b/lucene/core/src/test/org/apache/lucene/search/TestDocTermOrdsRangeFilter.javanew file mode 100644index 00000000000..89d2b70ee81--- /dev/null+++ b/lucene/core/src/test/org/apache/lucene/search/TestDocTermOrdsRangeFilter.java@@ -0,0 +1,129 @@+package org.apache.lucene.search;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.IOException;+import java.util.ArrayList;+import java.util.Collections;+import java.util.List;++import org.apache.lucene.analysis.MockAnalyzer;+import org.apache.lucene.analysis.MockTokenizer;+import org.apache.lucene.document.Document;+import org.apache.lucene.document.Field;+import org.apache.lucene.document.SortedSetDocValuesField;+import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.RandomIndexWriter;+import org.apache.lucene.index.Term;+import org.apache.lucene.store.Directory;+import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.LuceneTestCase;+import org.apache.lucene.util.UnicodeUtil;+import org.apache.lucene.util._TestUtil;++/**+ * Tests the DocTermOrdsRangeFilter+ */+public class TestDocTermOrdsRangeFilter extends LuceneTestCase {+ protected IndexSearcher searcher1;+ protected IndexSearcher searcher2;+ private IndexReader reader;+ private Directory dir;+ protected String fieldName;++ @Override+ public void setUp() throws Exception {+ super.setUp();+ dir = newDirectory();+ fieldName = random().nextBoolean() ? "field" : ""; // sometimes use an empty string as field name+ RandomIndexWriter writer = new RandomIndexWriter(random(), dir,+ newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random(), MockTokenizer.KEYWORD, false))+ .setMaxBufferedDocs(_TestUtil.nextInt(random(), 50, 1000)));+ List<String> terms = new ArrayList<String>();+ int num = atLeast(200);+ for (int i = 0; i < num; i++) {+ Document doc = new Document();+ doc.add(newStringField("id", Integer.toString(i), Field.Store.NO));+ int numTerms = random().nextInt(4);+ for (int j = 0; j < numTerms; j++) {+ String s = _TestUtil.randomUnicodeString(random());+ doc.add(newStringField(fieldName, s, Field.Store.NO));+ // if the default codec doesn't support sortedset, we will uninvert at search time+ if (defaultCodecSupportsSortedSet()) {+ doc.add(new SortedSetDocValuesField(fieldName, new BytesRef(s)));+ }+ terms.add(s);+ }+ writer.addDocument(doc);+ }++ if (VERBOSE) {+ // utf16 order+ Collections.sort(terms);+ System.out.println("UTF16 order:");+ for(String s : terms) {+ System.out.println(" " + UnicodeUtil.toHexString(s));+ }+ }++ int numDeletions = random().nextInt(num/10);+ for (int i = 0; i < numDeletions; i++) {+ writer.deleteDocuments(new Term("id", Integer.toString(random().nextInt(num))));+ }++ reader = writer.getReader();+ searcher1 = newSearcher(reader);+ searcher2 = newSearcher(reader);+ writer.close();+ }++ @Override+ public void tearDown() throws Exception {+ reader.close();+ dir.close();+ super.tearDown();+ }++ /** test a bunch of random ranges */+ public void testRanges() throws Exception {+ int num = atLeast(1000);+ for (int i = 0; i < num; i++) {+ BytesRef lowerVal = new BytesRef(_TestUtil.randomUnicodeString(random()));+ BytesRef upperVal = new BytesRef(_TestUtil.randomUnicodeString(random()));+ if (upperVal.compareTo(lowerVal) < 0) {+ assertSame(upperVal, lowerVal, random().nextBoolean(), random().nextBoolean());+ } else {+ assertSame(lowerVal, upperVal, random().nextBoolean(), random().nextBoolean());+ }+ }+ }++ /** check that the # of hits is the same as if the query+ * is run against the inverted index+ */+ protected void assertSame(BytesRef lowerVal, BytesRef upperVal, boolean includeLower, boolean includeUpper) throws IOException {+ Query docValues = new ConstantScoreQuery(DocTermOrdsRangeFilter.newBytesRefRange(fieldName, lowerVal, upperVal, includeLower, includeUpper));+ MultiTermQuery inverted = new TermRangeQuery(fieldName, lowerVal, upperVal, includeLower, includeUpper);+ inverted.setRewriteMethod(MultiTermQuery.CONSTANT_SCORE_FILTER_REWRITE);++ TopDocs invertedDocs = searcher1.search(inverted, 25);+ TopDocs docValuesDocs = searcher2.search(docValues, 25);++ CheckHits.checkEqual(inverted, invertedDocs.scoreDocs, docValuesDocs.scoreDocs);+ }+}diff --git a/lucene/core/src/test/org/apache/lucene/search/TestDocTermOrdsRewriteMethod.java b/lucene/core/src/test/org/apache/lucene/search/TestDocTermOrdsRewriteMethod.javanew file mode 100644index 00000000000..a8bc0e48cb1--- /dev/null+++ b/lucene/core/src/test/org/apache/lucene/search/TestDocTermOrdsRewriteMethod.java@@ -0,0 +1,129 @@+package org.apache.lucene.search;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.IOException;+import java.util.ArrayList;+import java.util.Collections;+import java.util.List;++import org.apache.lucene.analysis.MockAnalyzer;+import org.apache.lucene.analysis.MockTokenizer;+import org.apache.lucene.document.Document;+import org.apache.lucene.document.Field;+import org.apache.lucene.document.SortedSetDocValuesField;+import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.RandomIndexWriter;+import org.apache.lucene.index.Term;+import org.apache.lucene.store.Directory;+import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.LuceneTestCase;+import org.apache.lucene.util.automaton.AutomatonTestUtil;+import org.apache.lucene.util.automaton.RegExp;+import org.apache.lucene.util.UnicodeUtil;+import org.apache.lucene.util._TestUtil;++/**+ * Tests the DocTermOrdsRewriteMethod+ */+public class TestDocTermOrdsRewriteMethod extends LuceneTestCase {+ protected IndexSearcher searcher1;+ protected IndexSearcher searcher2;+ private IndexReader reader;+ private Directory dir;+ protected String fieldName;++ @Override+ public void setUp() throws Exception {+ super.setUp();+ dir = newDirectory();+ fieldName = random().nextBoolean() ? "field" : ""; // sometimes use an empty string as field name+ RandomIndexWriter writer = new RandomIndexWriter(random(), dir,+ newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random(), MockTokenizer.KEYWORD, false))+ .setMaxBufferedDocs(_TestUtil.nextInt(random(), 50, 1000)));+ List<String> terms = new ArrayList<String>();+ int num = atLeast(200);+ for (int i = 0; i < num; i++) {+ Document doc = new Document();+ doc.add(newStringField("id", Integer.toString(i), Field.Store.NO));+ int numTerms = random().nextInt(4);+ for (int j = 0; j < numTerms; j++) {+ String s = _TestUtil.randomUnicodeString(random());+ doc.add(newStringField(fieldName, s, Field.Store.NO));+ // if the default codec doesn't support sortedset, we will uninvert at search time+ if (defaultCodecSupportsSortedSet()) {+ doc.add(new SortedSetDocValuesField(fieldName, new BytesRef(s)));+ }+ terms.add(s);+ }+ writer.addDocument(doc);+ }++ if (VERBOSE) {+ // utf16 order+ Collections.sort(terms);+ System.out.println("UTF16 order:");+ for(String s : terms) {+ System.out.println(" " + UnicodeUtil.toHexString(s));+ }+ }++ int numDeletions = random().nextInt(num/10);+ for (int i = 0; i < numDeletions; i++) {+ writer.deleteDocuments(new Term("id", Integer.toString(random().nextInt(num))));+ }++ reader = writer.getReader();+ searcher1 = newSearcher(reader);+ searcher2 = newSearcher(reader);+ writer.close();+ }++ @Override+ public void tearDown() throws Exception {+ reader.close();+ dir.close();+ super.tearDown();+ }++ /** test a bunch of random regular expressions */+ public void testRegexps() throws Exception {+ int num = atLeast(1000);+ for (int i = 0; i < num; i++) {+ String reg = AutomatonTestUtil.randomRegexp(random());+ if (VERBOSE) {+ System.out.println("TEST: regexp=" + reg);+ }+ assertSame(reg);+ }+ }++ /** check that the # of hits is the same as if the query+ * is run against the inverted index+ */+ protected void assertSame(String regexp) throws IOException {+ RegexpQuery docValues = new RegexpQuery(new Term(fieldName, regexp), RegExp.NONE);+ docValues.setRewriteMethod(new DocTermOrdsRewriteMethod());+ RegexpQuery inverted = new RegexpQuery(new Term(fieldName, regexp), RegExp.NONE);++ TopDocs invertedDocs = searcher1.search(inverted, 25);+ TopDocs docValuesDocs = searcher2.search(docValues, 25);++ CheckHits.checkEqual(inverted, invertedDocs.scoreDocs, docValuesDocs.scoreDocs);+ }+}diff --git a/solr/CHANGES.txt b/solr/CHANGES.txtindex bb81e1e50f5..e058ff2b91c 100644--- a/solr/CHANGES.txt+++ b/solr/CHANGES.txt@@ -71,7 +71,7 @@ New Featuresunder the covers -- allowing many HTTP connection related properties to becontrolled via 'standard' java system properties. (hossman)-* SOLR-3855: Doc values support. (Adrien Grand)+* SOLR-3855, SOLR-4490: Doc values support. (Adrien Grand, Robert Muir)* SOLR-4417: Reopen the IndexWriter on SolrCore reload. (Mark Miller)diff --git a/solr/core/src/java/org/apache/solr/request/DocValuesFacets.java b/solr/core/src/java/org/apache/solr/request/DocValuesFacets.javanew file mode 100644index 00000000000..4dfc114a189--- /dev/null+++ b/solr/core/src/java/org/apache/solr/request/DocValuesFacets.java@@ -0,0 +1,270 @@+package org.apache.solr.request;++/*+ * 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.List;++import org.apache.lucene.index.AtomicReaderContext;+import org.apache.lucene.index.MultiDocValues.MultiSortedDocValues;+import org.apache.lucene.index.MultiDocValues.MultiSortedSetDocValues;+import org.apache.lucene.index.MultiDocValues.OrdinalMap;+import org.apache.lucene.index.SingletonSortedSetDocValues;+import org.apache.lucene.index.SortedDocValues;+import org.apache.lucene.index.SortedSetDocValues;+import org.apache.lucene.search.DocIdSet;+import org.apache.lucene.search.DocIdSetIterator;+import org.apache.lucene.search.Filter;+import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.CharsRef;+import org.apache.lucene.util.UnicodeUtil;+import org.apache.solr.common.params.FacetParams;+import org.apache.solr.common.util.NamedList;+import org.apache.solr.schema.FieldType;+import org.apache.solr.schema.SchemaField;+import org.apache.solr.search.DocSet;+import org.apache.solr.search.SolrIndexSearcher;+import org.apache.solr.util.LongPriorityQueue;++/**+ * Computes term facets for docvalues field (single or multivalued).+ * <p>+ * This is basically a specialized case of the code in SimpleFacets.+ * Instead of working on a top-level reader view (binary-search per docid),+ * it collects per-segment, but maps ordinals to global ordinal space using+ * MultiDocValues' OrdinalMap.+ * <p>+ * This means the ordinal map is created per-reopen: O(nterms), but this may+ * perform better than PerSegmentSingleValuedFaceting which has to merge O(nterms)+ * per query. Additionally it works for multi-valued fields.+ */+public class DocValuesFacets {+ private DocValuesFacets() {}++ public static NamedList<Integer> getCounts(SolrIndexSearcher searcher, DocSet docs, String fieldName, int offset, int limit, int mincount, boolean missing, String sort, String prefix) throws IOException {+ SchemaField schemaField = searcher.getSchema().getField(fieldName);+ FieldType ft = schemaField.getType();+ NamedList<Integer> res = new NamedList<Integer>();++ final SortedSetDocValues si; // for term lookups only+ OrdinalMap ordinalMap = null; // for mapping per-segment ords to global ones+ if (schemaField.multiValued()) {+ si = searcher.getAtomicReader().getSortedSetDocValues(fieldName);+ if (si instanceof MultiSortedSetDocValues) {+ ordinalMap = ((MultiSortedSetDocValues)si).mapping;+ }+ } else {+ SortedDocValues single = searcher.getAtomicReader().getSortedDocValues(fieldName);+ si = single == null ? null : new SingletonSortedSetDocValues(single);+ if (single instanceof MultiSortedDocValues) {+ ordinalMap = ((MultiSortedDocValues)single).mapping;+ }+ }+ if (si == null) {+ return finalize(res, searcher, schemaField, docs, -1, missing);+ }+ if (si.getValueCount() >= Integer.MAX_VALUE) {+ throw new UnsupportedOperationException("Currently this faceting method is limited to " + Integer.MAX_VALUE + " unique terms");+ }++ final BytesRef br = new BytesRef();++ final BytesRef prefixRef;+ if (prefix == null) {+ prefixRef = null;+ } else if (prefix.length()==0) {+ prefix = null;+ prefixRef = null;+ } else {+ prefixRef = new BytesRef(prefix);+ }++ int startTermIndex, endTermIndex;+ if (prefix!=null) {+ startTermIndex = (int) si.lookupTerm(prefixRef);+ if (startTermIndex<0) startTermIndex=-startTermIndex-1;+ prefixRef.append(UnicodeUtil.BIG_TERM);+ endTermIndex = (int) si.lookupTerm(prefixRef);+ assert endTermIndex < 0;+ endTermIndex = -endTermIndex-1;+ } else {+ startTermIndex=-1;+ endTermIndex=(int) si.getValueCount();+ }++ final int nTerms=endTermIndex-startTermIndex;+ int missingCount = -1;+ final CharsRef charsRef = new CharsRef(10);+ if (nTerms>0 && docs.size() >= mincount) {++ // count collection array only needs to be as big as the number of terms we are+ // going to collect counts for.+ final int[] counts = new int[nTerms];++ Filter filter = docs.getTopFilter();+ List<AtomicReaderContext> leaves = searcher.getTopReaderContext().leaves();+ for (int subIndex = 0; subIndex < leaves.size(); subIndex++) {+ AtomicReaderContext leaf = leaves.get(subIndex);+ DocIdSet dis = filter.getDocIdSet(leaf, null); // solr docsets already exclude any deleted docs+ DocIdSetIterator disi = null;+ if (dis != null) {+ disi = dis.iterator();+ }+ if (disi != null) {+ if (schemaField.multiValued()) {+ SortedSetDocValues sub = leaf.reader().getSortedSetDocValues(fieldName);+ if (sub == null) {+ sub = SortedSetDocValues.EMPTY;+ }+ accumMulti(counts, startTermIndex, sub, disi, subIndex, ordinalMap);+ } else {+ SortedDocValues sub = leaf.reader().getSortedDocValues(fieldName);+ if (sub == null) {+ sub = SortedDocValues.EMPTY;+ }+ accumSingle(counts, startTermIndex, sub, disi, subIndex, ordinalMap);+ }+ }+ }++ if (startTermIndex == -1) {+ missingCount = counts[0];+ }++ // IDEA: we could also maintain a count of "other"... everything that fell outside+ // of the top 'N'++ int off=offset;+ int lim=limit>=0 ? limit : Integer.MAX_VALUE;++ if (sort.equals(FacetParams.FACET_SORT_COUNT) || sort.equals(FacetParams.FACET_SORT_COUNT_LEGACY)) {+ int maxsize = limit>0 ? offset+limit : Integer.MAX_VALUE-1;+ maxsize = Math.min(maxsize, nTerms);+ LongPriorityQueue queue = new LongPriorityQueue(Math.min(maxsize,1000), maxsize, Long.MIN_VALUE);++ int min=mincount-1; // the smallest value in the top 'N' values+ for (int i=(startTermIndex==-1)?1:0; i<nTerms; i++) {+ int c = counts[i];+ if (c>min) {+ // NOTE: we use c>min rather than c>=min as an optimization because we are going in+ // index order, so we already know that the keys are ordered. This can be very+ // important if a lot of the counts are repeated (like zero counts would be).++ // smaller term numbers sort higher, so subtract the term number instead+ long pair = (((long)c)<<32) + (Integer.MAX_VALUE - i);+ boolean displaced = queue.insert(pair);+ if (displaced) min=(int)(queue.top() >>> 32);+ }+ }++ // if we are deep paging, we don't have to order the highest "offset" counts.+ int collectCount = Math.max(0, queue.size() - off);+ assert collectCount <= lim;++ // the start and end indexes of our list "sorted" (starting with the highest value)+ int sortedIdxStart = queue.size() - (collectCount - 1);+ int sortedIdxEnd = queue.size() + 1;+ final long[] sorted = queue.sort(collectCount);++ for (int i=sortedIdxStart; i<sortedIdxEnd; i++) {+ long pair = sorted[i];+ int c = (int)(pair >>> 32);+ int tnum = Integer.MAX_VALUE - (int)pair;+ si.lookupOrd(startTermIndex+tnum, br);+ ft.indexedToReadable(br, charsRef);+ res.add(charsRef.toString(), c);+ }++ } else {+ // add results in index order+ int i=(startTermIndex==-1)?1:0;+ if (mincount<=0) {+ // if mincount<=0, then we won't discard any terms and we know exactly+ // where to start.+ i+=off;+ off=0;+ }++ for (; i<nTerms; i++) {+ int c = counts[i];+ if (c<mincount || --off>=0) continue;+ if (--lim<0) break;+ si.lookupOrd(startTermIndex+i, br);+ ft.indexedToReadable(br, charsRef);+ res.add(charsRef.toString(), c);+ }+ }+ }++ return finalize(res, searcher, schemaField, docs, missingCount, missing);+ }++ /** finalizes result: computes missing count if applicable */+ static NamedList<Integer> finalize(NamedList<Integer> res, SolrIndexSearcher searcher, SchemaField schemaField, DocSet docs, int missingCount, boolean missing) throws IOException {+ if (missing) {+ if (missingCount < 0) {+ if (schemaField.multiValued()) {+ missingCount = SimpleFacets.getFieldMissingCount(searcher,docs,schemaField.getName());+ } else {+ missingCount = 0; // single-valued dv is implicitly 0+ }+ }+ res.add(null, missingCount);+ }++ return res;+ }++ /** accumulates per-segment single-valued facet counts, mapping to global ordinal space */+ // specialized since the single-valued case is simpler: you don't have to deal with missing count, etc+ static void accumSingle(int counts[], int startTermIndex, SortedDocValues si, DocIdSetIterator disi, int subIndex, OrdinalMap map) throws IOException {+ int doc;+ while ((doc = disi.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {+ int term = si.getOrd(doc);+ if (map != null) {+ term = (int) map.getGlobalOrd(subIndex, term);+ }+ int arrIdx = term-startTermIndex;+ if (arrIdx>=0 && arrIdx<counts.length) counts[arrIdx]++;+ }+ }++ /** accumulates per-segment multi-valued facet counts, mapping to global ordinal space */+ static void accumMulti(int counts[], int startTermIndex, SortedSetDocValues si, DocIdSetIterator disi, int subIndex, OrdinalMap map) throws IOException {+ int doc;+ while ((doc = disi.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {+ si.setDocument(doc);+ // strange do-while to collect the missing count (first ord is NO_MORE_ORDS)+ int term = (int) si.nextOrd();+ if (term < 0) {+ if (startTermIndex == -1) {+ counts[0]++; // missing count+ }+ continue;+ }++ do {+ if (map != null) {+ term = (int) map.getGlobalOrd(subIndex, term);+ }+ int arrIdx = term-startTermIndex;+ if (arrIdx>=0 && arrIdx<counts.length) counts[arrIdx]++;+ } while ((term = (int) si.nextOrd()) >= 0);+ }+ }+}diff --git a/solr/core/src/java/org/apache/solr/request/SimpleFacets.java b/solr/core/src/java/org/apache/solr/request/SimpleFacets.javaindex 49a6c67d4bb..88043d5f9d2 100644--- a/solr/core/src/java/org/apache/solr/request/SimpleFacets.java+++ b/solr/core/src/java/org/apache/solr/request/SimpleFacets.java@@ -389,6 +389,11 @@ public class SimpleFacets {// only fc knows how to deal with multi-token fieldsmethod = FacetMethod.FC;}++ if (method == FacetMethod.ENUM && sf.hasDocValues()) {+ // only fc can handle docvalues types+ method = FacetMethod.FC;+ }if (params.getFieldBool(field, GroupParams.GROUP_FACET, false)) {counts = getGroupedCounts(searcher, docs, field, multiToken, offset,limit, mincount, missing, sort, prefix);@@ -415,7 +420,9 @@ public class SimpleFacets {}break;case FC:- if (multiToken || TrieField.getMainValuePrefix(ft) != null) {+ if (sf.hasDocValues()) {+ counts = DocValuesFacets.getCounts(searcher, docs, field, offset,limit, mincount, missing, sort, prefix);+ } else if (multiToken || TrieField.getMainValuePrefix(ft) != null) {UnInvertedField uif = UnInvertedField.getUnInvertedField(field, searcher);counts = uif.getCounts(searcher, docs, offset, limit, mincount,missing,sort,prefix);} else {@@ -536,9 +543,9 @@ public class SimpleFacets {*/public static int getFieldMissingCount(SolrIndexSearcher searcher, DocSet docs, String fieldName)throws IOException {-+ SchemaField sf = searcher.getSchema().getField(fieldName);DocSet hasVal = searcher.getDocSet- (new TermRangeQuery(fieldName, null, null, false, false));+ (sf.getType().getRangeQuery(null, sf, null, null, false, false));return docs.andNotSize(hasVal);}diff --git a/solr/core/src/java/org/apache/solr/schema/FieldType.java b/solr/core/src/java/org/apache/solr/schema/FieldType.javaindex 288452bcae3..b94caf7d781 100644--- a/solr/core/src/java/org/apache/solr/schema/FieldType.java+++ b/solr/core/src/java/org/apache/solr/schema/FieldType.java@@ -35,9 +35,10 @@ import org.apache.lucene.index.StorableField;import org.apache.lucene.index.Term;import org.apache.lucene.queries.function.ValueSource;import org.apache.lucene.search.ConstantScoreQuery;+import org.apache.lucene.search.DocTermOrdsRangeFilter;+import org.apache.lucene.search.DocTermOrdsRewriteMethod;import org.apache.lucene.search.FieldCacheRangeFilter;import org.apache.lucene.search.FieldCacheRewriteMethod;-import org.apache.lucene.search.FieldCacheTermsFilter;import org.apache.lucene.search.MultiTermQuery;import org.apache.lucene.search.Query;import org.apache.lucene.search.SortField;@@ -596,13 +597,21 @@ public abstract class FieldType extends FieldProperties {**/public Query getRangeQuery(QParser parser, SchemaField field, String part1, String part2, boolean minInclusive, boolean maxInclusive) {- // constant score mode is now enabled per default+ // TODO: change these all to use readableToIndexed/bytes instead (e.g. for unicode collation)if (field.hasDocValues() && !field.indexed()) {- return new ConstantScoreQuery(FieldCacheRangeFilter.newStringRange(+ if (field.multiValued()) {+ return new ConstantScoreQuery(DocTermOrdsRangeFilter.newBytesRefRange(+ field.getName(),+ part1 == null ? null : new BytesRef(toInternal(part1)),+ part2 == null ? null : new BytesRef(toInternal(part2)),+ minInclusive, maxInclusive));+ } else {+ return new ConstantScoreQuery(FieldCacheRangeFilter.newStringRange(field.getName(),part1 == null ? null : toInternal(part1),part2 == null ? null : toInternal(part2),minInclusive, maxInclusive));+ }} else {MultiTermQuery rangeQuery = TermRangeQuery.newStringRange(field.getName(),@@ -627,7 +636,7 @@ public abstract class FieldType extends FieldProperties {readableToIndexed(externalVal, br);if (field.hasDocValues() && !field.indexed()) {// match-only- return new ConstantScoreQuery(new FieldCacheTermsFilter(field.getName(), br));+ return getRangeQuery(parser, field, externalVal, externalVal, true, true);} else {return new TermQuery(new Term(field.getName(), br));}@@ -641,7 +650,7 @@ public abstract class FieldType extends FieldProperties {*/public MultiTermQuery.RewriteMethod getRewriteMethod(QParser parser, SchemaField field) {if (!field.indexed() && field.hasDocValues()) {- return new FieldCacheRewriteMethod();+ return field.multiValued() ? new DocTermOrdsRewriteMethod() : new FieldCacheRewriteMethod();} else {return MultiTermQuery.CONSTANT_SCORE_AUTO_REWRITE_DEFAULT;}diff --git a/solr/core/src/java/org/apache/solr/schema/StrField.java b/solr/core/src/java/org/apache/solr/schema/StrField.javaindex 4f370cd3f3b..7c59741d7d8 100644--- a/solr/core/src/java/org/apache/solr/schema/StrField.java+++ b/solr/core/src/java/org/apache/solr/schema/StrField.java@@ -23,8 +23,8 @@ import java.util.Collections;import java.util.List;import java.util.Map;-import org.apache.lucene.document.Field;import org.apache.lucene.document.SortedDocValuesField;+import org.apache.lucene.document.SortedSetDocValuesField;import org.apache.lucene.index.StorableField;import org.apache.lucene.queries.function.ValueSource;import org.apache.lucene.search.SortField;@@ -46,8 +46,11 @@ public class StrField extends PrimitiveFieldType {List<StorableField> fields = new ArrayList<StorableField>();fields.add(createField(field, value, boost));final BytesRef bytes = new BytesRef(value.toString());- final Field docValuesField = new SortedDocValuesField(field.getName(), bytes);- fields.add(docValuesField);+ if (field.multiValued()) {+ fields.add(new SortedSetDocValuesField(field.getName(), bytes));+ } else {+ fields.add(new SortedDocValuesField(field.getName(), bytes));+ }return fields;} else {return Collections.singletonList(createField(field, value, boost));@@ -77,9 +80,8 @@ public class StrField extends PrimitiveFieldType {@Overridepublic void checkSchemaField(SchemaField field) {- // change me when multi-valued doc values are supported- if (field.hasDocValues() && !(field.isRequired() || field.getDefaultValue() != null)) {- throw new IllegalStateException("Field " + this + " has doc values enabled, but has no default value and is not required");+ if (field.hasDocValues() && !field.multiValued() && !(field.isRequired() || field.getDefaultValue() != null)) {+ throw new IllegalStateException("Field " + this + " has single-valued doc values enabled, but has no default value and is not required");}}}diff --git a/solr/core/src/java/org/apache/solr/schema/TrieField.java b/solr/core/src/java/org/apache/solr/schema/TrieField.javaindex 1573cae9b9a..99cff2204b5 100644--- a/solr/core/src/java/org/apache/solr/schema/TrieField.java+++ b/solr/core/src/java/org/apache/solr/schema/TrieField.java@@ -33,6 +33,7 @@ import org.apache.lucene.document.FloatField;import org.apache.lucene.document.IntField;import org.apache.lucene.document.LongField;import org.apache.lucene.document.NumericDocValuesField;+import org.apache.lucene.document.SortedSetDocValuesField;import org.apache.lucene.index.StorableField;import org.apache.lucene.queries.function.ValueSource;import org.apache.lucene.queries.function.valuesource.DoubleFieldSource;@@ -263,6 +264,10 @@ public class TrieField extends PrimitiveFieldType {@Overridepublic Query getRangeQuery(QParser parser, SchemaField field, String min, String max, boolean minInclusive, boolean maxInclusive) {+ if (field.multiValued() && field.hasDocValues() && !field.indexed()) {+ // for the multi-valued dv-case, the default rangeimpl over toInternal is correct+ return super.getRangeQuery(parser, field, min, max, minInclusive, maxInclusive);+ }int ps = precisionStep;Query query = null;final boolean matchOnly = field.hasDocValues() && !field.indexed();@@ -627,16 +632,24 @@ public class TrieField extends PrimitiveFieldType {List<StorableField> fields = new ArrayList<StorableField>();final StorableField field = createField(sf, value, boost);fields.add(field);- final long bits;- if (field.numericValue() instanceof Integer || field.numericValue() instanceof Long) {- bits = field.numericValue().longValue();- } else if (field.numericValue() instanceof Float) {- bits = Float.floatToIntBits(field.numericValue().floatValue());++ if (sf.multiValued()) {+ BytesRef bytes = new BytesRef();+ readableToIndexed(value.toString(), bytes);+ fields.add(new SortedSetDocValuesField(sf.getName(), bytes));} else {- assert field.numericValue() instanceof Double;- bits = Double.doubleToLongBits(field.numericValue().doubleValue());+ final long bits;+ if (field.numericValue() instanceof Integer || field.numericValue() instanceof Long) {+ bits = field.numericValue().longValue();+ } else if (field.numericValue() instanceof Float) {+ bits = Float.floatToIntBits(field.numericValue().floatValue());+ } else {+ assert field.numericValue() instanceof Double;+ bits = Double.doubleToLongBits(field.numericValue().doubleValue());+ }+ fields.add(new NumericDocValuesField(sf.getName(), bits));}- fields.add(new NumericDocValuesField(sf.getName(), bits));+return fields;} else {return Collections.singletonList(createField(sf, value, boost));@@ -683,8 +696,8 @@ public class TrieField extends PrimitiveFieldType {@Overridepublic void checkSchemaField(final SchemaField field) {- if (field.hasDocValues() && !(field.isRequired() || field.getDefaultValue() != null)) {- throw new IllegalStateException("Field " + this + " has doc values enabled, but has no default value and is not required");+ if (field.hasDocValues() && !field.multiValued() && !(field.isRequired() || field.getDefaultValue() != null)) {+ throw new IllegalStateException("Field " + this + " has single-valued doc values enabled, but has no default value and is not required");}}}diff --git a/solr/core/src/test-files/solr/collection1/conf/schema-docValuesFaceting.xml b/solr/core/src/test-files/solr/collection1/conf/schema-docValuesFaceting.xmlnew file mode 100755index 00000000000..e811f91e8a1--- /dev/null+++ b/solr/core/src/test-files/solr/collection1/conf/schema-docValuesFaceting.xml@@ -0,0 +1,51 @@+<?xml version="1.0" ?>+<!--+ 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.+-->++<schema name="test" version="1.5">+ <types>+ <fieldType name="int" class="solr.TrieIntField" precisionStep="0" omitNorms="true" positionIncrementGap="0"/>+ <fieldType name="float" class="solr.TrieFloatField" precisionStep="0" omitNorms="true" positionIncrementGap="0"/>+ <fieldtype name="string" class="solr.StrField" sortMissingLast="true"/>+ </types>++ <fields>+ <field name="id" type="string" indexed="true" stored="true" docValues="false" multiValued="false" required="true"/>+ <field name="id_dv" type="string" indexed="false" stored="false" docValues="true" multiValued="false" required="true"/>+ <!-- TODO: improve this test so we don't have to make all these DV types multivalued (for missing values) -->+ <dynamicField name="*_i" type="int" indexed="true" stored="false" docValues="false"/>+ <dynamicField name="*_i_dv" type="int" indexed="false" stored="false" docValues="true" multiValued="true"/>+ <dynamicField name="*_is" type="int" indexed="true" stored="false" docValues="false" multiValued="true"/>+ <dynamicField name="*_is_dv" type="int" indexed="false" stored="false" docValues="true" multiValued="true"/>+ <dynamicField name="*_s" type="string" indexed="true" stored="false" docValues="false" multiValued="true"/>+ <dynamicField name="*_s_dv" type="string" indexed="false" stored="false" docValues="true" multiValued="true"/>+ <dynamicField name="*_ss" type="string" indexed="true" stored="false" docValues="false" multiValued="true"/>+ <dynamicField name="*_ss_dv" type="string" indexed="false" stored="false" docValues="true" multiValued="true"/>+ <dynamicField name="*_f" type="float" indexed="true" stored="false" docValues="false"/>+ <dynamicField name="*_f_dv" type="float" indexed="false" stored="false" docValues="true" multiValued="true"/>+ </fields>++ <defaultSearchField>id</defaultSearchField>+ <uniqueKey>id</uniqueKey>++ <copyField source="*_i" dest="*_i_dv" />+ <copyField source="*_f" dest="*_f_dv" />+ <copyField source="*_is" dest="*_is_dv" />+ <copyField source="*_s" dest="*_s_dv" />+ <copyField source="*_ss" dest="*_ss_dv" />+ <copyField source="id" dest="id_dv" />+</schema>diff --git a/solr/core/src/test-files/solr/collection1/conf/schema-docValuesMulti.xml b/solr/core/src/test-files/solr/collection1/conf/schema-docValuesMulti.xmlnew file mode 100644index 00000000000..6d58feda4e5--- /dev/null+++ b/solr/core/src/test-files/solr/collection1/conf/schema-docValuesMulti.xml@@ -0,0 +1,54 @@+<?xml version="1.0" ?>+<!--+ 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.+-->++<schema name="schema-docValuesMulti" version="1.5">+ <types>++ <fieldType name="int" class="solr.TrieIntField" precisionStep="0" omitNorms="true" positionIncrementGap="0"/>+ <fieldType name="float" class="solr.TrieFloatField" precisionStep="0" omitNorms="true" positionIncrementGap="0"/>+ <fieldType name="long" class="solr.TrieLongField" precisionStep="0" omitNorms="true" positionIncrementGap="0"/>+ <fieldType name="double" class="solr.TrieDoubleField" precisionStep="0" omitNorms="true" positionIncrementGap="0"/>+ <!-- format for date is 1995-12-31T23:59:59.999Z and only the fractional+ seconds part (.999) is optional.+ -->+ <fieldtype name="date" class="solr.TrieDateField" precisionStep="0" omitNorms="true" positionIncrementGap="0"/>++ <fieldtype name="boolean" class="solr.BoolField" />+ <fieldtype name="string" class="solr.StrField" />++ <fieldType name="uuid" class="solr.UUIDField" />++ </types>+++ <fields>++ <field name="id" type="string" required="true" />++ <field name="floatdv" type="float" indexed="false" stored="false" docValues="true" multiValued="true" />+ <field name="intdv" type="int" indexed="false" stored="false" docValues="true" multiValued="true" />+ <field name="doubledv" type="double" indexed="false" stored="false" docValues="true" multiValued="true" />+ <field name="longdv" type="long" indexed="false" stored="false" docValues="true" multiValued="true" />+ <field name="datedv" type="date" indexed="false" stored="false" docValues="true" multiValued="true" />++ <field name="stringdv" type="string" indexed="false" stored="false" docValues="true" multiValued="true" />+ </fields>++ <uniqueKey>id</uniqueKey>++</schema>diff --git a/solr/core/src/test/org/apache/solr/TestRandomDVFaceting.java b/solr/core/src/test/org/apache/solr/TestRandomDVFaceting.javanew file mode 100644index 00000000000..df36b6b593b--- /dev/null+++ b/solr/core/src/test/org/apache/solr/TestRandomDVFaceting.java@@ -0,0 +1,251 @@+/*+ * 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.+ */++package org.apache.solr;++import java.util.ArrayList;+import java.util.Arrays;+import java.util.List;+import java.util.Map;+import java.util.Random;++import org.apache.lucene.search.FieldCache;+import org.apache.lucene.util._TestUtil;+import org.apache.lucene.util.LuceneTestCase.Slow;+import org.apache.lucene.util.LuceneTestCase.SuppressCodecs;+import org.apache.solr.common.params.ModifiableSolrParams;+import org.apache.solr.request.SolrQueryRequest;+import org.apache.solr.schema.SchemaField;+import org.junit.BeforeClass;+import org.junit.Test;++/**+ * This is like TestRandomFaceting, except it does a copyField on each+ * indexed field to field_dv, and compares the docvalues facet results+ * to the indexed facet results as if it were just another faceting method.+ */+@Slow+@SuppressCodecs({"Lucene40", "Lucene41"})+public class TestRandomDVFaceting extends SolrTestCaseJ4 {++ @BeforeClass+ public static void beforeTests() throws Exception {+ initCore("solrconfig-basic.xml","schema-docValuesFaceting.xml");+ }++ int indexSize;+ List<FldType> types;+ Map<Comparable, Doc> model = null;+ boolean validateResponses = true;++ void init() {+ Random rand = random();+ clearIndex();+ model = null;+ indexSize = rand.nextBoolean() ? (rand.nextInt(10) + 1) : (rand.nextInt(100) + 10);++ types = new ArrayList<FldType>();+ types.add(new FldType("id",ONE_ONE, new SVal('A','Z',4,4)));+ types.add(new FldType("score_f",ONE_ONE, new FVal(1,100)));+ types.add(new FldType("foo_i",ZERO_ONE, new IRange(0,indexSize)));+ types.add(new FldType("small_s",ZERO_ONE, new SVal('a',(char)('c'+indexSize/3),1,1)));+ types.add(new FldType("small2_s",ZERO_ONE, new SVal('a',(char)('c'+indexSize/3),1,1)));+ types.add(new FldType("small2_ss",ZERO_TWO, new SVal('a',(char)('c'+indexSize/3),1,1)));+ types.add(new FldType("small3_ss",new IRange(0,25), new SVal('A','z',1,1)));+ types.add(new FldType("small_i",ZERO_ONE, new IRange(0,5+indexSize/3)));+ types.add(new FldType("small2_i",ZERO_ONE, new IRange(0,5+indexSize/3)));+ types.add(new FldType("small2_is",ZERO_TWO, new IRange(0,5+indexSize/3)));+ types.add(new FldType("small3_is",new IRange(0,25), new IRange(0,100)));++ types.add(new FldType("missing_i",new IRange(0,0), new IRange(0,100)));+ types.add(new FldType("missing_is",new IRange(0,0), new IRange(0,100)));+ types.add(new FldType("missing_s",new IRange(0,0), new SVal('a','b',1,1)));+ types.add(new FldType("missing_ss",new IRange(0,0), new SVal('a','b',1,1)));++ // TODO: doubles, multi-floats, ints with precisionStep>0, booleans+ }++ void addMoreDocs(int ndocs) throws Exception {+ model = indexDocs(types, model, ndocs);+ }++ void deleteSomeDocs() {+ Random rand = random();+ int percent = rand.nextInt(100);+ if (model == null) return;+ ArrayList<String> ids = new ArrayList<String>(model.size());+ for (Comparable id : model.keySet()) {+ if (rand.nextInt(100) < percent) {+ ids.add(id.toString());+ }+ }+ if (ids.size() == 0) return;++ StringBuffer sb = new StringBuffer("id:(");+ for (String id : ids) {+ sb.append(id).append(' ');+ model.remove(id);+ }+ sb.append(')');++ assertU(delQ(sb.toString()));++ if (rand.nextInt(10)==0) {+ assertU(optimize());+ } else {+ assertU(commit("softCommit",""+(rand.nextInt(10)!=0)));+ }+ }++ @Test+ public void testRandomFaceting() throws Exception {+ try {+ Random rand = random();+ int iter = atLeast(100);+ init();+ addMoreDocs(0);++ for (int i=0; i<iter; i++) {+ doFacetTests();++ if (rand.nextInt(100) < 5) {+ init();+ }++ addMoreDocs(rand.nextInt(indexSize) + 1);++ if (rand.nextInt(100) < 50) {+ deleteSomeDocs();+ }+ }+ } finally {+ FieldCache.DEFAULT.purgeAllCaches(); // avoid FC insanity+ }+ }+++ void doFacetTests() throws Exception {+ for (FldType ftype : types) {+ doFacetTests(ftype);+ }+ }++ // NOTE: dv is not a "real" facet.method. when we see it, we facet on the dv field (*_dv)+ // but alias the result back as if we faceted on the regular indexed field for comparisons.+ List<String> multiValuedMethods = Arrays.asList(new String[]{"enum","fc","dv"});+ List<String> singleValuedMethods = Arrays.asList(new String[]{"enum","fc","fcs","dv"});+++ void doFacetTests(FldType ftype) throws Exception {+ SolrQueryRequest req = req();+ try {+ Random rand = random();+ boolean validate = validateResponses;+ ModifiableSolrParams params = params("facet","true", "wt","json", "indent","true", "omitHeader","true");+ params.add("q","*:*", "rows","0"); // TODO: select subsets+ params.add("rows","0");+++ SchemaField sf = req.getSchema().getField(ftype.fname);+ boolean multiValued = sf.getType().multiValuedFieldCache();++ int offset = 0;+ if (rand.nextInt(100) < 20) {+ if (rand.nextBoolean()) {+ offset = rand.nextInt(100) < 10 ? rand.nextInt(indexSize*2) : rand.nextInt(indexSize/3+1);+ }+ params.add("facet.offset", Integer.toString(offset));+ }++ int limit = 100;+ if (rand.nextInt(100) < 20) {+ if (rand.nextBoolean()) {+ limit = rand.nextInt(100) < 10 ? rand.nextInt(indexSize/2+1) : rand.nextInt(indexSize*2);+ }+ params.add("facet.limit", Integer.toString(limit));+ }++ if (rand.nextBoolean()) {+ params.add("facet.sort", rand.nextBoolean() ? "index" : "count");+ }++ if ((ftype.vals instanceof SVal) && rand.nextInt(100) < 20) {+ // validate = false;+ String prefix = ftype.createValue().toString();+ if (rand.nextInt(100) < 5) prefix = _TestUtil.randomUnicodeString(rand);+ else if (rand.nextInt(100) < 10) prefix = Character.toString((char)rand.nextInt(256));+ else if (prefix.length() > 0) prefix = prefix.substring(0, rand.nextInt(prefix.length()));+ params.add("facet.prefix", prefix);+ }++ if (rand.nextInt(100) < 10) {+ params.add("facet.mincount", Integer.toString(rand.nextInt(5)));+ }++ if (rand.nextInt(100) < 20) {+ params.add("facet.missing", "true");+ }++ // TODO: randomly add other facet params+ String facet_field = ftype.fname;++ List<String> methods = multiValued ? multiValuedMethods : singleValuedMethods;+ List<String> responses = new ArrayList<String>(methods.size());+ for (String method : methods) {+ if (method.equals("dv")) {+ params.set("facet.field", "{!key="+facet_field+"}"+facet_field+"_dv");+ params.set("facet.method", null);+ } else {+ params.set("facet.field", facet_field);+ params.set("facet.method", method);+ }++ // if (random().nextBoolean()) params.set("facet.mincount", "1"); // uncomment to test that validation fails++ String strResponse = h.query(req(params));+ // Object realResponse = ObjectBuilder.fromJSON(strResponse);+ // System.out.println(strResponse);++ responses.add(strResponse);+ }++ /**+ String strResponse = h.query(req(params));+ Object realResponse = ObjectBuilder.fromJSON(strResponse);+ **/++ if (validate) {+ for (int i=1; i<methods.size(); i++) {+ String err = JSONTestUtil.match("/", responses.get(i), responses.get(0), 0.0);+ if (err != null) {+ log.error("ERROR: mismatch facet response: " + err ++ "\n expected =" + responses.get(0) ++ "\n response = " + responses.get(i) ++ "\n request = " + params+ );+ fail(err);+ }+ }+ }+++ } finally {+ req.close();+ }+ }++}diff --git a/solr/core/src/test/org/apache/solr/schema/DocValuesMultiTest.java b/solr/core/src/test/org/apache/solr/schema/DocValuesMultiTest.javanew file mode 100644index 00000000000..0d96a92ffee--- /dev/null+++ b/solr/core/src/test/org/apache/solr/schema/DocValuesMultiTest.java@@ -0,0 +1,193 @@+package org.apache.solr.schema;++/*+ * 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.AtomicReader;+import org.apache.lucene.index.FieldInfo.DocValuesType;+import org.apache.lucene.index.FieldInfos;+import org.apache.lucene.index.SortedSetDocValues;+import org.apache.lucene.util.LuceneTestCase.SuppressCodecs;+import org.apache.solr.SolrTestCaseJ4;+import org.apache.solr.core.SolrCore;+import org.apache.solr.search.SolrIndexSearcher;+import org.apache.solr.util.RefCounted;+import org.junit.BeforeClass;++@SuppressCodecs({"Lucene40", "Lucene41"})+public class DocValuesMultiTest extends SolrTestCaseJ4 {++ @BeforeClass+ public static void beforeTests() throws Exception {+ initCore("solrconfig-basic.xml", "schema-docValuesMulti.xml");+ }++ public void setUp() throws Exception {+ super.setUp();+ assertU(delQ("*:*"));+ }++ public void testDocValues() throws IOException {+ assertU(adoc("id", "1", "floatdv", "4.5", "intdv", "-1", "intdv", "3", "stringdv", "value1", "stringdv", "value2"));+ commit();+ SolrCore core = h.getCoreInc();+ try {+ final RefCounted<SolrIndexSearcher> searcherRef = core.openNewSearcher(true, true);+ final SolrIndexSearcher searcher = searcherRef.get();+ try {+ final AtomicReader reader = searcher.getAtomicReader();+ assertEquals(1, reader.numDocs());+ final FieldInfos infos = reader.getFieldInfos();+ assertEquals(DocValuesType.SORTED_SET, infos.fieldInfo("stringdv").getDocValuesType());+ assertEquals(DocValuesType.SORTED_SET, infos.fieldInfo("floatdv").getDocValuesType());+ assertEquals(DocValuesType.SORTED_SET, infos.fieldInfo("intdv").getDocValuesType());++ SortedSetDocValues dv = reader.getSortedSetDocValues("stringdv");+ dv.setDocument(0);+ assertEquals(0, dv.nextOrd());+ assertEquals(1, dv.nextOrd());+ assertEquals(SortedSetDocValues.NO_MORE_ORDS, dv.nextOrd());+ } finally {+ searcherRef.decref();+ }+ } finally {+ core.close();+ }+ }++ /** Tests the ability to do basic queries (without scoring, just match-only) on+ * string docvalues fields that are not inverted (indexed "forward" only)+ */+ public void testStringDocValuesMatch() throws Exception {+ assertU(adoc("id", "1", "stringdv", "b"));+ assertU(adoc("id", "2", "stringdv", "a"));+ assertU(adoc("id", "3", "stringdv", "c"));+ assertU(adoc("id", "4", "stringdv", "car"));+ assertU(adoc("id", "5", "stringdv", "dog", "stringdv", "cat"));+ assertU(commit());++ // string: termquery+ assertQ(req("q", "stringdv:car", "sort", "id asc"),+ "//*[@numFound='1']",+ "//result/doc[1]/str[@name='id'][.=4]"+ );++ // string: range query+ assertQ(req("q", "stringdv:[b TO d]", "sort", "id asc"),+ "//*[@numFound='4']",+ "//result/doc[1]/str[@name='id'][.=1]",+ "//result/doc[2]/str[@name='id'][.=3]",+ "//result/doc[3]/str[@name='id'][.=4]",+ "//result/doc[4]/str[@name='id'][.=5]"+ );++ // string: prefix query+ assertQ(req("q", "stringdv:c*", "sort", "id asc"),+ "//*[@numFound='3']",+ "//result/doc[1]/str[@name='id'][.=3]",+ "//result/doc[2]/str[@name='id'][.=4]",+ "//result/doc[3]/str[@name='id'][.=5]"+ );++ // string: wildcard query+ assertQ(req("q", "stringdv:c?r", "sort", "id asc"),+ "//*[@numFound='1']",+ "//result/doc[1]/str[@name='id'][.=4]"+ );++ // string: regexp query+ assertQ(req("q", "stringdv:/c[a-b]r/", "sort", "id asc"),+ "//*[@numFound='1']",+ "//result/doc[1]/str[@name='id'][.=4]"+ );+ }++ /** Tests the ability to do basic queries (without scoring, just match-only) on+ * float docvalues fields that are not inverted (indexed "forward" only)+ */+ public void testFloatDocValuesMatch() throws Exception {+ assertU(adoc("id", "1", "floatdv", "2"));+ assertU(adoc("id", "2", "floatdv", "5"));+ assertU(adoc("id", "3", "floatdv", "3.0", "floatdv", "-1.3", "floatdv", "2.2"));+ assertU(adoc("id", "4", "floatdv", "3"));+ assertU(commit());++ // float: termquery+ assertQ(req("q", "floatdv:3", "sort", "id asc"),+ "//*[@numFound='2']",+ "//result/doc[1]/str[@name='id'][.=3]",+ "//result/doc[2]/str[@name='id'][.=4]"+ );++ // float: rangequery+ assertQ(req("q", "floatdv:[-1 TO 2.5]", "sort", "id asc"),+ "//*[@numFound='2']",+ "//result/doc[1]/str[@name='id'][.=1]",+ "//result/doc[2]/str[@name='id'][.=3]"+ );+ }++ public void testDocValuesFacetingSimple() {+ // this is the random test verbatim from DocValuesTest, so it populates with the default values defined in its schema.+ for (int i = 0; i < 50; ++i) {+ assertU(adoc("id", "" + i, "floatdv", "1", "intdv", "2", "doubledv", "3", "longdv", "4", "datedv", "1995-12-31T23:59:59.999Z"));+ }+ for (int i = 0; i < 50; ++i) {+ if (rarely()) {+ commit(); // to have several segments+ }+ assertU(adoc("id", "1000" + i, "floatdv", "" + i, "intdv", "" + i, "doubledv", "" + i, "longdv", "" + i, "datedv", (1900+i) + "-12-31T23:59:59.999Z", "stringdv", "abc" + i));+ }+ assertU(commit());+ assertQ(req("q", "*:*", "facet", "true", "rows", "0", "facet.field", "longdv", "facet.sort", "count", "facet.limit", "1"),+ "//lst[@name='longdv']/int[@name='4'][.='51']");+ assertQ(req("q", "*:*", "facet", "true", "rows", "0", "facet.field", "longdv", "facet.sort", "count", "facet.offset", "1", "facet.limit", "1"),+ "//lst[@name='longdv']/int[@name='0'][.='1']");+ assertQ(req("q", "*:*", "facet", "true", "rows", "0", "facet.field", "longdv", "facet.sort", "index", "facet.offset", "33", "facet.limit", "1", "facet.mincount", "1"),+ "//lst[@name='longdv']/int[@name='33'][.='1']");++ assertQ(req("q", "*:*", "facet", "true", "rows", "0", "facet.field", "floatdv", "facet.sort", "count", "facet.limit", "1"),+ "//lst[@name='floatdv']/int[@name='1.0'][.='51']");+ assertQ(req("q", "*:*", "facet", "true", "rows", "0", "facet.field", "floatdv", "facet.sort", "count", "facet.offset", "1", "facet.limit", "-1", "facet.mincount", "1"),+ "//lst[@name='floatdv']/int[@name='0.0'][.='1']");+ assertQ(req("q", "*:*", "facet", "true", "rows", "0", "facet.field", "floatdv", "facet.sort", "index", "facet.offset", "33", "facet.limit", "1", "facet.mincount", "1"),+ "//lst[@name='floatdv']/int[@name='33.0'][.='1']");++ assertQ(req("q", "*:*", "facet", "true", "rows", "0", "facet.field", "doubledv", "facet.sort", "count", "facet.limit", "1"),+ "//lst[@name='doubledv']/int[@name='3.0'][.='51']");+ assertQ(req("q", "*:*", "facet", "true", "rows", "0", "facet.field", "doubledv", "facet.sort", "count", "facet.offset", "1", "facet.limit", "-1", "facet.mincount", "1"),+ "//lst[@name='doubledv']/int[@name='0.0'][.='1']");+ assertQ(req("q", "*:*", "facet", "true", "rows", "0", "facet.field", "doubledv", "facet.sort", "index", "facet.offset", "33", "facet.limit", "1", "facet.mincount", "1"),+ "//lst[@name='doubledv']/int[@name='33.0'][.='1']");++ assertQ(req("q", "*:*", "facet", "true", "rows", "0", "facet.field", "intdv", "facet.sort", "count", "facet.limit", "1"),+ "//lst[@name='intdv']/int[@name='2'][.='51']");+ assertQ(req("q", "*:*", "facet", "true", "rows", "0", "facet.field", "intdv", "facet.sort", "count", "facet.offset", "1", "facet.limit", "-1", "facet.mincount", "1"),+ "//lst[@name='intdv']/int[@name='0'][.='1']");+ assertQ(req("q", "*:*", "facet", "true", "rows", "0", "facet.field", "intdv", "facet.sort", "index", "facet.offset", "33", "facet.limit", "1", "facet.mincount", "1"),+ "//lst[@name='intdv']/int[@name='33'][.='1']");++ assertQ(req("q", "*:*", "facet", "true", "rows", "0", "facet.field", "datedv", "facet.sort", "count", "facet.limit", "1"),+ "//lst[@name='datedv']/int[@name='1995-12-31T23:59:59.999Z'][.='50']");+ assertQ(req("q", "*:*", "facet", "true", "rows", "0", "facet.field", "datedv", "facet.sort", "count", "facet.offset", "1", "facet.limit", "-1", "facet.mincount", "1"),+ "//lst[@name='datedv']/int[@name='1900-12-31T23:59:59.999Z'][.='1']");+ assertQ(req("q", "*:*", "facet", "true", "rows", "0", "facet.field", "datedv", "facet.sort", "index", "facet.offset", "33", "facet.limit", "1", "facet.mincount", "1"),+ "//lst[@name='datedv']/int[@name='1933-12-31T23:59:59.999Z'][.='1']");+ }+}