Skip to content

Apache Lucene open-source search software

LUCENE-5339: cutover more tests

Michael McCandless6251fde285eb
diff --git a/lucene/facet/src/java/org/apache/lucene/facet/simple/MultiFacets.java b/lucene/facet/src/java/org/apache/lucene/facet/simple/MultiFacets.java
index ca73edba8b2..bccbbec6cb8 100644
--- a/lucene/facet/src/java/org/apache/lucene/facet/simple/MultiFacets.java
+++ b/lucene/facet/src/java/org/apache/lucene/facet/simple/MultiFacets.java
@@ -27,6 +27,10 @@ public class MultiFacets extends Facets {
private final Map<String,Facets> dimToFacets;
private final Facets defaultFacets;
+ public MultiFacets(Map<String,Facets> dimToFacets) {
+ this(dimToFacets = dimToFacets, null);
+ }
+
public MultiFacets(Map<String,Facets> dimToFacets, Facets defaultFacets) {
this.dimToFacets = dimToFacets;
this.defaultFacets = defaultFacets;
@@ -35,6 +39,9 @@ public class MultiFacets extends Facets {
public SimpleFacetResult getTopChildren(int topN, String dim, String... path) throws IOException {
Facets facets = dimToFacets.get(dim);
if (facets == null) {
+ if (defaultFacets == null) {
+ throw new IllegalArgumentException("invalid dim \"" + dim + "\"");
+ }
facets = defaultFacets;
}
return facets.getTopChildren(topN, dim, path);
@@ -43,6 +50,9 @@ public class MultiFacets extends Facets {
public Number getSpecificValue(String dim, String... path) throws IOException {
Facets facets = dimToFacets.get(dim);
if (facets == null) {
+ if (defaultFacets == null) {
+ throw new IllegalArgumentException("invalid dim \"" + dim + "\"");
+ }
facets = defaultFacets;
}
return facets.getSpecificValue(dim, path);
diff --git a/lucene/facet/src/java/org/apache/lucene/facet/simple/RangeFacetCounts.java b/lucene/facet/src/java/org/apache/lucene/facet/simple/RangeFacetCounts.java
index 6dbe47114dd..cc049012971 100644
--- a/lucene/facet/src/java/org/apache/lucene/facet/simple/RangeFacetCounts.java
+++ b/lucene/facet/src/java/org/apache/lucene/facet/simple/RangeFacetCounts.java
@@ -23,6 +23,7 @@ import java.util.List;
import org.apache.lucene.facet.range.Range;
import org.apache.lucene.facet.simple.SimpleFacetsCollector.MatchingDocs;
+import org.apache.lucene.facet.taxonomy.FacetLabel;
import org.apache.lucene.queries.function.FunctionValues;
import org.apache.lucene.queries.function.ValueSource;
import org.apache.lucene.queries.function.valuesource.LongFieldSource;
@@ -33,14 +34,16 @@ import org.apache.lucene.queries.function.valuesource.LongFieldSource;
public class RangeFacetCounts extends Facets {
private final Range[] ranges;
private final int[] counts;
+ private final String field;
private int totCount;
public RangeFacetCounts(String field, SimpleFacetsCollector hits, Range... ranges) throws IOException {
- this(new LongFieldSource(field), hits, ranges);
+ this(field, new LongFieldSource(field), hits, ranges);
}
- public RangeFacetCounts(ValueSource valueSource, SimpleFacetsCollector hits, Range... ranges) throws IOException {
+ public RangeFacetCounts(String field, ValueSource valueSource, SimpleFacetsCollector hits, Range... ranges) throws IOException {
this.ranges = ranges;
+ this.field = field;
counts = new int[ranges.length];
count(valueSource, hits.getMatchingDocs());
}
@@ -83,13 +86,16 @@ public class RangeFacetCounts extends Facets {
@Override
public SimpleFacetResult getTopChildren(int topN, String dim, String... path) {
+ if (dim.equals(field) == false) {
+ throw new IllegalArgumentException("invalid dim \"" + dim + "\"; should be \"" + field + "\"");
+ }
LabelAndValue[] labelValues = new LabelAndValue[counts.length];
for(int i=0;i<counts.length;i++) {
// nocommit can we add the range into this?
labelValues[i] = new LabelAndValue(ranges[i].label, counts[i]);
}
- return new SimpleFacetResult(null, totCount, labelValues);
+ return new SimpleFacetResult(new FacetLabel(field), totCount, labelValues);
}
@Override
diff --git a/lucene/facet/src/java/org/apache/lucene/facet/simple/SimpleDrillDownQuery.java b/lucene/facet/src/java/org/apache/lucene/facet/simple/SimpleDrillDownQuery.java
index 7bc2d17bc4f..89035cbd36b 100644
--- a/lucene/facet/src/java/org/apache/lucene/facet/simple/SimpleDrillDownQuery.java
+++ b/lucene/facet/src/java/org/apache/lucene/facet/simple/SimpleDrillDownQuery.java
@@ -203,10 +203,7 @@ public final class SimpleDrillDownQuery extends Query {
@Override
public Query rewrite(IndexReader r) throws IOException {
if (query.clauses().size() == 0) {
- // baseQuery given to the ctor was null + no drill-downs were added
- // note that if only baseQuery was given to the ctor, but no drill-down terms
- // is fine, since the rewritten query will be the original base query.
- throw new IllegalStateException("no base query or drill-down categories given");
+ return new MatchAllDocsQuery();
}
return query;
}
diff --git a/lucene/facet/src/java/org/apache/lucene/facet/simple/SimpleDrillSideways.java b/lucene/facet/src/java/org/apache/lucene/facet/simple/SimpleDrillSideways.java
index 92a9ecf404c..a7a6755cb86 100644
--- a/lucene/facet/src/java/org/apache/lucene/facet/simple/SimpleDrillSideways.java
+++ b/lucene/facet/src/java/org/apache/lucene/facet/simple/SimpleDrillSideways.java
@@ -108,31 +108,32 @@ public class SimpleDrillSideways {
* impl. */
protected Facets buildFacetsResult(SimpleFacetsCollector drillDowns, SimpleFacetsCollector[] drillSideways, String[] drillSidewaysDims) throws IOException {
+ Facets drillDownFacets;
+ Map<String,Facets> drillSidewaysFacets = new HashMap<String,Facets>();
+
if (taxoReader != null) {
- Facets drillDownFacets = new FastTaxonomyFacetCounts(taxoReader, config, drillDowns);
- if (drillSideways == null) {
- return drillDownFacets;
- } else {
- Map<String,Facets> drillSidewaysFacets = new HashMap<String,Facets>();
+ drillDownFacets = new FastTaxonomyFacetCounts(taxoReader, config, drillDowns);
+ if (drillSideways != null) {
for(int i=0;i<drillSideways.length;i++) {
drillSidewaysFacets.put(drillSidewaysDims[i],
new FastTaxonomyFacetCounts(taxoReader, config, drillSideways[i]));
}
- return new MultiFacets(drillSidewaysFacets, drillDownFacets);
}
} else {
- Facets drillDownFacets = new SortedSetDocValuesFacetCounts(state, drillDowns);
- if (drillSideways == null) {
- return drillDownFacets;
- } else {
- Map<String,Facets> drillSidewaysFacets = new HashMap<String,Facets>();
+ drillDownFacets = new SortedSetDocValuesFacetCounts(state, drillDowns);
+ if (drillSideways != null) {
for(int i=0;i<drillSideways.length;i++) {
drillSidewaysFacets.put(drillSidewaysDims[i],
new SortedSetDocValuesFacetCounts(state, drillSideways[i]));
}
- return new MultiFacets(drillSidewaysFacets, drillDownFacets);
}
}
+
+ if (drillSidewaysFacets.isEmpty()) {
+ return drillDownFacets;
+ } else {
+ return new MultiFacets(drillSidewaysFacets, drillDownFacets);
+ }
}
/**
diff --git a/lucene/facet/src/test/org/apache/lucene/facet/FacetTestCase.java b/lucene/facet/src/test/org/apache/lucene/facet/FacetTestCase.java
index 401be71899b..5dfc63f3d86 100644
--- a/lucene/facet/src/test/org/apache/lucene/facet/FacetTestCase.java
+++ b/lucene/facet/src/test/org/apache/lucene/facet/FacetTestCase.java
@@ -71,7 +71,7 @@ public abstract class FacetTestCase extends LuceneTestCase {
};
}
- public Facets getFacetCounts(TaxonomyReader taxoReader, FacetsConfig config, SimpleFacetsCollector c) throws IOException {
+ public Facets getTaxonomyFacetCounts(TaxonomyReader taxoReader, FacetsConfig config, SimpleFacetsCollector c) throws IOException {
Facets facets;
if (random().nextBoolean()) {
facets = new FastTaxonomyFacetCounts(taxoReader, config, c);
diff --git a/lucene/facet/src/test/org/apache/lucene/facet/range/TestRangeAccumulator.java b/lucene/facet/src/test/org/apache/lucene/facet/range/TestRangeAccumulator.java
deleted file mode 100644
index 93084e7fb5d..00000000000
--- a/lucene/facet/src/test/org/apache/lucene/facet/range/TestRangeAccumulator.java
+++ /dev/null
@@ -1,677 +0,0 @@
-package org.apache.lucene.facet.range;
-
-/*
- * 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.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.apache.lucene.document.Document;
-import org.apache.lucene.document.DoubleDocValuesField;
-import org.apache.lucene.document.DoubleField;
-import org.apache.lucene.document.Field;
-import org.apache.lucene.document.FloatDocValuesField;
-import org.apache.lucene.document.FloatField;
-import org.apache.lucene.document.LongField;
-import org.apache.lucene.document.NumericDocValuesField;
-import org.apache.lucene.facet.FacetTestCase;
-import org.apache.lucene.facet.FacetTestUtils;
-import org.apache.lucene.facet.index.FacetFields;
-import org.apache.lucene.facet.params.FacetIndexingParams;
-import org.apache.lucene.facet.params.FacetSearchParams;
-import org.apache.lucene.facet.search.CountFacetRequest;
-import org.apache.lucene.facet.search.DrillDownQuery;
-import org.apache.lucene.facet.search.DrillSideways;
-import org.apache.lucene.facet.search.DrillSideways.DrillSidewaysResult;
-import org.apache.lucene.facet.search.FacetRequest;
-import org.apache.lucene.facet.search.FacetResult;
-import org.apache.lucene.facet.search.FacetResultNode;
-import org.apache.lucene.facet.search.FacetsAccumulator;
-import org.apache.lucene.facet.search.FacetsCollector;
-import org.apache.lucene.facet.sortedset.SortedSetDocValuesFacetFields;
-import org.apache.lucene.facet.sortedset.SortedSetDocValuesReaderState;
-import org.apache.lucene.facet.taxonomy.FacetLabel;
-import org.apache.lucene.facet.taxonomy.TaxonomyReader;
-import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyReader;
-import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyWriter;
-import org.apache.lucene.index.IndexReader;
-import org.apache.lucene.index.IndexWriterConfig;
-import org.apache.lucene.index.RandomIndexWriter;
-import org.apache.lucene.search.IndexSearcher;
-import org.apache.lucene.search.MatchAllDocsQuery;
-import org.apache.lucene.search.NumericRangeQuery;
-import org.apache.lucene.store.Directory;
-import org.apache.lucene.util.IOUtils;
-import org.apache.lucene.util._TestUtil;
-
-public class TestRangeAccumulator extends FacetTestCase {
-
- public void testBasicLong() throws Exception {
- Directory d = newDirectory();
- RandomIndexWriter w = new RandomIndexWriter(random(), d);
- Document doc = new Document();
- NumericDocValuesField field = new NumericDocValuesField("field", 0L);
- doc.add(field);
- for(long l=0;l<100;l++) {
- field.setLongValue(l);
- w.addDocument(doc);
- }
- field.setLongValue(Long.MAX_VALUE);
- w.addDocument(doc);
-
- IndexReader r = w.getReader();
- w.close();
-
- RangeAccumulator a = new RangeAccumulator(new RangeFacetRequest<LongRange>("field",
- new LongRange("less than 10", 0L, true, 10L, false),
- new LongRange("less than or equal to 10", 0L, true, 10L, true),
- new LongRange("over 90", 90L, false, 100L, false),
- new LongRange("90 or above", 90L, true, 100L, false),
- new LongRange("over 1000", 1000L, false, Long.MAX_VALUE, true)));
-
- FacetsCollector fc = FacetsCollector.create(a);
-
- IndexSearcher s = newSearcher(r);
- s.search(new MatchAllDocsQuery(), fc);
- List<FacetResult> result = fc.getFacetResults();
- assertEquals(1, result.size());
- assertEquals("field (0)\n less than 10 (10)\n less than or equal to 10 (11)\n over 90 (9)\n 90 or above (10)\n over 1000 (1)\n", FacetTestUtils.toSimpleString(result.get(0)));
-
- r.close();
- d.close();
- }
-
- /** Tests single request that mixes Range and non-Range
- * faceting, with DrillSideways and taxonomy. */
- public void testMixedRangeAndNonRangeTaxonomy() throws Exception {
- Directory d = newDirectory();
- RandomIndexWriter w = new RandomIndexWriter(random(), d);
- Directory td = newDirectory();
- DirectoryTaxonomyWriter tw = new DirectoryTaxonomyWriter(td, IndexWriterConfig.OpenMode.CREATE);
- FacetFields ff = new FacetFields(tw);
-
- for (long l = 0; l < 100; l++) {
- Document doc = new Document();
- // For computing range facet counts:
- doc.add(new NumericDocValuesField("field", l));
- // For drill down by numeric range:
- doc.add(new LongField("field", l, Field.Store.NO));
-
- FacetLabel cp;
- if ((l&3) == 0) {
- cp = new FacetLabel("dim", "a");
- } else {
- cp = new FacetLabel("dim", "b");
- }
- ff.addFields(doc, Collections.singletonList(cp));
- w.addDocument(doc);
- }
-
- final IndexReader r = w.getReader();
- w.close();
-
- final TaxonomyReader tr = new DirectoryTaxonomyReader(tw);
- tw.close();
-
- IndexSearcher s = newSearcher(r);
-
- final CountFacetRequest countRequest = new CountFacetRequest(new FacetLabel("dim"), 2);
- final RangeFacetRequest<LongRange> rangeRequest = new RangeFacetRequest<LongRange>("field",
- new LongRange("less than 10", 0L, true, 10L, false),
- new LongRange("less than or equal to 10", 0L, true, 10L, true),
- new LongRange("over 90", 90L, false, 100L, false),
- new LongRange("90 or above", 90L, true, 100L, false),
- new LongRange("over 1000", 1000L, false, Long.MAX_VALUE, false));
- FacetSearchParams fsp = new FacetSearchParams(countRequest, rangeRequest);
-
- final Set<String> dimSeen = new HashSet<String>();
-
- DrillSideways ds = new DrillSideways(s, tr) {
- @Override
- protected FacetsAccumulator getDrillDownAccumulator(FacetSearchParams fsp) {
- checkSeen(fsp);
- return FacetsAccumulator.create(fsp, r, tr, null);
- }
-
- @Override
- protected FacetsAccumulator getDrillSidewaysAccumulator(String dim, FacetSearchParams fsp) {
- checkSeen(fsp);
- return FacetsAccumulator.create(fsp, r, tr, null);
- }
-
- private void checkSeen(FacetSearchParams fsp) {
- // Each dim should up only once, across
- // both drillDown and drillSideways requests:
- for(FacetRequest fr : fsp.facetRequests) {
- String dim = fr.categoryPath.components[0];
- assertFalse("dim " + dim + " already seen", dimSeen.contains(dim));
- dimSeen.add(dim);
- }
- }
-
- @Override
- protected boolean scoreSubDocsAtOnce() {
- return random().nextBoolean();
- }
- };
-
- // First search, no drill downs:
- DrillDownQuery ddq = new DrillDownQuery(FacetIndexingParams.DEFAULT, new MatchAllDocsQuery());
- DrillSidewaysResult dsr = ds.search(null, ddq, 10, fsp);
-
- assertEquals(100, dsr.hits.totalHits);
- assertEquals(2, dsr.facetResults.size());
- assertEquals("dim (0)\n b (75)\n a (25)\n", FacetTestUtils.toSimpleString(dsr.facetResults.get(0)));
- assertEquals("field (0)\n less than 10 (10)\n less than or equal to 10 (11)\n over 90 (9)\n 90 or above (10)\n over 1000 (0)\n", FacetTestUtils.toSimpleString(dsr.facetResults.get(1)));
-
- // Second search, drill down on dim=b:
- ddq = new DrillDownQuery(FacetIndexingParams.DEFAULT, new MatchAllDocsQuery());
- ddq.add(new FacetLabel("dim", "b"));
- dimSeen.clear();
- dsr = ds.search(null, ddq, 10, fsp);
-
- assertEquals(75, dsr.hits.totalHits);
- assertEquals(2, dsr.facetResults.size());
- assertEquals("dim (0)\n b (75)\n a (25)\n", FacetTestUtils.toSimpleString(dsr.facetResults.get(0)));
- assertEquals("field (0)\n less than 10 (7)\n less than or equal to 10 (8)\n over 90 (7)\n 90 or above (8)\n over 1000 (0)\n", FacetTestUtils.toSimpleString(dsr.facetResults.get(1)));
-
- // Third search, drill down on "less than or equal to 10":
- ddq = new DrillDownQuery(FacetIndexingParams.DEFAULT, new MatchAllDocsQuery());
- ddq.add("field", NumericRangeQuery.newLongRange("field", 0L, 10L, true, true));
- dimSeen.clear();
- dsr = ds.search(null, ddq, 10, fsp);
-
- assertEquals(11, dsr.hits.totalHits);
- assertEquals(2, dsr.facetResults.size());
- assertEquals("dim (0)\n b (8)\n a (3)\n", FacetTestUtils.toSimpleString(dsr.facetResults.get(0)));
- assertEquals("field (0)\n less than 10 (10)\n less than or equal to 10 (11)\n over 90 (9)\n 90 or above (10)\n over 1000 (0)\n", FacetTestUtils.toSimpleString(dsr.facetResults.get(1)));
-
- IOUtils.close(tr, td, r, d);
- }
-
- /** Tests single request that mixes Range and non-Range
- * faceting, with DrillSideways and SortedSet. */
- public void testMixedRangeAndNonRangeSortedSet() throws Exception {
- assumeTrue("Test requires SortedSetDV support", defaultCodecSupportsSortedSet());
- Directory d = newDirectory();
- RandomIndexWriter w = new RandomIndexWriter(random(), d);
- SortedSetDocValuesFacetFields ff = new SortedSetDocValuesFacetFields();
-
- for (long l = 0; l < 100; l++) {
- Document doc = new Document();
- // For computing range facet counts:
- doc.add(new NumericDocValuesField("field", l));
- // For drill down by numeric range:
- doc.add(new LongField("field", l, Field.Store.NO));
-
- FacetLabel cp;
- if ((l&3) == 0) {
- cp = new FacetLabel("dim", "a");
- } else {
- cp = new FacetLabel("dim", "b");
- }
- ff.addFields(doc, Collections.singletonList(cp));
- w.addDocument(doc);
- }
-
- final IndexReader r = w.getReader();
- w.close();
-
- IndexSearcher s = newSearcher(r);
- final SortedSetDocValuesReaderState state = new SortedSetDocValuesReaderState(s.getIndexReader());
-
- final CountFacetRequest countRequest = new CountFacetRequest(new FacetLabel("dim"), 2);
- final RangeFacetRequest<LongRange> rangeRequest = new RangeFacetRequest<LongRange>("field",
- new LongRange("less than 10", 0L, true, 10L, false),
- new LongRange("less than or equal to 10", 0L, true, 10L, true),
- new LongRange("over 90", 90L, false, 100L, false),
- new LongRange("90 or above", 90L, true, 100L, false),
- new LongRange("over 1000", 1000L, false, Long.MAX_VALUE, false));
- FacetSearchParams fsp = new FacetSearchParams(countRequest, rangeRequest);
-
- final Set<String> dimSeen = new HashSet<String>();
-
- DrillSideways ds = new DrillSideways(s, state) {
- @Override
- protected FacetsAccumulator getDrillDownAccumulator(FacetSearchParams fsp) throws IOException {
- checkSeen(fsp);
- return FacetsAccumulator.create(fsp, state, null);
- }
-
- @Override
- protected FacetsAccumulator getDrillSidewaysAccumulator(String dim, FacetSearchParams fsp) throws IOException {
- checkSeen(fsp);
- return FacetsAccumulator.create(fsp, state, null);
- }
-
- private void checkSeen(FacetSearchParams fsp) {
- // Each dim should up only once, across
- // both drillDown and drillSideways requests:
- for(FacetRequest fr : fsp.facetRequests) {
- String dim = fr.categoryPath.components[0];
- assertFalse("dim " + dim + " already seen", dimSeen.contains(dim));
- dimSeen.add(dim);
- }
- }
-
- @Override
- protected boolean scoreSubDocsAtOnce() {
- return random().nextBoolean();
- }
- };
-
- // First search, no drill downs:
- DrillDownQuery ddq = new DrillDownQuery(FacetIndexingParams.DEFAULT, new MatchAllDocsQuery());
- DrillSidewaysResult dsr = ds.search(null, ddq, 10, fsp);
-
- assertEquals(100, dsr.hits.totalHits);
- assertEquals(2, dsr.facetResults.size());
- assertEquals("dim (0)\n b (75)\n a (25)\n", FacetTestUtils.toSimpleString(dsr.facetResults.get(0)));
- assertEquals("field (0)\n less than 10 (10)\n less than or equal to 10 (11)\n over 90 (9)\n 90 or above (10)\n over 1000 (0)\n", FacetTestUtils.toSimpleString(dsr.facetResults.get(1)));
-
- // Second search, drill down on dim=b:
- ddq = new DrillDownQuery(FacetIndexingParams.DEFAULT, new MatchAllDocsQuery());
- ddq.add(new FacetLabel("dim", "b"));
- dimSeen.clear();
- dsr = ds.search(null, ddq, 10, fsp);
-
- assertEquals(75, dsr.hits.totalHits);
- assertEquals(2, dsr.facetResults.size());
- assertEquals("dim (0)\n b (75)\n a (25)\n", FacetTestUtils.toSimpleString(dsr.facetResults.get(0)));
- assertEquals("field (0)\n less than 10 (7)\n less than or equal to 10 (8)\n over 90 (7)\n 90 or above (8)\n over 1000 (0)\n", FacetTestUtils.toSimpleString(dsr.facetResults.get(1)));
-
- // Third search, drill down on "less than or equal to 10":
- ddq = new DrillDownQuery(FacetIndexingParams.DEFAULT, new MatchAllDocsQuery());
- ddq.add("field", NumericRangeQuery.newLongRange("field", 0L, 10L, true, true));
- dimSeen.clear();
- dsr = ds.search(null, ddq, 10, fsp);
-
- assertEquals(11, dsr.hits.totalHits);
- assertEquals(2, dsr.facetResults.size());
- assertEquals("dim (0)\n b (8)\n a (3)\n", FacetTestUtils.toSimpleString(dsr.facetResults.get(0)));
- assertEquals("field (0)\n less than 10 (10)\n less than or equal to 10 (11)\n over 90 (9)\n 90 or above (10)\n over 1000 (0)\n", FacetTestUtils.toSimpleString(dsr.facetResults.get(1)));
-
- IOUtils.close(r, d);
- }
-
- public void testBasicDouble() throws Exception {
- Directory d = newDirectory();
- RandomIndexWriter w = new RandomIndexWriter(random(), d);
- Document doc = new Document();
- DoubleDocValuesField field = new DoubleDocValuesField("field", 0.0);
- doc.add(field);
- for(long l=0;l<100;l++) {
- field.setDoubleValue(l);
- w.addDocument(doc);
- }
-
- IndexReader r = w.getReader();
- w.close();
-
- RangeAccumulator a = new RangeAccumulator(new RangeFacetRequest<DoubleRange>("field",
- new DoubleRange("less than 10", 0.0, true, 10.0, false),
- new DoubleRange("less than or equal to 10", 0.0, true, 10.0, true),
- new DoubleRange("over 90", 90.0, false, 100.0, false),
- new DoubleRange("90 or above", 90.0, true, 100.0, false),
- new DoubleRange("over 1000", 1000.0, false, Double.POSITIVE_INFINITY, false)));
-
- FacetsCollector fc = FacetsCollector.create(a);
-
- IndexSearcher s = newSearcher(r);
- s.search(new MatchAllDocsQuery(), fc);
- List<FacetResult> result = fc.getFacetResults();
- assertEquals(1, result.size());
- assertEquals("field (0)\n less than 10 (10)\n less than or equal to 10 (11)\n over 90 (9)\n 90 or above (10)\n over 1000 (0)\n", FacetTestUtils.toSimpleString(result.get(0)));
-
- r.close();
- d.close();
- }
-
- public void testBasicFloat() throws Exception {
- Directory d = newDirectory();
- RandomIndexWriter w = new RandomIndexWriter(random(), d);
- Document doc = new Document();
- FloatDocValuesField field = new FloatDocValuesField("field", 0.0f);
- doc.add(field);
- for(long l=0;l<100;l++) {
- field.setFloatValue(l);
- w.addDocument(doc);
- }
-
- IndexReader r = w.getReader();
- w.close();
-
- RangeAccumulator a = new RangeAccumulator(new RangeFacetRequest<FloatRange>("field",
- new FloatRange("less than 10", 0.0f, true, 10.0f, false),
- new FloatRange("less than or equal to 10", 0.0f, true, 10.0f, true),
- new FloatRange("over 90", 90.0f, false, 100.0f, false),
- new FloatRange("90 or above", 90.0f, true, 100.0f, false),
- new FloatRange("over 1000", 1000.0f, false, Float.POSITIVE_INFINITY, false)));
-
- FacetsCollector fc = FacetsCollector.create(a);
-
- IndexSearcher s = newSearcher(r);
- s.search(new MatchAllDocsQuery(), fc);
- List<FacetResult> result = fc.getFacetResults();
- assertEquals(1, result.size());
- assertEquals("field (0)\n less than 10 (10)\n less than or equal to 10 (11)\n over 90 (9)\n 90 or above (10)\n over 1000 (0)\n", FacetTestUtils.toSimpleString(result.get(0)));
-
- r.close();
- d.close();
- }
-
- public void testRandomLongs() throws Exception {
- Directory dir = newDirectory();
- RandomIndexWriter w = new RandomIndexWriter(random(), dir);
-
- int numDocs = atLeast(1000);
- long[] values = new long[numDocs];
- for(int i=0;i<numDocs;i++) {
- Document doc = new Document();
- long v = random().nextLong();
- values[i] = v;
- doc.add(new NumericDocValuesField("field", v));
- doc.add(new LongField("field", v, Field.Store.NO));
- w.addDocument(doc);
- }
- IndexReader r = w.getReader();
- w.close();
-
- IndexSearcher s = newSearcher(r);
-
- int numIters = atLeast(10);
- for(int iter=0;iter<numIters;iter++) {
- if (VERBOSE) {
- System.out.println("TEST: iter=" + iter);
- }
- int numRange = _TestUtil.nextInt(random(), 1, 5);
- LongRange[] ranges = new LongRange[numRange];
- int[] expectedCounts = new int[numRange];
- for(int rangeID=0;rangeID<numRange;rangeID++) {
- long min = random().nextLong();
- long max = random().nextLong();
- if (min > max) {
- long x = min;
- min = max;
- max = x;
- }
- boolean minIncl = random().nextBoolean();
- boolean maxIncl = random().nextBoolean();
- ranges[rangeID] = new LongRange("r" + rangeID, min, minIncl, max, maxIncl);
-
- // Do "slow but hopefully correct" computation of
- // expected count:
- for(int i=0;i<numDocs;i++) {
- boolean accept = true;
- if (minIncl) {
- accept &= values[i] >= min;
- } else {
- accept &= values[i] > min;
- }
- if (maxIncl) {
- accept &= values[i] <= max;
- } else {
- accept &= values[i] < max;
- }
- if (accept) {
- expectedCounts[rangeID]++;
- }
- }
- }
-
- FacetsCollector fc = FacetsCollector.create(new RangeAccumulator(new RangeFacetRequest<LongRange>("field", ranges)));
- s.search(new MatchAllDocsQuery(), fc);
- List<FacetResult> results = fc.getFacetResults();
- assertEquals(1, results.size());
- List<FacetResultNode> nodes = results.get(0).getFacetResultNode().subResults;
- assertEquals(numRange, nodes.size());
- for(int rangeID=0;rangeID<numRange;rangeID++) {
- if (VERBOSE) {
- System.out.println(" range " + rangeID + " expectedCount=" + expectedCounts[rangeID]);
- }
- FacetResultNode subNode = nodes.get(rangeID);
- assertEquals("field/r" + rangeID, subNode.label.toString('/'));
- assertEquals(expectedCounts[rangeID], (int) subNode.value);
-
- LongRange range = (LongRange) ((RangeFacetRequest<?>) results.get(0).getFacetRequest()).ranges[rangeID];
-
- // Test drill-down:
- DrillDownQuery ddq = new DrillDownQuery(FacetIndexingParams.DEFAULT);
- ddq.add("field", NumericRangeQuery.newLongRange("field", range.min, range.max, range.minInclusive, range.maxInclusive));
- assertEquals(expectedCounts[rangeID], s.search(ddq, 10).totalHits);
- }
- }
-
- r.close();
- dir.close();
- }
-
- public void testRandomFloats() throws Exception {
- Directory dir = newDirectory();
- RandomIndexWriter w = new RandomIndexWriter(random(), dir);
-
- int numDocs = atLeast(1000);
- float[] values = new float[numDocs];
- for(int i=0;i<numDocs;i++) {
- Document doc = new Document();
- float v = random().nextFloat();
- values[i] = v;
- doc.add(new FloatDocValuesField("field", v));
- doc.add(new FloatField("field", v, Field.Store.NO));
- w.addDocument(doc);
- }
- IndexReader r = w.getReader();
- w.close();
-
- IndexSearcher s = newSearcher(r);
-
- int numIters = atLeast(10);
- for(int iter=0;iter<numIters;iter++) {
- if (VERBOSE) {
- System.out.println("TEST: iter=" + iter);
- }
- int numRange = _TestUtil.nextInt(random(), 1, 5);
- FloatRange[] ranges = new FloatRange[numRange];
- int[] expectedCounts = new int[numRange];
- for(int rangeID=0;rangeID<numRange;rangeID++) {
- float min = random().nextFloat();
- float max = random().nextFloat();
- if (min > max) {
- float x = min;
- min = max;
- max = x;
- }
- boolean minIncl = random().nextBoolean();
- boolean maxIncl = random().nextBoolean();
- ranges[rangeID] = new FloatRange("r" + rangeID, min, minIncl, max, maxIncl);
-
- // Do "slow but hopefully correct" computation of
- // expected count:
- for(int i=0;i<numDocs;i++) {
- boolean accept = true;
- if (minIncl) {
- accept &= values[i] >= min;
- } else {
- accept &= values[i] > min;
- }
- if (maxIncl) {
- accept &= values[i] <= max;
- } else {
- accept &= values[i] < max;
- }
- if (accept) {
- expectedCounts[rangeID]++;
- }
- }
- }
-
- FacetsCollector fc = FacetsCollector.create(new RangeAccumulator(new RangeFacetRequest<FloatRange>("field", ranges)));
- s.search(new MatchAllDocsQuery(), fc);
- List<FacetResult> results = fc.getFacetResults();
- assertEquals(1, results.size());
- List<FacetResultNode> nodes = results.get(0).getFacetResultNode().subResults;
- assertEquals(numRange, nodes.size());
- for(int rangeID=0;rangeID<numRange;rangeID++) {
- if (VERBOSE) {
- System.out.println(" range " + rangeID + " expectedCount=" + expectedCounts[rangeID]);
- }
- FacetResultNode subNode = nodes.get(rangeID);
- assertEquals("field/r" + rangeID, subNode.label.toString('/'));
- assertEquals(expectedCounts[rangeID], (int) subNode.value);
-
- FloatRange range = (FloatRange) ((RangeFacetRequest<?>) results.get(0).getFacetRequest()).ranges[rangeID];
-
- // Test drill-down:
- DrillDownQuery ddq = new DrillDownQuery(FacetIndexingParams.DEFAULT);
- ddq.add("field", NumericRangeQuery.newFloatRange("field", range.min, range.max, range.minInclusive, range.maxInclusive));
- assertEquals(expectedCounts[rangeID], s.search(ddq, 10).totalHits);
- }
- }
-
- r.close();
- dir.close();
- }
-
- public void testRandomDoubles() throws Exception {
- Directory dir = newDirectory();
- RandomIndexWriter w = new RandomIndexWriter(random(), dir);
-
- int numDocs = atLeast(1000);
- double[] values = new double[numDocs];
- for(int i=0;i<numDocs;i++) {
- Document doc = new Document();
- double v = random().nextDouble();
- values[i] = v;
- doc.add(new DoubleDocValuesField("field", v));
- doc.add(new DoubleField("field", v, Field.Store.NO));
- w.addDocument(doc);
- }
- IndexReader r = w.getReader();
- w.close();
-
- IndexSearcher s = newSearcher(r);
-
- int numIters = atLeast(10);
- for(int iter=0;iter<numIters;iter++) {
- if (VERBOSE) {
- System.out.println("TEST: iter=" + iter);
- }
- int numRange = _TestUtil.nextInt(random(), 1, 5);
- DoubleRange[] ranges = new DoubleRange[numRange];
- int[] expectedCounts = new int[numRange];
- for(int rangeID=0;rangeID<numRange;rangeID++) {
- double min = random().nextDouble();
- double max = random().nextDouble();
- if (min > max) {
- double x = min;
- min = max;
- max = x;
- }
- boolean minIncl = random().nextBoolean();
- boolean maxIncl = random().nextBoolean();
- ranges[rangeID] = new DoubleRange("r" + rangeID, min, minIncl, max, maxIncl);
-
- // Do "slow but hopefully correct" computation of
- // expected count:
- for(int i=0;i<numDocs;i++) {
- boolean accept = true;
- if (minIncl) {
- accept &= values[i] >= min;
- } else {
- accept &= values[i] > min;
- }
- if (maxIncl) {
- accept &= values[i] <= max;
- } else {
- accept &= values[i] < max;
- }
- if (accept) {
- expectedCounts[rangeID]++;
- }
- }
- }
-
- FacetsCollector fc = FacetsCollector.create(new RangeAccumulator(new RangeFacetRequest<DoubleRange>("field", ranges)));
- s.search(new MatchAllDocsQuery(), fc);
- List<FacetResult> results = fc.getFacetResults();
- assertEquals(1, results.size());
- List<FacetResultNode> nodes = results.get(0).getFacetResultNode().subResults;
- assertEquals(numRange, nodes.size());
- for(int rangeID=0;rangeID<numRange;rangeID++) {
- if (VERBOSE) {
- System.out.println(" range " + rangeID + " expectedCount=" + expectedCounts[rangeID]);
- }
- FacetResultNode subNode = nodes.get(rangeID);
- assertEquals("field/r" + rangeID, subNode.label.toString('/'));
- assertEquals(expectedCounts[rangeID], (int) subNode.value);
-
- DoubleRange range = (DoubleRange) ((RangeFacetRequest<?>) results.get(0).getFacetRequest()).ranges[rangeID];
-
- // Test drill-down:
- DrillDownQuery ddq = new DrillDownQuery(FacetIndexingParams.DEFAULT);
- ddq.add("field", NumericRangeQuery.newDoubleRange("field", range.min, range.max, range.minInclusive, range.maxInclusive));
- assertEquals(expectedCounts[rangeID], s.search(ddq, 10).totalHits);
- }
- }
-
- r.close();
- dir.close();
- }
-
- // LUCENE-5178
- public void testMissingValues() throws Exception {
- assumeTrue("codec does not support docsWithField", defaultCodecSupportsDocsWithField());
- Directory d = newDirectory();
- RandomIndexWriter w = new RandomIndexWriter(random(), d);
- Document doc = new Document();
- NumericDocValuesField field = new NumericDocValuesField("field", 0L);
- doc.add(field);
- for(long l=0;l<100;l++) {
- if (l % 5 == 0) {
- // Every 5th doc is missing the value:
- w.addDocument(new Document());
- continue;
- }
- field.setLongValue(l);
- w.addDocument(doc);
- }
-
- IndexReader r = w.getReader();
- w.close();
-
- RangeAccumulator a = new RangeAccumulator(new RangeFacetRequest<LongRange>("field",
- new LongRange("less than 10", 0L, true, 10L, false),
- new LongRange("less than or equal to 10", 0L, true, 10L, true),
- new LongRange("over 90", 90L, false, 100L, false),
- new LongRange("90 or above", 90L, true, 100L, false),
- new LongRange("over 1000", 1000L, false, Long.MAX_VALUE, false)));
-
- FacetsCollector fc = FacetsCollector.create(a);
-
- IndexSearcher s = newSearcher(r);
- s.search(new MatchAllDocsQuery(), fc);
- List<FacetResult> result = fc.getFacetResults();
- assertEquals(1, result.size());
- assertEquals("field (0)\n less than 10 (8)\n less than or equal to 10 (8)\n over 90 (8)\n 90 or above (8)\n over 1000 (0)\n", FacetTestUtils.toSimpleString(result.get(0)));
-
- r.close();
- d.close();
- }
-}
diff --git a/lucene/facet/src/test/org/apache/lucene/facet/search/TestDrillSideways.java b/lucene/facet/src/test/org/apache/lucene/facet/search/TestDrillSideways.java
deleted file mode 100644
index 2248be02387..00000000000
--- a/lucene/facet/src/test/org/apache/lucene/facet/search/TestDrillSideways.java
+++ /dev/null
@@ -1,1170 +0,0 @@
-package org.apache.lucene.facet.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.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.lucene.analysis.MockAnalyzer;
-import org.apache.lucene.document.Document;
-import org.apache.lucene.document.Field;
-import org.apache.lucene.document.StringField;
-import org.apache.lucene.facet.FacetTestCase;
-import org.apache.lucene.facet.FacetTestUtils;
-import org.apache.lucene.facet.index.FacetFields;
-import org.apache.lucene.facet.params.FacetIndexingParams;
-import org.apache.lucene.facet.params.FacetSearchParams;
-import org.apache.lucene.facet.search.DrillSideways.DrillSidewaysResult;
-import org.apache.lucene.facet.sortedset.SortedSetDocValuesFacetFields;
-import org.apache.lucene.facet.sortedset.SortedSetDocValuesReaderState;
-import org.apache.lucene.facet.taxonomy.FacetLabel;
-import org.apache.lucene.facet.taxonomy.TaxonomyReader;
-import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyReader;
-import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyWriter;
-import org.apache.lucene.index.AtomicReaderContext;
-import org.apache.lucene.index.IndexReader;
-import org.apache.lucene.index.IndexWriterConfig;
-import org.apache.lucene.index.RandomIndexWriter;
-import org.apache.lucene.index.Term;
-import org.apache.lucene.search.Collector;
-import org.apache.lucene.search.DocIdSet;
-import org.apache.lucene.search.Filter;
-import org.apache.lucene.search.IndexSearcher;
-import org.apache.lucene.search.MatchAllDocsQuery;
-import org.apache.lucene.search.Query;
-import org.apache.lucene.search.ScoreDoc;
-import org.apache.lucene.search.Scorer;
-import org.apache.lucene.search.Sort;
-import org.apache.lucene.search.SortField;
-import org.apache.lucene.search.SortField.Type;
-import org.apache.lucene.search.TermQuery;
-import org.apache.lucene.search.TopDocs;
-import org.apache.lucene.store.Directory;
-import org.apache.lucene.util.Bits;
-import org.apache.lucene.util.BytesRef;
-import org.apache.lucene.util.FixedBitSet;
-import org.apache.lucene.util.IOUtils;
-import org.apache.lucene.util.InPlaceMergeSorter;
-import org.apache.lucene.util.InfoStream;
-import org.apache.lucene.util._TestUtil;
-import org.junit.Test;
-
-public class TestDrillSideways extends FacetTestCase {
-
- private DirectoryTaxonomyWriter taxoWriter;
- private RandomIndexWriter writer;
- private FacetFields facetFields;
-
- private void add(String ... categoryPaths) throws IOException {
- Document doc = new Document();
- List<FacetLabel> paths = new ArrayList<FacetLabel>();
- for(String categoryPath : categoryPaths) {
- paths.add(new FacetLabel(categoryPath, '/'));
- }
- facetFields.addFields(doc, paths);
- writer.addDocument(doc);
- }
-
- public void testBasic() throws Exception {
- Directory dir = newDirectory();
- Directory taxoDir = newDirectory();
- writer = new RandomIndexWriter(random(), dir);
-
- // Writes facet ords to a separate directory from the
- // main index:
- taxoWriter = new DirectoryTaxonomyWriter(taxoDir, IndexWriterConfig.OpenMode.CREATE);
-
- // Reused across documents, to add the necessary facet
- // fields:
- facetFields = new FacetFields(taxoWriter);
-
- add("Author/Bob", "Publish Date/2010/10/15");
- add("Author/Lisa", "Publish Date/2010/10/20");
- add("Author/Lisa", "Publish Date/2012/1/1");
- add("Author/Susan", "Publish Date/2012/1/7");
- add("Author/Frank", "Publish Date/1999/5/5");
-
- // NRT open
- IndexSearcher searcher = newSearcher(writer.getReader());
- writer.close();
-
- //System.out.println("searcher=" + searcher);
-
- // NRT open
- TaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoWriter);
- taxoWriter.close();
-
- // Count both "Publish Date" and "Author" dimensions, in
- // drill-down:
- FacetSearchParams fsp = new FacetSearchParams(
- new CountFacetRequest(new FacetLabel("Publish Date"), 10),
- new CountFacetRequest(new FacetLabel("Author"), 10));
-
- DrillSideways ds = new DrillSideways(searcher, taxoReader);
-
- // Simple case: drill-down on a single field; in this
- // case the drill-sideways + drill-down counts ==
- // drill-down of just the query:
- DrillDownQuery ddq = new DrillDownQuery(fsp.indexingParams, new MatchAllDocsQuery());
- ddq.add(new FacetLabel("Author", "Lisa"));
- DrillSidewaysResult r = ds.search(null, ddq, 10, fsp);
-
- assertEquals(2, r.hits.totalHits);
- assertEquals(2, r.facetResults.size());
- // Publish Date is only drill-down, and Lisa published
- // one in 2012 and one in 2010:
- assertEquals("Publish Date: 2012=1 2010=1", toString(r.facetResults.get(0)));
- // Author is drill-sideways + drill-down: Lisa
- // (drill-down) published twice, and Frank/Susan/Bob
- // published once:
- assertEquals("Author: Lisa=2 Frank=1 Susan=1 Bob=1", toString(r.facetResults.get(1)));
-
- // Same simple case, but no baseQuery (pure browse):
- // drill-down on a single field; in this case the
- // drill-sideways + drill-down counts == drill-down of
- // just the query:
- ddq = new DrillDownQuery(fsp.indexingParams);
- ddq.add(new FacetLabel("Author", "Lisa"));
- r = ds.search(null, ddq, 10, fsp);
-
- assertEquals(2, r.hits.totalHits);
- assertEquals(2, r.facetResults.size());
- // Publish Date is only drill-down, and Lisa published
- // one in 2012 and one in 2010:
- assertEquals("Publish Date: 2012=1 2010=1", toString(r.facetResults.get(0)));
- assertEquals(2, r.facetResults.get(0).getNumValidDescendants());
-
- // Author is drill-sideways + drill-down: Lisa
- // (drill-down) published twice, and Frank/Susan/Bob
- // published once:
- assertEquals("Author: Lisa=2 Frank=1 Susan=1 Bob=1", toString(r.facetResults.get(1)));
- assertEquals(4, r.facetResults.get(1).getNumValidDescendants());
-
- // Another simple case: drill-down on on single fields
- // but OR of two values
- ddq = new DrillDownQuery(fsp.indexingParams, new MatchAllDocsQuery());
- ddq.add(new FacetLabel("Author", "Lisa"), new FacetLabel("Author", "Bob"));
- r = ds.search(null, ddq, 10, fsp);
- assertEquals(3, r.hits.totalHits);
- assertEquals(2, r.facetResults.size());
- // Publish Date is only drill-down: Lisa and Bob
- // (drill-down) published twice in 2010 and once in 2012:
- assertEquals("Publish Date: 2010=2 2012=1", toString(r.facetResults.get(0)));
- // Author is drill-sideways + drill-down: Lisa
- // (drill-down) published twice, and Frank/Susan/Bob
- // published once:
- assertEquals("Author: Lisa=2 Frank=1 Susan=1 Bob=1", toString(r.facetResults.get(1)));
-
- // More interesting case: drill-down on two fields
- ddq = new DrillDownQuery(fsp.indexingParams, new MatchAllDocsQuery());
- ddq.add(new FacetLabel("Author", "Lisa"));
- ddq.add(new FacetLabel("Publish Date", "2010"));
- r = ds.search(null, ddq, 10, fsp);
- assertEquals(1, r.hits.totalHits);
- assertEquals(2, r.facetResults.size());
- // Publish Date is drill-sideways + drill-down: Lisa
- // (drill-down) published once in 2010 and once in 2012:
- assertEquals("Publish Date: 2012=1 2010=1", toString(r.facetResults.get(0)));
- // Author is drill-sideways + drill-down:
- // only Lisa & Bob published (once each) in 2010:
- assertEquals("Author: Lisa=1 Bob=1", toString(r.facetResults.get(1)));
-
- // Even more interesting case: drill down on two fields,
- // but one of them is OR
- ddq = new DrillDownQuery(fsp.indexingParams, new MatchAllDocsQuery());
-
- // Drill down on Lisa or Bob:
- ddq.add(new FacetLabel("Author", "Lisa"),
- new FacetLabel("Author", "Bob"));
- ddq.add(new FacetLabel("Publish Date", "2010"));
- r = ds.search(null, ddq, 10, fsp);
- assertEquals(2, r.hits.totalHits);
- assertEquals(2, r.facetResults.size());
- // Publish Date is both drill-sideways + drill-down:
- // Lisa or Bob published twice in 2010 and once in 2012:
- assertEquals("Publish Date: 2010=2 2012=1", toString(r.facetResults.get(0)));
- // Author is drill-sideways + drill-down:
- // only Lisa & Bob published (once each) in 2010:
- assertEquals("Author: Lisa=1 Bob=1", toString(r.facetResults.get(1)));
-
- // Test drilling down on invalid field:
- ddq = new DrillDownQuery(fsp.indexingParams, new MatchAllDocsQuery());
- ddq.add(new FacetLabel("Foobar", "Baz"));
- fsp = new FacetSearchParams(
- new CountFacetRequest(new FacetLabel("Publish Date"), 10),
- new CountFacetRequest(new FacetLabel("Foobar"), 10));
- r = ds.search(null, ddq, 10, fsp);
- assertEquals(0, r.hits.totalHits);
- assertEquals(2, r.facetResults.size());
- assertEquals("Publish Date:", toString(r.facetResults.get(0)));
- assertEquals("Foobar:", toString(r.facetResults.get(1)));
-
- // Test drilling down on valid term or'd with invalid term:
- ddq = new DrillDownQuery(fsp.indexingParams, new MatchAllDocsQuery());
- ddq.add(new FacetLabel("Author", "Lisa"),
- new FacetLabel("Author", "Tom"));
- fsp = new FacetSearchParams(
- new CountFacetRequest(new FacetLabel("Publish Date"), 10),
- new CountFacetRequest(new FacetLabel("Author"), 10));
- r = ds.search(null, ddq, 10, fsp);
- assertEquals(2, r.hits.totalHits);
- assertEquals(2, r.facetResults.size());
- // Publish Date is only drill-down, and Lisa published
- // one in 2012 and one in 2010:
- assertEquals("Publish Date: 2012=1 2010=1", toString(r.facetResults.get(0)));
- // Author is drill-sideways + drill-down: Lisa
- // (drill-down) published twice, and Frank/Susan/Bob
- // published once:
- assertEquals("Author: Lisa=2 Frank=1 Susan=1 Bob=1", toString(r.facetResults.get(1)));
-
- // LUCENE-4915: test drilling down on a dimension but
- // NOT facet counting it:
- ddq = new DrillDownQuery(fsp.indexingParams, new MatchAllDocsQuery());
- ddq.add(new FacetLabel("Author", "Lisa"),
- new FacetLabel("Author", "Tom"));
- fsp = new FacetSearchParams(
- new CountFacetRequest(new FacetLabel("Publish Date"), 10));
- r = ds.search(null, ddq, 10, fsp);
- assertEquals(2, r.hits.totalHits);
- assertEquals(1, r.facetResults.size());
- // Publish Date is only drill-down, and Lisa published
- // one in 2012 and one in 2010:
- assertEquals("Publish Date: 2012=1 2010=1", toString(r.facetResults.get(0)));
-
- // Test main query gets null scorer:
- fsp = new FacetSearchParams(
- new CountFacetRequest(new FacetLabel("Publish Date"), 10),
- new CountFacetRequest(new FacetLabel("Author"), 10));
- ddq = new DrillDownQuery(fsp.indexingParams, new TermQuery(new Term("foobar", "baz")));
- ddq.add(new FacetLabel("Author", "Lisa"));
- r = ds.search(null, ddq, 10, fsp);
-
- assertEquals(0, r.hits.totalHits);
- assertEquals(2, r.facetResults.size());
- assertEquals("Publish Date:", toString(r.facetResults.get(0)));
- assertEquals("Author:", toString(r.facetResults.get(1)));
-
- searcher.getIndexReader().close();
- taxoReader.close();
- dir.close();
- taxoDir.close();
- }
-
- public void testSometimesInvalidDrillDown() throws Exception {
- Directory dir = newDirectory();
- Directory taxoDir = newDirectory();
- writer = new RandomIndexWriter(random(), dir);
-
- // Writes facet ords to a separate directory from the
- // main index:
- taxoWriter = new DirectoryTaxonomyWriter(taxoDir, IndexWriterConfig.OpenMode.CREATE);
-
- // Reused across documents, to add the necessary facet
- // fields:
- facetFields = new FacetFields(taxoWriter);
-
- add("Author/Bob", "Publish Date/2010/10/15");
- add("Author/Lisa", "Publish Date/2010/10/20");
- writer.commit();
- // 2nd segment has no Author:
- add("Foobar/Lisa", "Publish Date/2012/1/1");
-
- // NRT open
- IndexSearcher searcher = newSearcher(writer.getReader());
- writer.close();
-
- //System.out.println("searcher=" + searcher);
-
- // NRT open
- TaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoWriter);
- taxoWriter.close();
-
- // Count both "Publish Date" and "Author" dimensions, in
- // drill-down:
- FacetSearchParams fsp = new FacetSearchParams(
- new CountFacetRequest(new FacetLabel("Publish Date"), 10),
- new CountFacetRequest(new FacetLabel("Author"), 10));
-
- DrillDownQuery ddq = new DrillDownQuery(fsp.indexingParams, new MatchAllDocsQuery());
- ddq.add(new FacetLabel("Author", "Lisa"));
- DrillSidewaysResult r = new DrillSideways(searcher, taxoReader).search(null, ddq, 10, fsp);
-
- assertEquals(1, r.hits.totalHits);
- assertEquals(2, r.facetResults.size());
- // Publish Date is only drill-down, and Lisa published
- // one in 2012 and one in 2010:
- assertEquals("Publish Date: 2010=1", toString(r.facetResults.get(0)));
- // Author is drill-sideways + drill-down: Lisa
- // (drill-down) published once, and Bob
- // published once:
- assertEquals("Author: Lisa=1 Bob=1", toString(r.facetResults.get(1)));
-
- searcher.getIndexReader().close();
- taxoReader.close();
- dir.close();
- taxoDir.close();
- }
-
- private static class Doc implements Comparable<Doc> {
- String id;
- String contentToken;
-
- public Doc() {}
-
- // -1 if the doc is missing this dim, else the index
- // -into the values for this dim:
- int[] dims;
-
- // 2nd value per dim for the doc (so we test
- // multi-valued fields):
- int[] dims2;
- boolean deleted;
-
- @Override
- public int compareTo(Doc other) {
- return id.compareTo(other.id);
- }
- }
-
- private double aChance, bChance, cChance;
-
- private String randomContentToken(boolean isQuery) {
- double d = random().nextDouble();
- if (isQuery) {
- if (d < 0.33) {
- return "a";
- } else if (d < 0.66) {
- return "b";
- } else {
- return "c";
- }
- } else {
- if (d <= aChance) {
- return "a";
- } else if (d < aChance + bChance) {
- return "b";
- } else {
- return "c";
- }
- }
- }
-
- public void testMultipleRequestsPerDim() throws Exception {
- Directory dir = newDirectory();
- Directory taxoDir = newDirectory();
- writer = new RandomIndexWriter(random(), dir);
-
- // Writes facet ords to a separate directory from the
- // main index:
- taxoWriter = new DirectoryTaxonomyWriter(taxoDir, IndexWriterConfig.OpenMode.CREATE);
-
- // Reused across documents, to add the necessary facet
- // fields:
- facetFields = new FacetFields(taxoWriter);
-
- add("dim/a/x");
- add("dim/a/y");
- add("dim/a/z");
- add("dim/b");
- add("dim/c");
- add("dim/d");
-
- // NRT open
- IndexSearcher searcher = newSearcher(writer.getReader());
- writer.close();
-
- //System.out.println("searcher=" + searcher);
-
- // NRT open
- TaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoWriter);
- taxoWriter.close();
-
- // Two requests against the same dim:
- FacetSearchParams fsp = new FacetSearchParams(
- new CountFacetRequest(new FacetLabel("dim"), 10),
- new CountFacetRequest(new FacetLabel("dim", "a"), 10));
-
- DrillDownQuery ddq = new DrillDownQuery(fsp.indexingParams, new MatchAllDocsQuery());
- ddq.add(new FacetLabel("dim", "a"));
- DrillSidewaysResult r = new DrillSideways(searcher, taxoReader).search(null, ddq, 10, fsp);
-
- assertEquals(3, r.hits.totalHits);
- assertEquals(2, r.facetResults.size());
- // Publish Date is only drill-down, and Lisa published
- // one in 2012 and one in 2010:
- assertEquals("dim: a=3 d=1 c=1 b=1", toString(r.facetResults.get(0)));
- // Author is drill-sideways + drill-down: Lisa
- // (drill-down) published twice, and Frank/Susan/Bob
- // published once:
- assertEquals("a (3)\n z (1)\n y (1)\n x (1)\n", FacetTestUtils.toSimpleString(r.facetResults.get(1)));
-
- searcher.getIndexReader().close();
- taxoReader.close();
- dir.close();
- taxoDir.close();
- }
-
- public void testRandom() throws Exception {
-
- boolean canUseDV = defaultCodecSupportsSortedSet();
-
- while (aChance == 0.0) {
- aChance = random().nextDouble();
- }
- while (bChance == 0.0) {
- bChance = random().nextDouble();
- }
- while (cChance == 0.0) {
- cChance = random().nextDouble();
- }
- /*
- aChance = .01;
- bChance = 0.5;
- cChance = 1.0;
- */
- double sum = aChance + bChance + cChance;
- aChance /= sum;
- bChance /= sum;
- cChance /= sum;
-
- int numDims = _TestUtil.nextInt(random(), 2, 5);
- //int numDims = 3;
- int numDocs = atLeast(3000);
- //int numDocs = 20;
- if (VERBOSE) {
- System.out.println("numDims=" + numDims + " numDocs=" + numDocs + " aChance=" + aChance + " bChance=" + bChance + " cChance=" + cChance);
- }
- String[][] dimValues = new String[numDims][];
- int valueCount = 2;
-
- for(int dim=0;dim<numDims;dim++) {
- Set<String> values = new HashSet<String>();
- while (values.size() < valueCount) {
- String s;
- while (true) {
- s = _TestUtil.randomRealisticUnicodeString(random());
- //s = _TestUtil.randomSimpleString(random());
- // We cannot include this character else we hit
- // IllegalArgExc:
- if (s.indexOf(FacetIndexingParams.DEFAULT_FACET_DELIM_CHAR) == -1 &&
- (!canUseDV || s.indexOf('/') == -1)) {
- break;
- }
- }
- if (s.length() > 0) {
- values.add(s);
- }
- }
- dimValues[dim] = values.toArray(new String[values.size()]);
- valueCount *= 2;
- }
-
- List<Doc> docs = new ArrayList<Doc>();
- for(int i=0;i<numDocs;i++) {
- Doc doc = new Doc();
- doc.id = ""+i;
- doc.contentToken = randomContentToken(false);
- doc.dims = new int[numDims];
- doc.dims2 = new int[numDims];
- for(int dim=0;dim<numDims;dim++) {
- if (random().nextInt(5) == 3) {
- // This doc is missing this dim:
- doc.dims[dim] = -1;
- } else if (dimValues[dim].length <= 4) {
- int dimUpto = 0;
- doc.dims[dim] = dimValues[dim].length-1;
- while (dimUpto < dimValues[dim].length) {
- if (random().nextBoolean()) {
- doc.dims[dim] = dimUpto;
- break;
- }
- dimUpto++;
- }
- } else {
- doc.dims[dim] = random().nextInt(dimValues[dim].length);
- }
-
- if (random().nextInt(5) == 3) {
- // 2nd value:
- doc.dims2[dim] = random().nextInt(dimValues[dim].length);
- } else {
- doc.dims2[dim] = -1;
- }
- }
- docs.add(doc);
- }
-
- Directory d = newDirectory();
- Directory td = newDirectory();
-
- IndexWriterConfig iwc = newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()));
- iwc.setInfoStream(InfoStream.NO_OUTPUT);
- RandomIndexWriter w = new RandomIndexWriter(random(), d, iwc);
- DirectoryTaxonomyWriter tw = new DirectoryTaxonomyWriter(td, IndexWriterConfig.OpenMode.CREATE);
- facetFields = new FacetFields(tw);
- SortedSetDocValuesFacetFields dvFacetFields = new SortedSetDocValuesFacetFields();
-
- boolean doUseDV = canUseDV && random().nextBoolean();
-
- for(Doc rawDoc : docs) {
- Document doc = new Document();
- doc.add(newStringField("id", rawDoc.id, Field.Store.YES));
- doc.add(newStringField("content", rawDoc.contentToken, Field.Store.NO));
- List<FacetLabel> paths = new ArrayList<FacetLabel>();
-
- if (VERBOSE) {
- System.out.println(" doc id=" + rawDoc.id + " token=" + rawDoc.contentToken);
- }
- for(int dim=0;dim<numDims;dim++) {
- int dimValue = rawDoc.dims[dim];
- if (dimValue != -1) {
- FacetLabel cp = new FacetLabel("dim" + dim, dimValues[dim][dimValue]);
- paths.add(cp);
- doc.add(new StringField("dim" + dim, dimValues[dim][dimValue], Field.Store.YES));
- if (VERBOSE) {
- System.out.println(" dim" + dim + "=" + new BytesRef(dimValues[dim][dimValue]));
- }
- }
- int dimValue2 = rawDoc.dims2[dim];
- if (dimValue2 != -1) {
- FacetLabel cp = new FacetLabel("dim" + dim, dimValues[dim][dimValue2]);
- paths.add(cp);
- doc.add(new StringField("dim" + dim, dimValues[dim][dimValue2], Field.Store.YES));
- if (VERBOSE) {
- System.out.println(" dim" + dim + "=" + new BytesRef(dimValues[dim][dimValue2]));
- }
- }
- }
- if (!paths.isEmpty()) {
- if (doUseDV) {
- dvFacetFields.addFields(doc, paths);
- } else {
- facetFields.addFields(doc, paths);
- }
- }
-
- w.addDocument(doc);
- }
-
- if (random().nextBoolean()) {
- // Randomly delete a few docs:
- int numDel = _TestUtil.nextInt(random(), 1, (int) (numDocs*0.05));
- if (VERBOSE) {
- System.out.println("delete " + numDel);
- }
- int delCount = 0;
- while (delCount < numDel) {
- Doc doc = docs.get(random().nextInt(docs.size()));
- if (!doc.deleted) {
- if (VERBOSE) {
- System.out.println(" delete id=" + doc.id);
- }
- doc.deleted = true;
- w.deleteDocuments(new Term("id", doc.id));
- delCount++;
- }
- }
- }
-
- if (random().nextBoolean()) {
- if (VERBOSE) {
- System.out.println("TEST: forceMerge(1)...");
- }
- w.forceMerge(1);
- }
- IndexReader r = w.getReader();
- w.close();
-
- final SortedSetDocValuesReaderState sortedSetDVState;
- IndexSearcher s = newSearcher(r);
- if (doUseDV) {
- sortedSetDVState = new SortedSetDocValuesReaderState(s.getIndexReader());
- } else {
- sortedSetDVState = null;
- }
-
- if (VERBOSE) {
- System.out.println("r.numDocs() = " + r.numDocs());
- }
-
- // NRT open
- TaxonomyReader tr = new DirectoryTaxonomyReader(tw);
- tw.close();
-
- int numIters = atLeast(10);
-
- for(int iter=0;iter<numIters;iter++) {
-
- String contentToken = random().nextInt(30) == 17 ? null : randomContentToken(true);
- int numDrillDown = _TestUtil.nextInt(random(), 1, Math.min(4, numDims));
- if (VERBOSE) {
- System.out.println("\nTEST: iter=" + iter + " baseQuery=" + contentToken + " numDrillDown=" + numDrillDown + " useSortedSetDV=" + doUseDV);
- }
-
- List<FacetRequest> requests = new ArrayList<FacetRequest>();
- while(true) {
- for(int i=0;i<numDims;i++) {
- // LUCENE-4915: sometimes don't request facet
- // counts on the dim(s) we drill down on
- if (random().nextDouble() <= 0.9) {
- if (VERBOSE) {
- System.out.println(" do facet request on dim=" + i);
- }
- requests.add(new CountFacetRequest(new FacetLabel("dim" + i), dimValues[numDims-1].length));
- } else {
- if (VERBOSE) {
- System.out.println(" skip facet request on dim=" + i);
- }
- }
- }
- if (!requests.isEmpty()) {
- break;
- }
- }
- FacetSearchParams fsp = new FacetSearchParams(requests);
- String[][] drillDowns = new String[numDims][];
-
- int count = 0;
- boolean anyMultiValuedDrillDowns = false;
- while (count < numDrillDown) {
- int dim = random().nextInt(numDims);
- if (drillDowns[dim] == null) {
- if (random().nextBoolean()) {
- // Drill down on one value:
- drillDowns[dim] = new String[] {dimValues[dim][random().nextInt(dimValues[dim].length)]};
- } else {
- int orCount = _TestUtil.nextInt(random(), 1, Math.min(5, dimValues[dim].length));
- drillDowns[dim] = new String[orCount];
- anyMultiValuedDrillDowns |= orCount > 1;
- for(int i=0;i<orCount;i++) {
- while (true) {
- String value = dimValues[dim][random().nextInt(dimValues[dim].length)];
- for(int j=0;j<i;j++) {
- if (value.equals(drillDowns[dim][j])) {
- value = null;
- break;
- }
- }
- if (value != null) {
- drillDowns[dim][i] = value;
- break;
- }
- }
- }
- }
- if (VERBOSE) {
- BytesRef[] values = new BytesRef[drillDowns[dim].length];
- for(int i=0;i<values.length;i++) {
- values[i] = new BytesRef(drillDowns[dim][i]);
- }
- System.out.println(" dim" + dim + "=" + Arrays.toString(values));
- }
- count++;
- }
- }
-
- Query baseQuery;
- if (contentToken == null) {
- baseQuery = new MatchAllDocsQuery();
- } else {
- baseQuery = new TermQuery(new Term("content", contentToken));
- }
-
- DrillDownQuery ddq = new DrillDownQuery(fsp.indexingParams, baseQuery);
-
- for(int dim=0;dim<numDims;dim++) {
- if (drillDowns[dim] != null) {
- FacetLabel[] paths = new FacetLabel[drillDowns[dim].length];
- int upto = 0;
- for(String value : drillDowns[dim]) {
- paths[upto++] = new FacetLabel("dim" + dim, value);
- }
- ddq.add(paths);
- }
- }
-
- Filter filter;
- if (random().nextInt(7) == 6) {
- if (VERBOSE) {
- System.out.println(" only-even filter");
- }
- filter = new Filter() {
- @Override
- public DocIdSet getDocIdSet(AtomicReaderContext context, Bits acceptDocs) throws IOException {
- int maxDoc = context.reader().maxDoc();
- final FixedBitSet bits = new FixedBitSet(maxDoc);
- for(int docID=0;docID < maxDoc;docID++) {
- // Keeps only the even ids:
- if ((acceptDocs == null || acceptDocs.get(docID)) && ((Integer.parseInt(context.reader().document(docID).get("id")) & 1) == 0)) {
- bits.set(docID);
- }
- }
- return bits;
- }
- };
- } else {
- filter = null;
- }
-
- // Verify docs are always collected in order. If we
- // had an AssertingScorer it could catch it when
- // Weight.scoresDocsOutOfOrder lies!:
- new DrillSideways(s, tr).search(ddq,
- new Collector() {
- int lastDocID;
-
- @Override
- public void setScorer(Scorer s) {
- }
-
- @Override
- public void collect(int doc) {
- assert doc > lastDocID;
- lastDocID = doc;
- }
-
- @Override
- public void setNextReader(AtomicReaderContext context) {
- lastDocID = -1;
- }
-
- @Override
- public boolean acceptsDocsOutOfOrder() {
- return false;
- }
- }, fsp);
-
- // Also separately verify that DS respects the
- // scoreSubDocsAtOnce method, to ensure that all
- // subScorers are on the same docID:
- if (!anyMultiValuedDrillDowns) {
- // Can only do this test when there are no OR'd
- // drill-down values, beacuse in that case it's
- // easily possible for one of the DD terms to be on
- // a future docID:
- new DrillSideways(s, tr) {
- @Override
- protected boolean scoreSubDocsAtOnce() {
- return true;
- }
- }.search(ddq, new AssertingSubDocsAtOnceCollector(), fsp);
- }
-
- SimpleFacetResult expected = slowDrillSidewaysSearch(s, requests, docs, contentToken, drillDowns, dimValues, filter);
-
- Sort sort = new Sort(new SortField("id", SortField.Type.STRING));
- DrillSideways ds;
- if (doUseDV) {
- ds = new DrillSideways(s, sortedSetDVState);
- } else {
- ds = new DrillSideways(s, tr);
- }
-
- // Retrieve all facets:
- DrillSidewaysResult actual = ds.search(ddq, filter, null, numDocs, sort, true, true, fsp);
-
- TopDocs hits = s.search(baseQuery, numDocs);
- Map<String,Float> scores = new HashMap<String,Float>();
- for(ScoreDoc sd : hits.scoreDocs) {
- scores.put(s.doc(sd.doc).get("id"), sd.score);
- }
- if (VERBOSE) {
- System.out.println(" verify all facets");
- }
- verifyEquals(requests, dimValues, s, expected, actual, scores, -1, doUseDV);
-
- // Retrieve topN facets:
- int topN = _TestUtil.nextInt(random(), 1, 20);
-
- List<FacetRequest> newRequests = new ArrayList<FacetRequest>();
- for(FacetRequest oldRequest : requests) {
- newRequests.add(new CountFacetRequest(oldRequest.categoryPath, topN));
- }
- fsp = new FacetSearchParams(newRequests);
- actual = ds.search(ddq, filter, null, numDocs, sort, true, true, fsp);
- if (VERBOSE) {
- System.out.println(" verify topN=" + topN);
- }
- verifyEquals(newRequests, dimValues, s, expected, actual, scores, topN, doUseDV);
-
- // Make sure drill down doesn't change score:
- TopDocs ddqHits = s.search(ddq, filter, numDocs);
- assertEquals(expected.hits.size(), ddqHits.totalHits);
- for(int i=0;i<expected.hits.size();i++) {
- // Score should be IDENTICAL:
- assertEquals(scores.get(expected.hits.get(i).id), ddqHits.scoreDocs[i].score, 0.0f);
- }
- }
-
- tr.close();
- r.close();
- td.close();
- d.close();
- }
-
- private static class Counters {
- int[][] counts;
-
- public Counters(String[][] dimValues) {
- counts = new int[dimValues.length][];
- for(int dim=0;dim<dimValues.length;dim++) {
- counts[dim] = new int[dimValues[dim].length];
- }
- }
-
- public void inc(int[] dims, int[] dims2) {
- inc(dims, dims2, -1);
- }
-
- public void inc(int[] dims, int[] dims2, int onlyDim) {
- assert dims.length == counts.length;
- assert dims2.length == counts.length;
- for(int dim=0;dim<dims.length;dim++) {
- if (onlyDim == -1 || dim == onlyDim) {
- if (dims[dim] != -1) {
- counts[dim][dims[dim]]++;
- }
- if (dims2[dim] != -1 && dims2[dim] != dims[dim]) {
- counts[dim][dims2[dim]]++;
- }
- }
- }
- }
- }
-
- private static class SimpleFacetResult {
- List<Doc> hits;
- int[][] counts;
- int[] uniqueCounts;
- public SimpleFacetResult() {}
- }
-
- private int[] getTopNOrds(final int[] counts, final String[] values, int topN) {
- final int[] ids = new int[counts.length];
- for(int i=0;i<ids.length;i++) {
- ids[i] = i;
- }
-
- // Naive (on purpose, to reduce bug in tester/gold):
- // sort all ids, then return top N slice:
- new InPlaceMergeSorter() {
-
- @Override
- protected void swap(int i, int j) {
- int id = ids[i];
- ids[i] = ids[j];
- ids[j] = id;
- }
-
- @Override
- protected int compare(int i, int j) {
- int counti = counts[ids[i]];
- int countj = counts[ids[j]];
- // Sort by count descending...
- if (counti > countj) {
- return -1;
- } else if (counti < countj) {
- return 1;
- } else {
- // ... then by label ascending:
- return new BytesRef(values[ids[i]]).compareTo(new BytesRef(values[ids[j]]));
- }
- }
-
- }.sort(0, ids.length);
-
- if (topN > ids.length) {
- topN = ids.length;
- }
-
- int numSet = topN;
- for(int i=0;i<topN;i++) {
- if (counts[ids[i]] == 0) {
- numSet = i;
- break;
- }
- }
-
- int[] topNIDs = new int[numSet];
- System.arraycopy(ids, 0, topNIDs, 0, topNIDs.length);
- return topNIDs;
- }
-
- private SimpleFacetResult slowDrillSidewaysSearch(IndexSearcher s, List<FacetRequest> requests, List<Doc> docs,
- String contentToken, String[][] drillDowns,
- String[][] dimValues, Filter onlyEven) throws Exception {
- int numDims = dimValues.length;
-
- List<Doc> hits = new ArrayList<Doc>();
- Counters drillDownCounts = new Counters(dimValues);
- Counters[] drillSidewaysCounts = new Counters[dimValues.length];
- for(int dim=0;dim<numDims;dim++) {
- drillSidewaysCounts[dim] = new Counters(dimValues);
- }
-
- if (VERBOSE) {
- System.out.println(" compute expected");
- }
-
- nextDoc: for(Doc doc : docs) {
- if (doc.deleted) {
- continue;
- }
- if (onlyEven != null & (Integer.parseInt(doc.id) & 1) != 0) {
- continue;
- }
- if (contentToken == null || doc.contentToken.equals(contentToken)) {
- int failDim = -1;
- for(int dim=0;dim<numDims;dim++) {
- if (drillDowns[dim] != null) {
- String docValue = doc.dims[dim] == -1 ? null : dimValues[dim][doc.dims[dim]];
- String docValue2 = doc.dims2[dim] == -1 ? null : dimValues[dim][doc.dims2[dim]];
- boolean matches = false;
- for(String value : drillDowns[dim]) {
- if (value.equals(docValue) || value.equals(docValue2)) {
- matches = true;
- break;
- }
- }
- if (!matches) {
- if (failDim == -1) {
- // Doc could be a near-miss, if no other dim fails
- failDim = dim;
- } else {
- // Doc isn't a hit nor a near-miss
- continue nextDoc;
- }
- }
- }
- }
-
- if (failDim == -1) {
- if (VERBOSE) {
- System.out.println(" exp: id=" + doc.id + " is a hit");
- }
- // Hit:
- hits.add(doc);
- drillDownCounts.inc(doc.dims, doc.dims2);
- for(int dim=0;dim<dimValues.length;dim++) {
- drillSidewaysCounts[dim].inc(doc.dims, doc.dims2);
- }
- } else {
- if (VERBOSE) {
- System.out.println(" exp: id=" + doc.id + " is a near-miss on dim=" + failDim);
- }
- drillSidewaysCounts[failDim].inc(doc.dims, doc.dims2, failDim);
- }
- }
- }
-
- Map<String,Integer> idToDocID = new HashMap<String,Integer>();
- for(int i=0;i<s.getIndexReader().maxDoc();i++) {
- idToDocID.put(s.doc(i).get("id"), i);
- }
-
- Collections.sort(hits);
-
- SimpleFacetResult res = new SimpleFacetResult();
- res.hits = hits;
- res.counts = new int[numDims][];
- res.uniqueCounts = new int[numDims];
- for (int i = 0; i < requests.size(); i++) {
- int dim = Integer.parseInt(requests.get(i).categoryPath.components[0].substring(3));
- if (drillDowns[dim] != null) {
- res.counts[dim] = drillSidewaysCounts[dim].counts[dim];
- } else {
- res.counts[dim] = drillDownCounts.counts[dim];
- }
- int uniqueCount = 0;
- for (int j = 0; j < res.counts[dim].length; j++) {
- if (res.counts[dim][j] != 0) {
- uniqueCount++;
- }
- }
- res.uniqueCounts[dim] = uniqueCount;
- }
-
- return res;
- }
-
- void verifyEquals(List<FacetRequest> requests, String[][] dimValues, IndexSearcher s, SimpleFacetResult expected,
- DrillSidewaysResult actual, Map<String,Float> scores, int topN, boolean isSortedSetDV) throws Exception {
- if (VERBOSE) {
- System.out.println(" verify totHits=" + expected.hits.size());
- }
- assertEquals(expected.hits.size(), actual.hits.totalHits);
- assertEquals(expected.hits.size(), actual.hits.scoreDocs.length);
- for(int i=0;i<expected.hits.size();i++) {
- if (VERBOSE) {
- System.out.println(" hit " + i + " expected=" + expected.hits.get(i).id);
- }
- assertEquals(expected.hits.get(i).id,
- s.doc(actual.hits.scoreDocs[i].doc).get("id"));
- // Score should be IDENTICAL:
- assertEquals(scores.get(expected.hits.get(i).id), actual.hits.scoreDocs[i].score, 0.0f);
- }
-
- int numExpected = 0;
- for(int dim=0;dim<expected.counts.length;dim++) {
- if (expected.counts[dim] != null) {
- numExpected++;
- }
- }
-
- assertEquals(numExpected, actual.facetResults.size());
-
- for(int dim=0;dim<expected.counts.length;dim++) {
- if (expected.counts[dim] == null) {
- continue;
- }
- int idx = -1;
- for(int i=0;i<requests.size();i++) {
- if (Integer.parseInt(requests.get(i).categoryPath.components[0].substring(3)) == dim) {
- idx = i;
- break;
- }
- }
- assert idx != -1;
- FacetResult fr = actual.facetResults.get(idx);
- List<FacetResultNode> subResults = fr.getFacetResultNode().subResults;
- if (VERBOSE) {
- System.out.println(" dim" + dim);
- System.out.println(" actual");
- }
-
- Map<String,Integer> actualValues = new HashMap<String,Integer>();
- idx = 0;
- for(FacetResultNode childNode : subResults) {
- actualValues.put(childNode.label.components[1], (int) childNode.value);
- if (VERBOSE) {
- System.out.println(" " + idx + ": " + new BytesRef(childNode.label.components[1]) + ": " + (int) childNode.value);
- idx++;
- }
- }
-
- if (topN != -1) {
- int[] topNIDs = getTopNOrds(expected.counts[dim], dimValues[dim], topN);
- if (VERBOSE) {
- idx = 0;
- System.out.println(" expected (sorted)");
- for(int i=0;i<topNIDs.length;i++) {
- int expectedOrd = topNIDs[i];
- String value = dimValues[dim][expectedOrd];
- System.out.println(" " + idx + ": " + new BytesRef(value) + ": " + expected.counts[dim][expectedOrd]);
- idx++;
- }
- }
- if (VERBOSE) {
- System.out.println(" topN=" + topN + " expectedTopN=" + topNIDs.length);
- }
-
- assertEquals(topNIDs.length, subResults.size());
- for(int i=0;i<topNIDs.length;i++) {
- FacetResultNode node = subResults.get(i);
- int expectedOrd = topNIDs[i];
- assertEquals(expected.counts[dim][expectedOrd], (int) node.value);
- assertEquals(2, node.label.length);
- if (isSortedSetDV) {
- // Tie-break facet labels are only in unicode
- // order with SortedSetDVFacets:
- assertEquals("value @ idx=" + i, dimValues[dim][expectedOrd], node.label.components[1]);
- }
- }
- } else {
-
- if (VERBOSE) {
- idx = 0;
- System.out.println(" expected (unsorted)");
- for(int i=0;i<dimValues[dim].length;i++) {
- String value = dimValues[dim][i];
- if (expected.counts[dim][i] != 0) {
- System.out.println(" " + idx + ": " + new BytesRef(value) + ": " + expected.counts[dim][i]);
- idx++;
- }
- }
- }
-
- int setCount = 0;
- for(int i=0;i<dimValues[dim].length;i++) {
- String value = dimValues[dim][i];
- if (expected.counts[dim][i] != 0) {
- assertTrue(actualValues.containsKey(value));
- assertEquals(expected.counts[dim][i], actualValues.get(value).intValue());
- setCount++;
- } else {
- assertFalse(actualValues.containsKey(value));
- }
- }
- assertEquals(setCount, actualValues.size());
- }
-
- assertEquals("dim=" + dim, expected.uniqueCounts[dim], fr.getNumValidDescendants());
- }
- }
-
- /** Just gathers counts of values under the dim. */
- private String toString(FacetResult fr) {
- StringBuilder b = new StringBuilder();
- FacetResultNode node = fr.getFacetResultNode();
- b.append(node.label);
- b.append(":");
- for(FacetResultNode childNode : node.subResults) {
- b.append(' ');
- b.append(childNode.label.components[1]);
- b.append('=');
- b.append((int) childNode.value);
- }
- return b.toString();
- }
-
- @Test
- public void testEmptyIndex() throws Exception {
- // LUCENE-5045: make sure DrillSideways works with an empty index
- Directory dir = newDirectory();
- Directory taxoDir = newDirectory();
- writer = new RandomIndexWriter(random(), dir);
- taxoWriter = new DirectoryTaxonomyWriter(taxoDir, IndexWriterConfig.OpenMode.CREATE);
- IndexSearcher searcher = newSearcher(writer.getReader());
- writer.close();
- TaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoWriter);
- taxoWriter.close();
-
- // Count "Author"
- FacetSearchParams fsp = new FacetSearchParams(new CountFacetRequest(new FacetLabel("Author"), 10));
-
- DrillSideways ds = new DrillSideways(searcher, taxoReader);
- DrillDownQuery ddq = new DrillDownQuery(fsp.indexingParams, new MatchAllDocsQuery());
- ddq.add(new FacetLabel("Author", "Lisa"));
-
- DrillSidewaysResult r = ds.search(null, ddq, 10, fsp); // this used to fail on IllegalArgEx
- assertEquals(0, r.hits.totalHits);
-
- r = ds.search(ddq, null, null, 10, new Sort(new SortField("foo", Type.INT)), false, false, fsp); // this used to fail on IllegalArgEx
- assertEquals(0, r.hits.totalHits);
-
- IOUtils.close(searcher.getIndexReader(), taxoReader, dir, taxoDir);
- }
-}
-
diff --git a/lucene/facet/src/test/org/apache/lucene/facet/simple/TestRangeFacets.java b/lucene/facet/src/test/org/apache/lucene/facet/simple/TestRangeFacets.java
index 8e4dfcbf1e4..176c4c0d66f 100644
--- a/lucene/facet/src/test/org/apache/lucene/facet/simple/TestRangeFacets.java
+++ b/lucene/facet/src/test/org/apache/lucene/facet/simple/TestRangeFacets.java
@@ -19,8 +19,10 @@ package org.apache.lucene.facet.simple;
import java.io.IOException;
import java.util.Collections;
+import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
+import java.util.Map;
import java.util.Set;
import org.apache.lucene.document.Document;
@@ -36,16 +38,17 @@ import org.apache.lucene.facet.FacetTestUtils;
import org.apache.lucene.facet.index.FacetFields;
import org.apache.lucene.facet.params.FacetIndexingParams;
import org.apache.lucene.facet.params.FacetSearchParams;
+import org.apache.lucene.facet.range.DoubleRange;
+import org.apache.lucene.facet.range.FloatRange;
import org.apache.lucene.facet.range.LongRange;
import org.apache.lucene.facet.search.CountFacetRequest;
import org.apache.lucene.facet.search.DrillDownQuery;
-import org.apache.lucene.facet.search.DrillSideways.DrillSidewaysResult;
-import org.apache.lucene.facet.search.DrillSideways;
import org.apache.lucene.facet.search.FacetRequest;
import org.apache.lucene.facet.search.FacetResult;
import org.apache.lucene.facet.search.FacetResultNode;
import org.apache.lucene.facet.search.FacetsAccumulator;
import org.apache.lucene.facet.search.FacetsCollector;
+import org.apache.lucene.facet.simple.SimpleDrillSideways.SimpleDrillSidewaysResult;
import org.apache.lucene.facet.sortedset.SortedSetDocValuesReaderState;
import org.apache.lucene.facet.taxonomy.FacetLabel;
import org.apache.lucene.facet.taxonomy.TaxonomyReader;
@@ -61,6 +64,8 @@ import org.apache.lucene.store.Directory;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util._TestUtil;
+
+// nocommit rename to TestRangeFacetCounts
public class TestRangeFacets extends FacetTestCase {
public void testBasicLong() throws Exception {
@@ -90,13 +95,462 @@ public class TestRangeFacets extends FacetTestCase {
new LongRange("90 or above", 90L, true, 100L, false),
new LongRange("over 1000", 1000L, false, Long.MAX_VALUE, true));
- SimpleFacetResult result = facets.getTopChildren(10, null);
- assertEquals("null (101)\n less than 10 (10)\n less than or equal to 10 (11)\n over 90 (9)\n 90 or above (10)\n over 1000 (1)\n",
+ SimpleFacetResult result = facets.getTopChildren(10, "field");
+ assertEquals("field (101)\n less than 10 (10)\n less than or equal to 10 (11)\n over 90 (9)\n 90 or above (10)\n over 1000 (1)\n",
result.toString());
r.close();
d.close();
}
- // nocommit pull over all the other tests
+ /** Tests single request that mixes Range and non-Range
+ * faceting, with DrillSideways and taxonomy. */
+ public void testMixedRangeAndNonRangeTaxonomy() throws Exception {
+ Directory d = newDirectory();
+ RandomIndexWriter w = new RandomIndexWriter(random(), d);
+ Directory td = newDirectory();
+ DirectoryTaxonomyWriter tw = new DirectoryTaxonomyWriter(td, IndexWriterConfig.OpenMode.CREATE);
+
+ FacetsConfig config = new FacetsConfig();
+ DocumentBuilder builder = new DocumentBuilder(tw, config);
+
+ for (long l = 0; l < 100; l++) {
+ Document doc = new Document();
+ // For computing range facet counts:
+ doc.add(new NumericDocValuesField("field", l));
+ // For drill down by numeric range:
+ doc.add(new LongField("field", l, Field.Store.NO));
+
+ if ((l&3) == 0) {
+ doc.add(new FacetField("dim", "a"));
+ } else {
+ doc.add(new FacetField("dim", "b"));
+ }
+ w.addDocument(builder.build(doc));
+ }
+
+ final IndexReader r = w.getReader();
+
+ final TaxonomyReader tr = new DirectoryTaxonomyReader(tw);
+
+ IndexSearcher s = newSearcher(r);
+
+ SimpleDrillSideways ds = new SimpleDrillSideways(s, config, tr) {
+
+ @Override
+ protected Facets buildFacetsResult(SimpleFacetsCollector drillDowns, SimpleFacetsCollector[] drillSideways, String[] drillSidewaysDims) throws IOException {
+ // nocommit this is awkward... can we improve?
+ // nocommit is drillDowns allowed to be null?
+ // should it?
+ SimpleFacetsCollector dimFC = drillDowns;
+ SimpleFacetsCollector fieldFC = drillDowns;
+ if (drillSideways != null) {
+ for(int i=0;i<drillSideways.length;i++) {
+ String dim = drillSidewaysDims[i];
+ if (dim.equals("field")) {
+ fieldFC = drillSideways[i];
+ } else {
+ dimFC = drillSideways[i];
+ }
+ }
+ }
+
+ Map<String,Facets> byDim = new HashMap<String,Facets>();
+ byDim.put("field",
+ new RangeFacetCounts("field", fieldFC,
+ new LongRange("less than 10", 0L, true, 10L, false),
+ new LongRange("less than or equal to 10", 0L, true, 10L, true),
+ new LongRange("over 90", 90L, false, 100L, false),
+ new LongRange("90 or above", 90L, true, 100L, false),
+ new LongRange("over 1000", 1000L, false, Long.MAX_VALUE, false)));
+ byDim.put("dim", getTaxonomyFacetCounts(taxoReader, config, dimFC));
+ return new MultiFacets(byDim, null);
+ }
+
+ @Override
+ protected boolean scoreSubDocsAtOnce() {
+ return random().nextBoolean();
+ }
+ };
+
+ // First search, no drill downs:
+ SimpleDrillDownQuery ddq = new SimpleDrillDownQuery(config);
+ SimpleDrillSidewaysResult dsr = ds.search(null, ddq, 10);
+
+ assertEquals(100, dsr.hits.totalHits);
+ assertEquals("dim (100)\n b (75)\n a (25)\n", dsr.facets.getTopChildren(10, "dim").toString());
+ assertEquals("field (100)\n less than 10 (10)\n less than or equal to 10 (11)\n over 90 (9)\n 90 or above (10)\n over 1000 (0)\n",
+ dsr.facets.getTopChildren(10, "field").toString());
+
+ // Second search, drill down on dim=b:
+ ddq = new SimpleDrillDownQuery(config);
+ ddq.add("dim", "b");
+ dsr = ds.search(null, ddq, 10);
+
+ assertEquals(75, dsr.hits.totalHits);
+ assertEquals("dim (100)\n b (75)\n a (25)\n", dsr.facets.getTopChildren(10, "dim").toString());
+ assertEquals("field (75)\n less than 10 (7)\n less than or equal to 10 (8)\n over 90 (7)\n 90 or above (8)\n over 1000 (0)\n",
+ dsr.facets.getTopChildren(10, "field").toString());
+
+ // Third search, drill down on "less than or equal to 10":
+ ddq = new SimpleDrillDownQuery(config);
+ ddq.add("field", NumericRangeQuery.newLongRange("field", 0L, 10L, true, true));
+ dsr = ds.search(null, ddq, 10);
+
+ assertEquals(11, dsr.hits.totalHits);
+ assertEquals("dim (11)\n b (8)\n a (3)\n", dsr.facets.getTopChildren(10, "dim").toString());
+ assertEquals("field (100)\n less than 10 (10)\n less than or equal to 10 (11)\n over 90 (9)\n 90 or above (10)\n over 1000 (0)\n",
+ dsr.facets.getTopChildren(10, "field").toString());
+ IOUtils.close(tw, tr, td, w, r, d);
+ }
+
+ public void testBasicDouble() throws Exception {
+ Directory d = newDirectory();
+ RandomIndexWriter w = new RandomIndexWriter(random(), d);
+ Document doc = new Document();
+ DoubleDocValuesField field = new DoubleDocValuesField("field", 0.0);
+ doc.add(field);
+ for(long l=0;l<100;l++) {
+ field.setDoubleValue(l);
+ w.addDocument(doc);
+ }
+
+ IndexReader r = w.getReader();
+
+ SimpleFacetsCollector fc = new SimpleFacetsCollector();
+
+ IndexSearcher s = newSearcher(r);
+ s.search(new MatchAllDocsQuery(), fc);
+ Facets facets = new RangeFacetCounts("field", fc,
+ new DoubleRange("less than 10", 0.0, true, 10.0, false),
+ new DoubleRange("less than or equal to 10", 0.0, true, 10.0, true),
+ new DoubleRange("over 90", 90.0, false, 100.0, false),
+ new DoubleRange("90 or above", 90.0, true, 100.0, false),
+ new DoubleRange("over 1000", 1000.0, false, Double.POSITIVE_INFINITY, false));
+
+ assertEquals("field (100)\n less than 10 (10)\n less than or equal to 10 (11)\n over 90 (9)\n 90 or above (10)\n over 1000 (0)\n",
+ facets.getTopChildren(10, "field").toString());
+
+ IOUtils.close(w, r, d);
+ }
+
+ public void testBasicFloat() throws Exception {
+ Directory d = newDirectory();
+ RandomIndexWriter w = new RandomIndexWriter(random(), d);
+ Document doc = new Document();
+ FloatDocValuesField field = new FloatDocValuesField("field", 0.0f);
+ doc.add(field);
+ for(long l=0;l<100;l++) {
+ field.setFloatValue(l);
+ w.addDocument(doc);
+ }
+
+ IndexReader r = w.getReader();
+
+ SimpleFacetsCollector fc = new SimpleFacetsCollector();
+
+ IndexSearcher s = newSearcher(r);
+ s.search(new MatchAllDocsQuery(), fc);
+
+ Facets facets = new RangeFacetCounts("field", fc,
+ new FloatRange("less than 10", 0.0f, true, 10.0f, false),
+ new FloatRange("less than or equal to 10", 0.0f, true, 10.0f, true),
+ new FloatRange("over 90", 90.0f, false, 100.0f, false),
+ new FloatRange("90 or above", 90.0f, true, 100.0f, false),
+ new FloatRange("over 1000", 1000.0f, false, Float.POSITIVE_INFINITY, false));
+
+ assertEquals("field (100)\n less than 10 (10)\n less than or equal to 10 (11)\n over 90 (9)\n 90 or above (10)\n over 1000 (0)\n",
+ facets.getTopChildren(10, "field").toString());
+
+ IOUtils.close(w, r, d);
+ }
+
+ public void testRandomLongs() throws Exception {
+ Directory dir = newDirectory();
+ RandomIndexWriter w = new RandomIndexWriter(random(), dir);
+
+ int numDocs = atLeast(1000);
+ long[] values = new long[numDocs];
+ for(int i=0;i<numDocs;i++) {
+ Document doc = new Document();
+ long v = random().nextLong();
+ values[i] = v;
+ doc.add(new NumericDocValuesField("field", v));
+ doc.add(new LongField("field", v, Field.Store.NO));
+ w.addDocument(doc);
+ }
+ IndexReader r = w.getReader();
+
+ IndexSearcher s = newSearcher(r);
+ FacetsConfig config = new FacetsConfig();
+
+ int numIters = atLeast(10);
+ for(int iter=0;iter<numIters;iter++) {
+ if (VERBOSE) {
+ System.out.println("TEST: iter=" + iter);
+ }
+ int numRange = _TestUtil.nextInt(random(), 1, 5);
+ LongRange[] ranges = new LongRange[numRange];
+ int[] expectedCounts = new int[numRange];
+ for(int rangeID=0;rangeID<numRange;rangeID++) {
+ long min = random().nextLong();
+ long max = random().nextLong();
+ if (min > max) {
+ long x = min;
+ min = max;
+ max = x;
+ }
+ boolean minIncl = random().nextBoolean();
+ boolean maxIncl = random().nextBoolean();
+ ranges[rangeID] = new LongRange("r" + rangeID, min, minIncl, max, maxIncl);
+
+ // Do "slow but hopefully correct" computation of
+ // expected count:
+ for(int i=0;i<numDocs;i++) {
+ boolean accept = true;
+ if (minIncl) {
+ accept &= values[i] >= min;
+ } else {
+ accept &= values[i] > min;
+ }
+ if (maxIncl) {
+ accept &= values[i] <= max;
+ } else {
+ accept &= values[i] < max;
+ }
+ if (accept) {
+ expectedCounts[rangeID]++;
+ }
+ }
+ }
+
+ SimpleFacetsCollector sfc = new SimpleFacetsCollector();
+ s.search(new MatchAllDocsQuery(), sfc);
+ Facets facets = new RangeFacetCounts("field", sfc, ranges);
+ SimpleFacetResult result = facets.getTopChildren(10, "field");
+ assertEquals(numRange, result.labelValues.length);
+ for(int rangeID=0;rangeID<numRange;rangeID++) {
+ if (VERBOSE) {
+ System.out.println(" range " + rangeID + " expectedCount=" + expectedCounts[rangeID]);
+ }
+ LabelAndValue subNode = result.labelValues[rangeID];
+ assertEquals("r" + rangeID, subNode.label);
+ assertEquals(expectedCounts[rangeID], subNode.value.intValue());
+
+ LongRange range = ranges[rangeID];
+
+ // Test drill-down:
+ SimpleDrillDownQuery ddq = new SimpleDrillDownQuery(config);
+ ddq.add("field", NumericRangeQuery.newLongRange("field", range.min, range.max, range.minInclusive, range.maxInclusive));
+ assertEquals(expectedCounts[rangeID], s.search(ddq, 10).totalHits);
+ }
+ }
+
+ IOUtils.close(w, r, dir);
+ }
+
+ public void testRandomFloats() throws Exception {
+ Directory dir = newDirectory();
+ RandomIndexWriter w = new RandomIndexWriter(random(), dir);
+
+ int numDocs = atLeast(1000);
+ float[] values = new float[numDocs];
+ for(int i=0;i<numDocs;i++) {
+ Document doc = new Document();
+ float v = random().nextFloat();
+ values[i] = v;
+ doc.add(new FloatDocValuesField("field", v));
+ doc.add(new FloatField("field", v, Field.Store.NO));
+ w.addDocument(doc);
+ }
+ IndexReader r = w.getReader();
+
+ IndexSearcher s = newSearcher(r);
+ FacetsConfig config = new FacetsConfig();
+
+ int numIters = atLeast(10);
+ for(int iter=0;iter<numIters;iter++) {
+ if (VERBOSE) {
+ System.out.println("TEST: iter=" + iter);
+ }
+ int numRange = _TestUtil.nextInt(random(), 1, 5);
+ FloatRange[] ranges = new FloatRange[numRange];
+ int[] expectedCounts = new int[numRange];
+ for(int rangeID=0;rangeID<numRange;rangeID++) {
+ float min = random().nextFloat();
+ float max = random().nextFloat();
+ if (min > max) {
+ float x = min;
+ min = max;
+ max = x;
+ }
+ boolean minIncl = random().nextBoolean();
+ boolean maxIncl = random().nextBoolean();
+ ranges[rangeID] = new FloatRange("r" + rangeID, min, minIncl, max, maxIncl);
+
+ // Do "slow but hopefully correct" computation of
+ // expected count:
+ for(int i=0;i<numDocs;i++) {
+ boolean accept = true;
+ if (minIncl) {
+ accept &= values[i] >= min;
+ } else {
+ accept &= values[i] > min;
+ }
+ if (maxIncl) {
+ accept &= values[i] <= max;
+ } else {
+ accept &= values[i] < max;
+ }
+ if (accept) {
+ expectedCounts[rangeID]++;
+ }
+ }
+ }
+
+ SimpleFacetsCollector sfc = new SimpleFacetsCollector();
+ s.search(new MatchAllDocsQuery(), sfc);
+ Facets facets = new RangeFacetCounts("field", sfc, ranges);
+ SimpleFacetResult result = facets.getTopChildren(10, "field");
+ assertEquals(numRange, result.labelValues.length);
+ for(int rangeID=0;rangeID<numRange;rangeID++) {
+ if (VERBOSE) {
+ System.out.println(" range " + rangeID + " expectedCount=" + expectedCounts[rangeID]);
+ }
+ LabelAndValue subNode = result.labelValues[rangeID];
+ assertEquals("r" + rangeID, subNode.label);
+ assertEquals(expectedCounts[rangeID], subNode.value.intValue());
+
+ FloatRange range = ranges[rangeID];
+
+ // Test drill-down:
+ SimpleDrillDownQuery ddq = new SimpleDrillDownQuery(config);
+ ddq.add("field", NumericRangeQuery.newFloatRange("field", range.min, range.max, range.minInclusive, range.maxInclusive));
+ assertEquals(expectedCounts[rangeID], s.search(ddq, 10).totalHits);
+ }
+ }
+
+ IOUtils.close(w, r, dir);
+ }
+
+ public void testRandomDoubles() throws Exception {
+ Directory dir = newDirectory();
+ RandomIndexWriter w = new RandomIndexWriter(random(), dir);
+
+ int numDocs = atLeast(1000);
+ double[] values = new double[numDocs];
+ for(int i=0;i<numDocs;i++) {
+ Document doc = new Document();
+ double v = random().nextDouble();
+ values[i] = v;
+ doc.add(new DoubleDocValuesField("field", v));
+ doc.add(new DoubleField("field", v, Field.Store.NO));
+ w.addDocument(doc);
+ }
+ IndexReader r = w.getReader();
+
+ IndexSearcher s = newSearcher(r);
+ FacetsConfig config = new FacetsConfig();
+
+ int numIters = atLeast(10);
+ for(int iter=0;iter<numIters;iter++) {
+ if (VERBOSE) {
+ System.out.println("TEST: iter=" + iter);
+ }
+ int numRange = _TestUtil.nextInt(random(), 1, 5);
+ DoubleRange[] ranges = new DoubleRange[numRange];
+ int[] expectedCounts = new int[numRange];
+ for(int rangeID=0;rangeID<numRange;rangeID++) {
+ double min = random().nextDouble();
+ double max = random().nextDouble();
+ if (min > max) {
+ double x = min;
+ min = max;
+ max = x;
+ }
+ boolean minIncl = random().nextBoolean();
+ boolean maxIncl = random().nextBoolean();
+ ranges[rangeID] = new DoubleRange("r" + rangeID, min, minIncl, max, maxIncl);
+
+ // Do "slow but hopefully correct" computation of
+ // expected count:
+ for(int i=0;i<numDocs;i++) {
+ boolean accept = true;
+ if (minIncl) {
+ accept &= values[i] >= min;
+ } else {
+ accept &= values[i] > min;
+ }
+ if (maxIncl) {
+ accept &= values[i] <= max;
+ } else {
+ accept &= values[i] < max;
+ }
+ if (accept) {
+ expectedCounts[rangeID]++;
+ }
+ }
+ }
+
+ SimpleFacetsCollector sfc = new SimpleFacetsCollector();
+ s.search(new MatchAllDocsQuery(), sfc);
+ Facets facets = new RangeFacetCounts("field", sfc, ranges);
+ SimpleFacetResult result = facets.getTopChildren(10, "field");
+ assertEquals(numRange, result.labelValues.length);
+ for(int rangeID=0;rangeID<numRange;rangeID++) {
+ if (VERBOSE) {
+ System.out.println(" range " + rangeID + " expectedCount=" + expectedCounts[rangeID]);
+ }
+ LabelAndValue subNode = result.labelValues[rangeID];
+ assertEquals("r" + rangeID, subNode.label);
+ assertEquals(expectedCounts[rangeID], subNode.value.intValue());
+
+ DoubleRange range = ranges[rangeID];
+
+ // Test drill-down:
+ SimpleDrillDownQuery ddq = new SimpleDrillDownQuery(config);
+ ddq.add("field", NumericRangeQuery.newDoubleRange("field", range.min, range.max, range.minInclusive, range.maxInclusive));
+ assertEquals(expectedCounts[rangeID], s.search(ddq, 10).totalHits);
+ }
+ }
+
+ IOUtils.close(w, r, dir);
+ }
+
+ // LUCENE-5178
+ public void testMissingValues() throws Exception {
+ assumeTrue("codec does not support docsWithField", defaultCodecSupportsDocsWithField());
+ Directory d = newDirectory();
+ RandomIndexWriter w = new RandomIndexWriter(random(), d);
+ Document doc = new Document();
+ NumericDocValuesField field = new NumericDocValuesField("field", 0L);
+ doc.add(field);
+ for(long l=0;l<100;l++) {
+ if (l % 5 == 0) {
+ // Every 5th doc is missing the value:
+ w.addDocument(new Document());
+ continue;
+ }
+ field.setLongValue(l);
+ w.addDocument(doc);
+ }
+
+ IndexReader r = w.getReader();
+
+ SimpleFacetsCollector sfc = new SimpleFacetsCollector();
+
+ IndexSearcher s = newSearcher(r);
+ s.search(new MatchAllDocsQuery(), sfc);
+ Facets facets = new RangeFacetCounts("field", sfc,
+ new LongRange("less than 10", 0L, true, 10L, false),
+ new LongRange("less than or equal to 10", 0L, true, 10L, true),
+ new LongRange("over 90", 90L, false, 100L, false),
+ new LongRange("90 or above", 90L, true, 100L, false),
+ new LongRange("over 1000", 1000L, false, Long.MAX_VALUE, false));
+
+ assertEquals("field (100)\n less than 10 (8)\n less than or equal to 10 (8)\n over 90 (8)\n 90 or above (8)\n over 1000 (0)\n",
+ facets.getTopChildren(10, "field").toString());
+
+ IOUtils.close(w, r, d);
+ }
}
diff --git a/lucene/facet/src/test/org/apache/lucene/facet/simple/TestSimpleDrillSideways.java b/lucene/facet/src/test/org/apache/lucene/facet/simple/TestSimpleDrillSideways.java
index 9f9b677f9e1..803bf94d81e 100644
--- a/lucene/facet/src/test/org/apache/lucene/facet/simple/TestSimpleDrillSideways.java
+++ b/lucene/facet/src/test/org/apache/lucene/facet/simple/TestSimpleDrillSideways.java
@@ -420,7 +420,6 @@ public class TestSimpleDrillSideways extends FacetTestCase {
bChance /= sum;
cChance /= sum;
- // nocommit
int numDims = _TestUtil.nextInt(random(), 2, 5);
//int numDims = 3;
int numDocs = atLeast(3000);
diff --git a/lucene/facet/src/test/org/apache/lucene/facet/simple/TestTaxonomyFacetCounts.java b/lucene/facet/src/test/org/apache/lucene/facet/simple/TestTaxonomyFacetCounts.java
index 776ae9e66b7..a5fdda623b5 100644
--- a/lucene/facet/src/test/org/apache/lucene/facet/simple/TestTaxonomyFacetCounts.java
+++ b/lucene/facet/src/test/org/apache/lucene/facet/simple/TestTaxonomyFacetCounts.java
@@ -173,7 +173,7 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
SimpleFacetsCollector c = new SimpleFacetsCollector();
searcher.search(new MatchAllDocsQuery(), c);
- Facets facets = getFacetCounts(taxoReader, new FacetsConfig(), c);
+ Facets facets = getTaxonomyFacetCounts(taxoReader, new FacetsConfig(), c);
// Ask for top 10 labels for any dims that have counts:
List<SimpleFacetResult> results = facets.getAllDims(10);
@@ -303,7 +303,7 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
// you'd use a "normal" query, and use MultiCollector to
// wrap collecting the "normal" hits and also facets:
searcher.search(new MatchAllDocsQuery(), c);
- Facets facets = getFacetCounts(taxoReader, config, c);
+ Facets facets = getTaxonomyFacetCounts(taxoReader, config, c);
SimpleFacetResult result = facets.getTopChildren(10, "a");
assertEquals(1, result.labelValues.length);
assertEquals(1, result.labelValues[0].value.intValue());
@@ -336,7 +336,7 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
SimpleFacetsCollector c = new SimpleFacetsCollector();
searcher.search(new MatchAllDocsQuery(), c);
- Facets facets = getFacetCounts(taxoReader, config, c);
+ Facets facets = getTaxonomyFacetCounts(taxoReader, config, c);
assertEquals(1, facets.getSpecificValue("dim", "test\u001Fone"));
assertEquals(1, facets.getSpecificValue("dim", "test\u001Etwo"));
@@ -378,7 +378,7 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
SimpleFacetsCollector c = new SimpleFacetsCollector();
searcher.search(new MatchAllDocsQuery(), c);
- Facets facets = getFacetCounts(taxoReader, config, c);
+ Facets facets = getTaxonomyFacetCounts(taxoReader, config, c);
assertEquals(1, facets.getTopChildren(10, "dim").value);
assertEquals(1, facets.getTopChildren(10, "dim2").value);
assertEquals(1, facets.getTopChildren(10, "dim3").value);
@@ -422,7 +422,7 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
// you'd use a "normal" query, and use MultiCollector to
// wrap collecting the "normal" hits and also facets:
searcher.search(new MatchAllDocsQuery(), c);
- Facets facets = getFacetCounts(taxoReader, config, c);
+ Facets facets = getTaxonomyFacetCounts(taxoReader, config, c);
SimpleFacetResult result = facets.getTopChildren(Integer.MAX_VALUE, "dim");
assertEquals(numLabels, result.labelValues.length);