Skip to content

Apache Lucene open-source search software

LUCENE-5339: move build into FacetsConfig; cutover more tests

Michael McCandless59c08c3fa13b
diff --git a/TODO b/TODO
index 2ecf831fe7c..c767fe0ff47 100644
--- a/TODO
+++ b/TODO
@@ -1,6 +1,7 @@
nocommit this!
TODO
+ - move DocumentBuilder.build -> FacetsConfig.build
- add sugar apis to do sort-by-score, sort-by-field sort AND collect into SimpleFacetsCollector?
- getSpecificValue for a dim isn't reliable
- we could put more stuff into the "schema", e.g. this field is
diff --git a/lucene/facet/src/java/org/apache/lucene/facet/simple/DocumentBuilder.java b/lucene/facet/src/java/org/apache/lucene/facet/simple/DocumentBuilder.java
deleted file mode 100644
index 6e94a6d892d..00000000000
--- a/lucene/facet/src/java/org/apache/lucene/facet/simple/DocumentBuilder.java
+++ /dev/null
@@ -1,417 +0,0 @@
-package org.apache.lucene.facet.simple;
-
-/*
- * 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.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.apache.lucene.document.BinaryDocValuesField;
-import org.apache.lucene.document.Field;
-import org.apache.lucene.document.SortedSetDocValuesField;
-import org.apache.lucene.document.StringField;
-import org.apache.lucene.facet.taxonomy.FacetLabel;
-import org.apache.lucene.facet.taxonomy.TaxonomyWriter;
-import org.apache.lucene.index.IndexDocument;
-import org.apache.lucene.index.IndexableField;
-import org.apache.lucene.index.IndexableFieldType;
-import org.apache.lucene.index.StorableField;
-import org.apache.lucene.util.ArrayUtil;
-import org.apache.lucene.util.BytesRef;
-import org.apache.lucene.util.IntsRef;
-
-/** Pass the {@link #Document} to index to {@link #build},
- * to translate any added {@link FacetField}s into
- * indexable and storable fields. It's safe to share a
- * single instance of this across multiple threads. */
-
-public class DocumentBuilder {
- private final TaxonomyWriter taxoWriter;
- private final FacetsConfig config;
-
- // Used only for best-effort detection of app mixing
- // int/float/bytes in a single indexed field:
- private final Map<String,String> assocDimTypes = new ConcurrentHashMap<String,String>();
-
- public DocumentBuilder(TaxonomyWriter taxoWriter, FacetsConfig config) {
- this.taxoWriter = taxoWriter;
- this.config = config;
- }
-
- private static void checkSeen(Set<String> seenDims, String dim) {
- if (seenDims.contains(dim)) {
- throw new IllegalArgumentException("dimension \"" + dim + "\" is not multiValued, but it appears more than once in this document");
- }
- seenDims.add(dim);
- }
-
- public IndexDocument build(IndexDocument doc) throws IOException {
- // Find all FacetFields, collated by the actual field:
- Map<String,List<FacetField>> byField = new HashMap<String,List<FacetField>>();
-
- // ... and also all SortedSetDocValuesFacetFields:
- Map<String,List<SortedSetDocValuesFacetField>> dvByField = new HashMap<String,List<SortedSetDocValuesFacetField>>();
-
- // ... and also all AssociationFacetFields
- Map<String,List<AssociationFacetField>> assocByField = new HashMap<String,List<AssociationFacetField>>();
-
- Set<String> seenDims = new HashSet<String>();
-
- for(IndexableField field : doc.indexableFields()) {
- if (field.fieldType() == FacetField.TYPE) {
- FacetField facetField = (FacetField) field;
- FacetsConfig.DimConfig dimConfig = config.getDimConfig(facetField.dim);
- if (dimConfig.multiValued == false) {
- checkSeen(seenDims, facetField.dim);
- }
- String indexFieldName = dimConfig.indexFieldName;
- List<FacetField> fields = byField.get(indexFieldName);
- if (fields == null) {
- fields = new ArrayList<FacetField>();
- byField.put(indexFieldName, fields);
- }
- fields.add(facetField);
- }
-
- if (field.fieldType() == SortedSetDocValuesFacetField.TYPE) {
- SortedSetDocValuesFacetField facetField = (SortedSetDocValuesFacetField) field;
- FacetsConfig.DimConfig dimConfig = config.getDimConfig(facetField.dim);
- if (dimConfig.multiValued == false) {
- checkSeen(seenDims, facetField.dim);
- }
- String indexFieldName = dimConfig.indexFieldName;
- List<SortedSetDocValuesFacetField> fields = dvByField.get(indexFieldName);
- if (fields == null) {
- fields = new ArrayList<SortedSetDocValuesFacetField>();
- dvByField.put(indexFieldName, fields);
- }
- fields.add(facetField);
- }
-
- if (field.fieldType() == AssociationFacetField.TYPE) {
- AssociationFacetField facetField = (AssociationFacetField) field;
- FacetsConfig.DimConfig dimConfig = config.getDimConfig(facetField.dim);
- if (dimConfig.multiValued == false) {
- checkSeen(seenDims, facetField.dim);
- }
- if (dimConfig.hierarchical) {
- throw new IllegalArgumentException("AssociationFacetField cannot be hierarchical (dim=\"" + facetField.dim + "\")");
- }
- if (dimConfig.requireDimCount) {
- throw new IllegalArgumentException("AssociationFacetField cannot requireDimCount (dim=\"" + facetField.dim + "\")");
- }
-
- String indexFieldName = dimConfig.indexFieldName;
- List<AssociationFacetField> fields = assocByField.get(indexFieldName);
- if (fields == null) {
- fields = new ArrayList<AssociationFacetField>();
- assocByField.put(indexFieldName, fields);
- }
- fields.add(facetField);
-
- // Best effort: detect mis-matched types in same
- // indexed field:
- String type;
- if (facetField instanceof IntAssociationFacetField) {
- type = "int";
- } else if (facetField instanceof FloatAssociationFacetField) {
- type = "float";
- } else {
- type = "bytes";
- }
- // NOTE: not thread safe, but this is just best effort:
- String curType = assocDimTypes.get(indexFieldName);
- if (curType == null) {
- assocDimTypes.put(indexFieldName, type);
- } else if (!curType.equals(type)) {
- throw new IllegalArgumentException("mixing incompatible types of AssocationFacetField (" + curType + " and " + type + ") in indexed field \"" + indexFieldName + "\"; use FacetsConfig to change the indexFieldName for each dimension");
- }
- }
- }
-
- List<Field> addedIndexedFields = new ArrayList<Field>();
- List<Field> addedStoredFields = new ArrayList<Field>();
-
- processFacetFields(byField, addedIndexedFields, addedStoredFields);
- processSSDVFacetFields(dvByField, addedIndexedFields, addedStoredFields);
- processAssocFacetFields(assocByField, addedIndexedFields, addedStoredFields);
-
- //System.out.println("add stored: " + addedStoredFields);
-
- final List<IndexableField> allIndexedFields = new ArrayList<IndexableField>();
- for(IndexableField field : doc.indexableFields()) {
- IndexableFieldType ft = field.fieldType();
- if (ft != FacetField.TYPE && ft != SortedSetDocValuesFacetField.TYPE && ft != AssociationFacetField.TYPE) {
- allIndexedFields.add(field);
- }
- }
- allIndexedFields.addAll(addedIndexedFields);
-
- final List<StorableField> allStoredFields = new ArrayList<StorableField>();
- for(StorableField field : doc.storableFields()) {
- allStoredFields.add(field);
- }
- allStoredFields.addAll(addedStoredFields);
-
- //System.out.println("all indexed: " + allIndexedFields);
- //System.out.println("all stored: " + allStoredFields);
-
- return new IndexDocument() {
- @Override
- public Iterable<IndexableField> indexableFields() {
- return allIndexedFields;
- }
-
- @Override
- public Iterable<StorableField> storableFields() {
- return allStoredFields;
- }
- };
- }
-
- private void processFacetFields(Map<String,List<FacetField>> byField, List<Field> addedIndexedFields, List<Field> addedStoredFields) throws IOException {
-
- for(Map.Entry<String,List<FacetField>> ent : byField.entrySet()) {
-
- String indexFieldName = ent.getKey();
- //System.out.println(" fields=" + ent.getValue());
-
- IntsRef ordinals = new IntsRef(32);
- for(FacetField facetField : ent.getValue()) {
-
- FacetsConfig.DimConfig ft = config.getDimConfig(facetField.dim);
- if (facetField.path.length > 1 && ft.hierarchical == false) {
- throw new IllegalArgumentException("dimension \"" + facetField.dim + "\" is not hierarchical yet has " + facetField.path.length + " components");
- }
-
- FacetLabel cp = FacetLabel.create(facetField.dim, facetField.path);
-
- int ordinal = taxoWriter.addCategory(cp);
- if (ordinals.length == ordinals.ints.length) {
- ordinals.grow(ordinals.length+1);
- }
- ordinals.ints[ordinals.length++] = ordinal;
- //System.out.println(" add cp=" + cp);
-
- if (ft.multiValued && (ft.hierarchical || ft.requireDimCount)) {
- // Add all parents too:
- int parent = taxoWriter.getParent(ordinal);
- while (parent > 0) {
- if (ordinals.ints.length == ordinals.length) {
- ordinals.grow(ordinals.length+1);
- }
- ordinals.ints[ordinals.length++] = parent;
- parent = taxoWriter.getParent(parent);
- }
-
- if (ft.requireDimCount == false) {
- // Remove last (dimension) ord:
- ordinals.length--;
- }
- }
-
- // Drill down:
- for(int i=2;i<=cp.length;i++) {
- addedIndexedFields.add(new StringField(indexFieldName, pathToString(cp.components, i), Field.Store.NO));
- }
- }
-
- // Facet counts:
- // DocValues are considered stored fields:
- addedStoredFields.add(new BinaryDocValuesField(indexFieldName, dedupAndEncode(ordinals)));
- }
- }
-
- private void processSSDVFacetFields(Map<String,List<SortedSetDocValuesFacetField>> byField, List<Field> addedIndexedFields, List<Field> addedStoredFields) throws IOException {
- //System.out.println("process SSDV: " + byField);
- for(Map.Entry<String,List<SortedSetDocValuesFacetField>> ent : byField.entrySet()) {
-
- String indexFieldName = ent.getKey();
- //System.out.println(" field=" + indexFieldName);
-
- for(SortedSetDocValuesFacetField facetField : ent.getValue()) {
- FacetLabel cp = new FacetLabel(facetField.dim, facetField.label);
- String fullPath = pathToString(cp.components, cp.length);
- //System.out.println("add " + fullPath);
-
- // For facet counts:
- addedStoredFields.add(new SortedSetDocValuesField(indexFieldName, new BytesRef(fullPath)));
-
- // For drill-down:
- addedIndexedFields.add(new StringField(indexFieldName, fullPath, Field.Store.NO));
- }
- }
- }
-
- private void processAssocFacetFields(Map<String,List<AssociationFacetField>> byField, List<Field> addedIndexedFields, List<Field> addedStoredFields) throws IOException {
- for(Map.Entry<String,List<AssociationFacetField>> ent : byField.entrySet()) {
- byte[] bytes = new byte[16];
- int upto = 0;
- String indexFieldName = ent.getKey();
- for(AssociationFacetField field : ent.getValue()) {
- // NOTE: we don't add parents for associations
- // nocommit is that right? maybe we are supposed to
- // add to taxo writer, and just not index the parent
- // ords?
- int ordinal = taxoWriter.addCategory(FacetLabel.create(field.dim, field.path));
- if (upto + 4 > bytes.length) {
- bytes = ArrayUtil.grow(bytes, upto+4);
- }
- // big-endian:
- bytes[upto++] = (byte) (ordinal >> 24);
- bytes[upto++] = (byte) (ordinal >> 16);
- bytes[upto++] = (byte) (ordinal >> 8);
- bytes[upto++] = (byte) ordinal;
- if (upto + field.assoc.length > bytes.length) {
- bytes = ArrayUtil.grow(bytes, upto+field.assoc.length);
- }
- System.arraycopy(field.assoc.bytes, field.assoc.offset, bytes, upto, field.assoc.length);
- upto += field.assoc.length;
- }
- addedStoredFields.add(new BinaryDocValuesField(indexFieldName, new BytesRef(bytes, 0, upto)));
- }
- }
-
- /** Encodes ordinals into a BytesRef; expert: subclass can
- * override this to change encoding. */
- protected BytesRef dedupAndEncode(IntsRef ordinals) {
- Arrays.sort(ordinals.ints, ordinals.offset, ordinals.length);
- byte[] bytes = new byte[5*ordinals.length];
- int lastOrd = -1;
- int upto = 0;
- for(int i=0;i<ordinals.length;i++) {
- int ord = ordinals.ints[ordinals.offset+i];
- // ord could be == lastOrd, so we must dedup:
- if (ord > lastOrd) {
- int delta;
- if (lastOrd == -1) {
- delta = ord;
- } else {
- delta = ord - lastOrd;
- }
- if ((delta & ~0x7F) == 0) {
- bytes[upto] = (byte) delta;
- upto++;
- } else if ((delta & ~0x3FFF) == 0) {
- bytes[upto] = (byte) (0x80 | ((delta & 0x3F80) >> 7));
- bytes[upto + 1] = (byte) (delta & 0x7F);
- upto += 2;
- } else if ((delta & ~0x1FFFFF) == 0) {
- bytes[upto] = (byte) (0x80 | ((delta & 0x1FC000) >> 14));
- bytes[upto + 1] = (byte) (0x80 | ((delta & 0x3F80) >> 7));
- bytes[upto + 2] = (byte) (delta & 0x7F);
- upto += 3;
- } else if ((delta & ~0xFFFFFFF) == 0) {
- bytes[upto] = (byte) (0x80 | ((delta & 0xFE00000) >> 21));
- bytes[upto + 1] = (byte) (0x80 | ((delta & 0x1FC000) >> 14));
- bytes[upto + 2] = (byte) (0x80 | ((delta & 0x3F80) >> 7));
- bytes[upto + 3] = (byte) (delta & 0x7F);
- upto += 4;
- } else {
- bytes[upto] = (byte) (0x80 | ((delta & 0xF0000000) >> 28));
- bytes[upto + 1] = (byte) (0x80 | ((delta & 0xFE00000) >> 21));
- bytes[upto + 2] = (byte) (0x80 | ((delta & 0x1FC000) >> 14));
- bytes[upto + 3] = (byte) (0x80 | ((delta & 0x3F80) >> 7));
- bytes[upto + 4] = (byte) (delta & 0x7F);
- upto += 5;
- }
- lastOrd = ord;
- }
- }
- return new BytesRef(bytes, 0, upto);
- }
-
- // nocommit move all of this to Util?
-
- // Joins the path components together:
- private static final char DELIM_CHAR = '\u001F';
-
- // Escapes any occurrence of the path component inside the label:
- private static final char ESCAPE_CHAR = '\u001E';
-
- /** Turns a path into a string without stealing any
- * characters. */
- public static String pathToString(String dim, String[] path) {
- String[] fullPath = new String[1+path.length];
- fullPath[0] = dim;
- System.arraycopy(path, 0, fullPath, 1, path.length);
- return pathToString(fullPath, fullPath.length);
- }
-
- public static String pathToString(String[] path) {
- return pathToString(path, path.length);
- }
-
- public static String pathToString(String[] path, int length) {
- if (length == 0) {
- return "";
- }
- StringBuilder sb = new StringBuilder();
- for(int i=0;i<length;i++) {
- String s = path[i];
- int numChars = s.length();
- for(int j=0;j<numChars;j++) {
- char ch = s.charAt(j);
- if (ch == DELIM_CHAR || ch == ESCAPE_CHAR) {
- sb.append(ESCAPE_CHAR);
- }
- sb.append(ch);
- }
- sb.append(DELIM_CHAR);
- }
-
- // Trim off last DELIM_CHAR:
- sb.setLength(sb.length()-1);
- return sb.toString();
- }
-
- /** Turns a result from previous call to {@link
- * #pathToString} back into the original {@code String[]}
- * without stealing any characters. */
- public static String[] stringToPath(String s) {
- List<String> parts = new ArrayList<String>();
- int length = s.length();
- char[] buffer = new char[length];
-
- int upto = 0;
- boolean lastEscape = false;
- for(int i=0;i<length;i++) {
- char ch = s.charAt(i);
- if (lastEscape) {
- buffer[upto++] = ch;
- lastEscape = false;
- } else if (ch == ESCAPE_CHAR) {
- lastEscape = true;
- } else if (ch == DELIM_CHAR) {
- parts.add(new String(buffer, 0, upto));
- upto = 0;
- } else {
- buffer[upto++] = ch;
- }
- }
- parts.add(new String(buffer, 0, upto));
- assert !lastEscape;
- return parts.toArray(new String[parts.size()]);
- }
-}
diff --git a/lucene/facet/src/java/org/apache/lucene/facet/simple/FacetsConfig.java b/lucene/facet/src/java/org/apache/lucene/facet/simple/FacetsConfig.java
index 744cd1ad90e..2d82ac9492b 100644
--- a/lucene/facet/src/java/org/apache/lucene/facet/simple/FacetsConfig.java
+++ b/lucene/facet/src/java/org/apache/lucene/facet/simple/FacetsConfig.java
@@ -17,9 +17,30 @@ package org.apache.lucene.facet.simple;
* limitations under the License.
*/
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
+import org.apache.lucene.document.BinaryDocValuesField;
+import org.apache.lucene.document.Field;
+import org.apache.lucene.document.SortedSetDocValuesField;
+import org.apache.lucene.document.StringField;
+import org.apache.lucene.facet.taxonomy.FacetLabel;
+import org.apache.lucene.facet.taxonomy.TaxonomyWriter;
+import org.apache.lucene.index.IndexDocument;
+import org.apache.lucene.index.IndexableField;
+import org.apache.lucene.index.IndexableFieldType;
+import org.apache.lucene.index.StorableField;
+import org.apache.lucene.util.ArrayUtil;
+import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.IntsRef;
+
/** By default a dimension is flat, single valued and does
* not require count for the dimension; use
* the setters in this class to change these settings for
@@ -37,6 +58,12 @@ public class FacetsConfig {
private final Map<String,DimConfig> fieldTypes = new ConcurrentHashMap<String,DimConfig>();
+ // Used only for best-effort detection of app mixing
+ // int/float/bytes in a single indexed field:
+ private final Map<String,String> assocDimTypes = new ConcurrentHashMap<String,String>();
+
+ private final TaxonomyWriter taxoWriter;
+
/** @lucene.internal */
// nocommit expose this to the user, vs the setters?
public static final class DimConfig {
@@ -55,6 +82,14 @@ public class FacetsConfig {
String indexFieldName = DEFAULT_INDEX_FIELD_NAME;
}
+ public FacetsConfig() {
+ this(null);
+ }
+
+ public FacetsConfig(TaxonomyWriter taxoWriter) {
+ this.taxoWriter = taxoWriter;
+ }
+
public final static DimConfig DEFAULT_DIM_CONFIG = new DimConfig();
public DimConfig getDimConfig(String dimName) {
@@ -105,4 +140,369 @@ public class FacetsConfig {
Map<String,DimConfig> getDimConfigs() {
return fieldTypes;
}
+
+ private static void checkSeen(Set<String> seenDims, String dim) {
+ if (seenDims.contains(dim)) {
+ throw new IllegalArgumentException("dimension \"" + dim + "\" is not multiValued, but it appears more than once in this document");
+ }
+ seenDims.add(dim);
+ }
+
+ /** Translates any added {@link FacetField}s into normal
+ * fields for indexing */
+ public IndexDocument build(IndexDocument doc) throws IOException {
+ // Find all FacetFields, collated by the actual field:
+ Map<String,List<FacetField>> byField = new HashMap<String,List<FacetField>>();
+
+ // ... and also all SortedSetDocValuesFacetFields:
+ Map<String,List<SortedSetDocValuesFacetField>> dvByField = new HashMap<String,List<SortedSetDocValuesFacetField>>();
+
+ // ... and also all AssociationFacetFields
+ Map<String,List<AssociationFacetField>> assocByField = new HashMap<String,List<AssociationFacetField>>();
+
+ Set<String> seenDims = new HashSet<String>();
+
+ for(IndexableField field : doc.indexableFields()) {
+ if (field.fieldType() == FacetField.TYPE) {
+ FacetField facetField = (FacetField) field;
+ FacetsConfig.DimConfig dimConfig = getDimConfig(facetField.dim);
+ if (dimConfig.multiValued == false) {
+ checkSeen(seenDims, facetField.dim);
+ }
+ String indexFieldName = dimConfig.indexFieldName;
+ List<FacetField> fields = byField.get(indexFieldName);
+ if (fields == null) {
+ fields = new ArrayList<FacetField>();
+ byField.put(indexFieldName, fields);
+ }
+ fields.add(facetField);
+ }
+
+ if (field.fieldType() == SortedSetDocValuesFacetField.TYPE) {
+ SortedSetDocValuesFacetField facetField = (SortedSetDocValuesFacetField) field;
+ FacetsConfig.DimConfig dimConfig = getDimConfig(facetField.dim);
+ if (dimConfig.multiValued == false) {
+ checkSeen(seenDims, facetField.dim);
+ }
+ String indexFieldName = dimConfig.indexFieldName;
+ List<SortedSetDocValuesFacetField> fields = dvByField.get(indexFieldName);
+ if (fields == null) {
+ fields = new ArrayList<SortedSetDocValuesFacetField>();
+ dvByField.put(indexFieldName, fields);
+ }
+ fields.add(facetField);
+ }
+
+ if (field.fieldType() == AssociationFacetField.TYPE) {
+ AssociationFacetField facetField = (AssociationFacetField) field;
+ FacetsConfig.DimConfig dimConfig = getDimConfig(facetField.dim);
+ if (dimConfig.multiValued == false) {
+ checkSeen(seenDims, facetField.dim);
+ }
+ if (dimConfig.hierarchical) {
+ throw new IllegalArgumentException("AssociationFacetField cannot be hierarchical (dim=\"" + facetField.dim + "\")");
+ }
+ if (dimConfig.requireDimCount) {
+ throw new IllegalArgumentException("AssociationFacetField cannot requireDimCount (dim=\"" + facetField.dim + "\")");
+ }
+
+ String indexFieldName = dimConfig.indexFieldName;
+ List<AssociationFacetField> fields = assocByField.get(indexFieldName);
+ if (fields == null) {
+ fields = new ArrayList<AssociationFacetField>();
+ assocByField.put(indexFieldName, fields);
+ }
+ fields.add(facetField);
+
+ // Best effort: detect mis-matched types in same
+ // indexed field:
+ String type;
+ if (facetField instanceof IntAssociationFacetField) {
+ type = "int";
+ } else if (facetField instanceof FloatAssociationFacetField) {
+ type = "float";
+ } else {
+ type = "bytes";
+ }
+ // NOTE: not thread safe, but this is just best effort:
+ String curType = assocDimTypes.get(indexFieldName);
+ if (curType == null) {
+ assocDimTypes.put(indexFieldName, type);
+ } else if (!curType.equals(type)) {
+ throw new IllegalArgumentException("mixing incompatible types of AssocationFacetField (" + curType + " and " + type + ") in indexed field \"" + indexFieldName + "\"; use FacetsConfig to change the indexFieldName for each dimension");
+ }
+ }
+ }
+
+ List<Field> addedIndexedFields = new ArrayList<Field>();
+ List<Field> addedStoredFields = new ArrayList<Field>();
+
+ processFacetFields(byField, addedIndexedFields, addedStoredFields);
+ processSSDVFacetFields(dvByField, addedIndexedFields, addedStoredFields);
+ processAssocFacetFields(assocByField, addedIndexedFields, addedStoredFields);
+
+ //System.out.println("add stored: " + addedStoredFields);
+
+ final List<IndexableField> allIndexedFields = new ArrayList<IndexableField>();
+ for(IndexableField field : doc.indexableFields()) {
+ IndexableFieldType ft = field.fieldType();
+ if (ft != FacetField.TYPE && ft != SortedSetDocValuesFacetField.TYPE && ft != AssociationFacetField.TYPE) {
+ allIndexedFields.add(field);
+ }
+ }
+ allIndexedFields.addAll(addedIndexedFields);
+
+ final List<StorableField> allStoredFields = new ArrayList<StorableField>();
+ for(StorableField field : doc.storableFields()) {
+ allStoredFields.add(field);
+ }
+ allStoredFields.addAll(addedStoredFields);
+
+ //System.out.println("all indexed: " + allIndexedFields);
+ //System.out.println("all stored: " + allStoredFields);
+
+ return new IndexDocument() {
+ @Override
+ public Iterable<IndexableField> indexableFields() {
+ return allIndexedFields;
+ }
+
+ @Override
+ public Iterable<StorableField> storableFields() {
+ return allStoredFields;
+ }
+ };
+ }
+
+ private void processFacetFields(Map<String,List<FacetField>> byField, List<Field> addedIndexedFields, List<Field> addedStoredFields) throws IOException {
+
+ for(Map.Entry<String,List<FacetField>> ent : byField.entrySet()) {
+
+ String indexFieldName = ent.getKey();
+ //System.out.println(" fields=" + ent.getValue());
+
+ IntsRef ordinals = new IntsRef(32);
+ for(FacetField facetField : ent.getValue()) {
+
+ FacetsConfig.DimConfig ft = getDimConfig(facetField.dim);
+ if (facetField.path.length > 1 && ft.hierarchical == false) {
+ throw new IllegalArgumentException("dimension \"" + facetField.dim + "\" is not hierarchical yet has " + facetField.path.length + " components");
+ }
+
+ FacetLabel cp = FacetLabel.create(facetField.dim, facetField.path);
+
+ checkTaxoWriter();
+ int ordinal = taxoWriter.addCategory(cp);
+ if (ordinals.length == ordinals.ints.length) {
+ ordinals.grow(ordinals.length+1);
+ }
+ ordinals.ints[ordinals.length++] = ordinal;
+ //System.out.println(" add cp=" + cp);
+
+ if (ft.multiValued && (ft.hierarchical || ft.requireDimCount)) {
+ // Add all parents too:
+ int parent = taxoWriter.getParent(ordinal);
+ while (parent > 0) {
+ if (ordinals.ints.length == ordinals.length) {
+ ordinals.grow(ordinals.length+1);
+ }
+ ordinals.ints[ordinals.length++] = parent;
+ parent = taxoWriter.getParent(parent);
+ }
+
+ if (ft.requireDimCount == false) {
+ // Remove last (dimension) ord:
+ ordinals.length--;
+ }
+ }
+
+ // Drill down:
+ for(int i=2;i<=cp.length;i++) {
+ addedIndexedFields.add(new StringField(indexFieldName, pathToString(cp.components, i), Field.Store.NO));
+ }
+ }
+
+ // Facet counts:
+ // DocValues are considered stored fields:
+ addedStoredFields.add(new BinaryDocValuesField(indexFieldName, dedupAndEncode(ordinals)));
+ }
+ }
+
+ private void processSSDVFacetFields(Map<String,List<SortedSetDocValuesFacetField>> byField, List<Field> addedIndexedFields, List<Field> addedStoredFields) throws IOException {
+ //System.out.println("process SSDV: " + byField);
+ for(Map.Entry<String,List<SortedSetDocValuesFacetField>> ent : byField.entrySet()) {
+
+ String indexFieldName = ent.getKey();
+ //System.out.println(" field=" + indexFieldName);
+
+ for(SortedSetDocValuesFacetField facetField : ent.getValue()) {
+ FacetLabel cp = new FacetLabel(facetField.dim, facetField.label);
+ String fullPath = pathToString(cp.components, cp.length);
+ //System.out.println("add " + fullPath);
+
+ // For facet counts:
+ addedStoredFields.add(new SortedSetDocValuesField(indexFieldName, new BytesRef(fullPath)));
+
+ // For drill-down:
+ addedIndexedFields.add(new StringField(indexFieldName, fullPath, Field.Store.NO));
+ }
+ }
+ }
+
+ private void processAssocFacetFields(Map<String,List<AssociationFacetField>> byField,
+ List<Field> addedIndexedFields, List<Field> addedStoredFields) throws IOException {
+ for(Map.Entry<String,List<AssociationFacetField>> ent : byField.entrySet()) {
+ byte[] bytes = new byte[16];
+ int upto = 0;
+ String indexFieldName = ent.getKey();
+ for(AssociationFacetField field : ent.getValue()) {
+ // NOTE: we don't add parents for associations
+ // nocommit is that right? maybe we are supposed to
+ // add to taxo writer, and just not index the parent
+ // ords?
+ checkTaxoWriter();
+ int ordinal = taxoWriter.addCategory(FacetLabel.create(field.dim, field.path));
+ if (upto + 4 > bytes.length) {
+ bytes = ArrayUtil.grow(bytes, upto+4);
+ }
+ // big-endian:
+ bytes[upto++] = (byte) (ordinal >> 24);
+ bytes[upto++] = (byte) (ordinal >> 16);
+ bytes[upto++] = (byte) (ordinal >> 8);
+ bytes[upto++] = (byte) ordinal;
+ if (upto + field.assoc.length > bytes.length) {
+ bytes = ArrayUtil.grow(bytes, upto+field.assoc.length);
+ }
+ System.arraycopy(field.assoc.bytes, field.assoc.offset, bytes, upto, field.assoc.length);
+ upto += field.assoc.length;
+ }
+ addedStoredFields.add(new BinaryDocValuesField(indexFieldName, new BytesRef(bytes, 0, upto)));
+ }
+ }
+
+ /** Encodes ordinals into a BytesRef; expert: subclass can
+ * override this to change encoding. */
+ protected BytesRef dedupAndEncode(IntsRef ordinals) {
+ Arrays.sort(ordinals.ints, ordinals.offset, ordinals.length);
+ byte[] bytes = new byte[5*ordinals.length];
+ int lastOrd = -1;
+ int upto = 0;
+ for(int i=0;i<ordinals.length;i++) {
+ int ord = ordinals.ints[ordinals.offset+i];
+ // ord could be == lastOrd, so we must dedup:
+ if (ord > lastOrd) {
+ int delta;
+ if (lastOrd == -1) {
+ delta = ord;
+ } else {
+ delta = ord - lastOrd;
+ }
+ if ((delta & ~0x7F) == 0) {
+ bytes[upto] = (byte) delta;
+ upto++;
+ } else if ((delta & ~0x3FFF) == 0) {
+ bytes[upto] = (byte) (0x80 | ((delta & 0x3F80) >> 7));
+ bytes[upto + 1] = (byte) (delta & 0x7F);
+ upto += 2;
+ } else if ((delta & ~0x1FFFFF) == 0) {
+ bytes[upto] = (byte) (0x80 | ((delta & 0x1FC000) >> 14));
+ bytes[upto + 1] = (byte) (0x80 | ((delta & 0x3F80) >> 7));
+ bytes[upto + 2] = (byte) (delta & 0x7F);
+ upto += 3;
+ } else if ((delta & ~0xFFFFFFF) == 0) {
+ bytes[upto] = (byte) (0x80 | ((delta & 0xFE00000) >> 21));
+ bytes[upto + 1] = (byte) (0x80 | ((delta & 0x1FC000) >> 14));
+ bytes[upto + 2] = (byte) (0x80 | ((delta & 0x3F80) >> 7));
+ bytes[upto + 3] = (byte) (delta & 0x7F);
+ upto += 4;
+ } else {
+ bytes[upto] = (byte) (0x80 | ((delta & 0xF0000000) >> 28));
+ bytes[upto + 1] = (byte) (0x80 | ((delta & 0xFE00000) >> 21));
+ bytes[upto + 2] = (byte) (0x80 | ((delta & 0x1FC000) >> 14));
+ bytes[upto + 3] = (byte) (0x80 | ((delta & 0x3F80) >> 7));
+ bytes[upto + 4] = (byte) (delta & 0x7F);
+ upto += 5;
+ }
+ lastOrd = ord;
+ }
+ }
+ return new BytesRef(bytes, 0, upto);
+ }
+
+ private void checkTaxoWriter() {
+ if (taxoWriter == null) {
+ throw new IllegalStateException("a valid TaxonomyWriter must be provided to the constructor (got null), when using FacetField or AssociationFacetField");
+ }
+ }
+
+ // Joins the path components together:
+ private static final char DELIM_CHAR = '\u001F';
+
+ // Escapes any occurrence of the path component inside the label:
+ private static final char ESCAPE_CHAR = '\u001E';
+
+ /** Turns a path into a string without stealing any
+ * characters. */
+ public static String pathToString(String dim, String[] path) {
+ String[] fullPath = new String[1+path.length];
+ fullPath[0] = dim;
+ System.arraycopy(path, 0, fullPath, 1, path.length);
+ return pathToString(fullPath, fullPath.length);
+ }
+
+ public static String pathToString(String[] path) {
+ return pathToString(path, path.length);
+ }
+
+ public static String pathToString(String[] path, int length) {
+ if (length == 0) {
+ return "";
+ }
+ StringBuilder sb = new StringBuilder();
+ for(int i=0;i<length;i++) {
+ String s = path[i];
+ int numChars = s.length();
+ for(int j=0;j<numChars;j++) {
+ char ch = s.charAt(j);
+ if (ch == DELIM_CHAR || ch == ESCAPE_CHAR) {
+ sb.append(ESCAPE_CHAR);
+ }
+ sb.append(ch);
+ }
+ sb.append(DELIM_CHAR);
+ }
+
+ // Trim off last DELIM_CHAR:
+ sb.setLength(sb.length()-1);
+ return sb.toString();
+ }
+
+ /** Turns a result from previous call to {@link
+ * #pathToString} back into the original {@code String[]}
+ * without stealing any characters. */
+ public static String[] stringToPath(String s) {
+ List<String> parts = new ArrayList<String>();
+ int length = s.length();
+ char[] buffer = new char[length];
+
+ int upto = 0;
+ boolean lastEscape = false;
+ for(int i=0;i<length;i++) {
+ char ch = s.charAt(i);
+ if (lastEscape) {
+ buffer[upto++] = ch;
+ lastEscape = false;
+ } else if (ch == ESCAPE_CHAR) {
+ lastEscape = true;
+ } else if (ch == DELIM_CHAR) {
+ parts.add(new String(buffer, 0, upto));
+ upto = 0;
+ } else {
+ buffer[upto++] = ch;
+ }
+ }
+ parts.add(new String(buffer, 0, upto));
+ assert !lastEscape;
+ return parts.toArray(new String[parts.size()]);
+ }
}
diff --git a/lucene/facet/src/java/org/apache/lucene/facet/simple/FastTaxonomyFacetCounts.java b/lucene/facet/src/java/org/apache/lucene/facet/simple/FastTaxonomyFacetCounts.java
index 65c11c2e90b..42697e679fb 100644
--- a/lucene/facet/src/java/org/apache/lucene/facet/simple/FastTaxonomyFacetCounts.java
+++ b/lucene/facet/src/java/org/apache/lucene/facet/simple/FastTaxonomyFacetCounts.java
@@ -138,12 +138,14 @@ public class FastTaxonomyFacetCounts extends TaxonomyFacets {
int ord = children[dimOrd];
int totCount = 0;
+ int childCount = 0;
TopOrdAndIntQueue.OrdAndValue reuse = null;
while(ord != TaxonomyReader.INVALID_ORDINAL) {
//System.out.println(" check ord=" + ord + " label=" + taxoReader.getPath(ord) + " topN=" + topN);
if (counts[ord] > 0) {
totCount += counts[ord];
+ childCount++;
if (counts[ord] > bottomCount) {
if (reuse == null) {
reuse = new TopOrdAndIntQueue.OrdAndValue();
@@ -183,6 +185,6 @@ public class FastTaxonomyFacetCounts extends TaxonomyFacets {
labelValues[i] = new LabelAndValue(child.components[cp.length], ordAndValue.value);
}
- return new SimpleFacetResult(cp, totCount, labelValues);
+ return new SimpleFacetResult(cp, totCount, labelValues, childCount);
}
}
diff --git a/lucene/facet/src/java/org/apache/lucene/facet/simple/LabelAndValue.java b/lucene/facet/src/java/org/apache/lucene/facet/simple/LabelAndValue.java
index a7fc790441b..9bce0d4ee58 100644
--- a/lucene/facet/src/java/org/apache/lucene/facet/simple/LabelAndValue.java
+++ b/lucene/facet/src/java/org/apache/lucene/facet/simple/LabelAndValue.java
@@ -33,4 +33,15 @@ public final class LabelAndValue {
public String toString() {
return label + " (" + value + ")";
}
+
+ @Override
+ public boolean equals(Object _other) {
+ if ((_other instanceof LabelAndValue) == false) {
+ return false;
+ }
+ LabelAndValue other = (LabelAndValue) _other;
+ return label.equals(other.label) && value.equals(other.value);
+ }
+
+ // nocommit hashCode
}
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 cc049012971..b1e649293c1 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
@@ -95,7 +95,7 @@ public class RangeFacetCounts extends Facets {
labelValues[i] = new LabelAndValue(ranges[i].label, counts[i]);
}
- return new SimpleFacetResult(new FacetLabel(field), totCount, labelValues);
+ return new SimpleFacetResult(new FacetLabel(field), totCount, labelValues, labelValues.length);
}
@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 89035cbd36b..75ac545dfef 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
@@ -53,7 +53,7 @@ import org.apache.lucene.search.TermQuery;
public final class SimpleDrillDownQuery extends Query {
private static Term term(String field, String dim, String[] path) {
- return new Term(field, DocumentBuilder.pathToString(dim, path));
+ return new Term(field, FacetsConfig.pathToString(dim, path));
}
private final FacetsConfig config;
diff --git a/lucene/facet/src/java/org/apache/lucene/facet/simple/SimpleFacetResult.java b/lucene/facet/src/java/org/apache/lucene/facet/simple/SimpleFacetResult.java
index 4be86b74b70..cbbba15ff80 100644
--- a/lucene/facet/src/java/org/apache/lucene/facet/simple/SimpleFacetResult.java
+++ b/lucene/facet/src/java/org/apache/lucene/facet/simple/SimpleFacetResult.java
@@ -17,7 +17,9 @@ package org.apache.lucene.facet.simple;
* limitations under the License.
*/
+import java.util.Arrays;
import java.util.List;
+
import org.apache.lucene.facet.taxonomy.FacetLabel;
public final class SimpleFacetResult {
@@ -27,17 +29,20 @@ public final class SimpleFacetResult {
/** Total value for this path (sum of all child counts, or
* sum of all child values), even those not included in
* the topN. */
- public Number value;
+ public final Number value;
+
+ /** How many labels were populated under the requested
+ * path. */
+ public final int childCount;
/** Child counts. */
public final LabelAndValue[] labelValues;
- // nocommit also return number of children?
-
- public SimpleFacetResult(FacetLabel path, Number value, LabelAndValue[] labelValues) {
+ public SimpleFacetResult(FacetLabel path, Number value, LabelAndValue[] labelValues, int childCount) {
this.path = path;
this.value = value;
this.labelValues = labelValues;
+ this.childCount = childCount;
}
@Override
@@ -54,4 +59,17 @@ public final class SimpleFacetResult {
}
return sb.toString();
}
+
+ @Override
+ public boolean equals(Object _other) {
+ if ((_other instanceof SimpleFacetResult) == false) {
+ return false;
+ }
+ SimpleFacetResult other = (SimpleFacetResult) _other;
+ return path.equals(other.path) &&
+ value.equals(other.value) &&
+ Arrays.equals(labelValues, other.labelValues);
+ }
+
+ // nocommit hashCode
}
diff --git a/lucene/facet/src/java/org/apache/lucene/facet/simple/SortedSetDocValuesFacetCounts.java b/lucene/facet/src/java/org/apache/lucene/facet/simple/SortedSetDocValuesFacetCounts.java
index b822c4a4dd1..55f788eb2ff 100644
--- a/lucene/facet/src/java/org/apache/lucene/facet/simple/SortedSetDocValuesFacetCounts.java
+++ b/lucene/facet/src/java/org/apache/lucene/facet/simple/SortedSetDocValuesFacetCounts.java
@@ -93,6 +93,7 @@ public class SortedSetDocValuesFacetCounts extends Facets {
int bottomCount = 0;
int dimCount = 0;
+ int childCount = 0;
TopOrdAndIntQueue.OrdAndValue reuse = null;
//System.out.println("getDim : " + ordRange.start + " - " + ordRange.end);
@@ -100,6 +101,7 @@ public class SortedSetDocValuesFacetCounts extends Facets {
//System.out.println(" ord=" + ord + " count=" + counts[ord]);
if (counts[ord] > 0) {
dimCount += counts[ord];
+ childCount++;
if (counts[ord] > bottomCount) {
if (reuse == null) {
reuse = new TopOrdAndIntQueue.OrdAndValue();
@@ -129,11 +131,11 @@ public class SortedSetDocValuesFacetCounts extends Facets {
for(int i=labelValues.length-1;i>=0;i--) {
TopOrdAndIntQueue.OrdAndValue ordAndValue = q.pop();
dv.lookupOrd(ordAndValue.ord, scratch);
- String[] parts = DocumentBuilder.stringToPath(scratch.utf8ToString());
+ String[] parts = FacetsConfig.stringToPath(scratch.utf8ToString());
labelValues[i] = new LabelAndValue(parts[1], ordAndValue.value);
}
- return new SimpleFacetResult(new FacetLabel(dim), dimCount, labelValues);
+ return new SimpleFacetResult(new FacetLabel(dim), dimCount, labelValues, childCount);
}
/** Does all the "real work" of tallying up the counts. */
@@ -255,7 +257,7 @@ public class SortedSetDocValuesFacetCounts extends Facets {
}
// nocommit this is not thread safe in general? add
// jdocs that app must instantiate & use from same thread?
- int ord = (int) dv.lookupTerm(new BytesRef(DocumentBuilder.pathToString(dim, path)));
+ int ord = (int) dv.lookupTerm(new BytesRef(FacetsConfig.pathToString(dim, path)));
if (ord < 0) {
return -1;
}
diff --git a/lucene/facet/src/java/org/apache/lucene/facet/simple/SortedSetDocValuesReaderState.java b/lucene/facet/src/java/org/apache/lucene/facet/simple/SortedSetDocValuesReaderState.java
index aa752d2ada1..49aa209670e 100644
--- a/lucene/facet/src/java/org/apache/lucene/facet/simple/SortedSetDocValuesReaderState.java
+++ b/lucene/facet/src/java/org/apache/lucene/facet/simple/SortedSetDocValuesReaderState.java
@@ -110,7 +110,7 @@ public final class SortedSetDocValuesReaderState {
// support arbitrary hierarchy:
for(int ord=0;ord<valueCount;ord++) {
dv.lookupOrd(ord, spare);
- String[] components = DocumentBuilder.stringToPath(spare.utf8ToString());
+ String[] components = FacetsConfig.stringToPath(spare.utf8ToString());
if (components.length != 2) {
throw new IllegalArgumentException("this class can only handle 2 level hierarchy (dim/value); got: " + Arrays.toString(components) + " " + spare.utf8ToString());
}
diff --git a/lucene/facet/src/java/org/apache/lucene/facet/simple/TaxonomyFacetCounts.java b/lucene/facet/src/java/org/apache/lucene/facet/simple/TaxonomyFacetCounts.java
index a268e6051bb..6a354281d66 100644
--- a/lucene/facet/src/java/org/apache/lucene/facet/simple/TaxonomyFacetCounts.java
+++ b/lucene/facet/src/java/org/apache/lucene/facet/simple/TaxonomyFacetCounts.java
@@ -120,11 +120,13 @@ public class TaxonomyFacetCounts extends TaxonomyFacets {
int ord = children[dimOrd];
int totCount = 0;
+ int childCount = 0;
TopOrdAndIntQueue.OrdAndValue reuse = null;
while(ord != TaxonomyReader.INVALID_ORDINAL) {
if (counts[ord] > 0) {
totCount += counts[ord];
+ childCount++;
if (counts[ord] > bottomCount) {
if (reuse == null) {
reuse = new TopOrdAndIntQueue.OrdAndValue();
@@ -163,6 +165,6 @@ public class TaxonomyFacetCounts extends TaxonomyFacets {
labelValues[i] = new LabelAndValue(child.components[cp.length], ordAndValue.value);
}
- return new SimpleFacetResult(cp, totCount, labelValues);
+ return new SimpleFacetResult(cp, totCount, labelValues, childCount);
}
}
diff --git a/lucene/facet/src/java/org/apache/lucene/facet/simple/TaxonomyFacetSumFloatAssociations.java b/lucene/facet/src/java/org/apache/lucene/facet/simple/TaxonomyFacetSumFloatAssociations.java
index c7c9385c2c8..4b261edd62b 100644
--- a/lucene/facet/src/java/org/apache/lucene/facet/simple/TaxonomyFacetSumFloatAssociations.java
+++ b/lucene/facet/src/java/org/apache/lucene/facet/simple/TaxonomyFacetSumFloatAssociations.java
@@ -110,11 +110,12 @@ public class TaxonomyFacetSumFloatAssociations extends TaxonomyFacets {
int ord = children[dimOrd];
float sumValue = 0;
-
+ int childCount = 0;
TopOrdAndFloatQueue.OrdAndValue reuse = null;
while(ord != TaxonomyReader.INVALID_ORDINAL) {
if (values[ord] > 0) {
sumValue += values[ord];
+ childCount++;
if (values[ord] > bottomValue) {
if (reuse == null) {
reuse = new TopOrdAndFloatQueue.OrdAndValue();
@@ -143,6 +144,6 @@ public class TaxonomyFacetSumFloatAssociations extends TaxonomyFacets {
labelValues[i] = new LabelAndValue(child.components[path.length], ordAndValue.value);
}
- return new SimpleFacetResult(cp, sumValue, labelValues);
+ return new SimpleFacetResult(cp, sumValue, labelValues, childCount);
}
}
diff --git a/lucene/facet/src/java/org/apache/lucene/facet/simple/TaxonomyFacetSumIntAssociations.java b/lucene/facet/src/java/org/apache/lucene/facet/simple/TaxonomyFacetSumIntAssociations.java
index f6b94dfc10d..c8e73c2c517 100644
--- a/lucene/facet/src/java/org/apache/lucene/facet/simple/TaxonomyFacetSumIntAssociations.java
+++ b/lucene/facet/src/java/org/apache/lucene/facet/simple/TaxonomyFacetSumIntAssociations.java
@@ -110,11 +110,13 @@ public class TaxonomyFacetSumIntAssociations extends TaxonomyFacets {
int ord = children[dimOrd];
long sumValue = 0;
+ int childCount = 0;
TopOrdAndIntQueue.OrdAndValue reuse = null;
while(ord != TaxonomyReader.INVALID_ORDINAL) {
if (values[ord] > 0) {
sumValue += values[ord];
+ childCount++;
if (values[ord] > bottomValue) {
if (reuse == null) {
reuse = new TopOrdAndIntQueue.OrdAndValue();
@@ -143,6 +145,6 @@ public class TaxonomyFacetSumIntAssociations extends TaxonomyFacets {
labelValues[i] = new LabelAndValue(child.components[path.length], ordAndValue.value);
}
- return new SimpleFacetResult(cp, sumValue, labelValues);
+ return new SimpleFacetResult(cp, sumValue, labelValues, childCount);
}
}
diff --git a/lucene/facet/src/java/org/apache/lucene/facet/simple/TaxonomyFacetSumValueSource.java b/lucene/facet/src/java/org/apache/lucene/facet/simple/TaxonomyFacetSumValueSource.java
index 29aec03c853..e4a8517e584 100644
--- a/lucene/facet/src/java/org/apache/lucene/facet/simple/TaxonomyFacetSumValueSource.java
+++ b/lucene/facet/src/java/org/apache/lucene/facet/simple/TaxonomyFacetSumValueSource.java
@@ -25,8 +25,10 @@ import java.util.Map;
import org.apache.lucene.facet.simple.SimpleFacetsCollector.MatchingDocs;
import org.apache.lucene.facet.taxonomy.FacetLabel;
import org.apache.lucene.facet.taxonomy.TaxonomyReader;
+import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.queries.function.FunctionValues;
import org.apache.lucene.queries.function.ValueSource;
+import org.apache.lucene.queries.function.docvalues.DoubleDocValues;
import org.apache.lucene.search.Scorer;
import org.apache.lucene.util.FixedBitSet;
import org.apache.lucene.util.IntsRef;
@@ -74,7 +76,9 @@ public class TaxonomyFacetSumValueSource extends TaxonomyFacets {
private final void sumValues(List<MatchingDocs> matchingDocs, boolean keepScores, ValueSource valueSource) throws IOException {
final FakeScorer scorer = new FakeScorer();
Map<String, Scorer> context = new HashMap<String, Scorer>();
- context.put("scorer", scorer);
+ if (keepScores) {
+ context.put("scorer", scorer);
+ }
IntsRef scratch = new IntsRef();
for(MatchingDocs hits : matchingDocs) {
OrdinalsReader.OrdinalsSegmentReader ords = ordinalsReader.getReader(hits.context);
@@ -144,6 +148,7 @@ public class TaxonomyFacetSumValueSource extends TaxonomyFacets {
FacetLabel cp = FacetLabel.create(dim, path);
int dimOrd = taxoReader.getOrdinal(cp);
if (dimOrd == -1) {
+ System.out.println(" no dim ord " + dim);
return null;
}
@@ -152,11 +157,13 @@ public class TaxonomyFacetSumValueSource extends TaxonomyFacets {
int ord = children[dimOrd];
float sumValues = 0;
+ int childCount = 0;
TopOrdAndFloatQueue.OrdAndValue reuse = null;
while(ord != TaxonomyReader.INVALID_ORDINAL) {
if (values[ord] > 0) {
sumValues += values[ord];
+ childCount++;
if (values[ord] > bottomValue) {
if (reuse == null) {
reuse = new TopOrdAndFloatQueue.OrdAndValue();
@@ -174,6 +181,7 @@ public class TaxonomyFacetSumValueSource extends TaxonomyFacets {
}
if (sumValues == 0) {
+ System.out.println(" no sum");
return null;
}
@@ -195,6 +203,33 @@ public class TaxonomyFacetSumValueSource extends TaxonomyFacets {
labelValues[i] = new LabelAndValue(child.components[cp.length], ordAndValue.value);
}
- return new SimpleFacetResult(cp, sumValues, labelValues);
+ return new SimpleFacetResult(cp, sumValues, labelValues, childCount);
}
+
+ /** {@link ValueSource} that returns the score for each
+ * hit; use this to aggregate the sum of all hit scores
+ * for each facet label. */
+ public static class ScoreValueSource extends ValueSource {
+ @Override
+ public FunctionValues getValues(@SuppressWarnings("rawtypes") Map context, AtomicReaderContext readerContext) throws IOException {
+ final Scorer scorer = (Scorer) context.get("scorer");
+ if (scorer == null) {
+ throw new IllegalStateException("scores are missing; be sure to pass keepScores=true to SimpleFacetsCollector");
+ }
+ return new DoubleDocValues(this) {
+ @Override
+ public double doubleVal(int document) {
+ try {
+ return scorer.score();
+ } catch (IOException exception) {
+ throw new RuntimeException(exception);
+ }
+ }
+ };
+ }
+
+ @Override public boolean equals(Object o) { return o == this; }
+ @Override public int hashCode() { return System.identityHashCode(this); }
+ @Override public String description() { return "score()"; }
+ };
}
diff --git a/lucene/facet/src/java/org/apache/lucene/facet/taxonomy/FacetLabel.java b/lucene/facet/src/java/org/apache/lucene/facet/taxonomy/FacetLabel.java
index 0c350bd7103..cf6b224647f 100644
--- a/lucene/facet/src/java/org/apache/lucene/facet/taxonomy/FacetLabel.java
+++ b/lucene/facet/src/java/org/apache/lucene/facet/taxonomy/FacetLabel.java
@@ -20,7 +20,7 @@ package org.apache.lucene.facet.taxonomy;
import java.util.Arrays;
import java.util.regex.Pattern;
-import org.apache.lucene.facet.simple.DocumentBuilder;
+import org.apache.lucene.facet.simple.FacetsConfig;
import static org.apache.lucene.util.ByteBlockPool.BYTE_BLOCK_SIZE;
@@ -116,7 +116,7 @@ public class FacetLabel implements Comparable<FacetLabel> {
// nocommit
String[] comps;
if (delimiter == '\u001F') {
- comps = DocumentBuilder.stringToPath(pathString);
+ comps = FacetsConfig.stringToPath(pathString);
} else {
comps = pathString.split(Pattern.quote(Character.toString(delimiter)));
}
@@ -286,7 +286,7 @@ public class FacetLabel implements Comparable<FacetLabel> {
public String toString(char delimiter) {
// nocommit
if (delimiter == '\u001F') {
- return DocumentBuilder.pathToString(components, length);
+ return FacetsConfig.pathToString(components, length);
} else {
if (length == 0) return "";
StringBuilder sb = new StringBuilder();
diff --git a/lucene/facet/src/java/org/apache/lucene/facet/taxonomy/directory/DirectoryTaxonomyWriter.java b/lucene/facet/src/java/org/apache/lucene/facet/taxonomy/directory/DirectoryTaxonomyWriter.java
index 2c6a0ef689c..59df2c188ae 100644
--- a/lucene/facet/src/java/org/apache/lucene/facet/taxonomy/directory/DirectoryTaxonomyWriter.java
+++ b/lucene/facet/src/java/org/apache/lucene/facet/taxonomy/directory/DirectoryTaxonomyWriter.java
@@ -21,7 +21,7 @@ import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
-import org.apache.lucene.facet.simple.DocumentBuilder;
+import org.apache.lucene.facet.simple.FacetsConfig;
import org.apache.lucene.facet.taxonomy.FacetLabel;
import org.apache.lucene.facet.taxonomy.TaxonomyReader;
import org.apache.lucene.facet.taxonomy.TaxonomyWriter;
@@ -530,7 +530,7 @@ public class DirectoryTaxonomyWriter implements TaxonomyWriter {
Document d = new Document();
d.add(parentStreamField);
- fullPathField.setStringValue(DocumentBuilder.pathToString(categoryPath.components, categoryPath.length));
+ fullPathField.setStringValue(FacetsConfig.pathToString(categoryPath.components, categoryPath.length));
d.add(fullPathField);
// Note that we do no pass an Analyzer here because the fields that are
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 5dfc63f3d86..18b2d477fe4 100644
--- a/lucene/facet/src/test/org/apache/lucene/facet/FacetTestCase.java
+++ b/lucene/facet/src/test/org/apache/lucene/facet/FacetTestCase.java
@@ -72,11 +72,15 @@ public abstract class FacetTestCase extends LuceneTestCase {
}
public Facets getTaxonomyFacetCounts(TaxonomyReader taxoReader, FacetsConfig config, SimpleFacetsCollector c) throws IOException {
+ return getTaxonomyFacetCounts(taxoReader, config, c, FacetsConfig.DEFAULT_INDEX_FIELD_NAME);
+ }
+
+ public Facets getTaxonomyFacetCounts(TaxonomyReader taxoReader, FacetsConfig config, SimpleFacetsCollector c, String indexFieldName) throws IOException {
Facets facets;
if (random().nextBoolean()) {
- facets = new FastTaxonomyFacetCounts(taxoReader, config, c);
+ facets = new FastTaxonomyFacetCounts(indexFieldName, taxoReader, config, c);
} else {
- OrdinalsReader ordsReader = new DocValuesOrdinalsReader();
+ OrdinalsReader ordsReader = new DocValuesOrdinalsReader(indexFieldName);
if (random().nextBoolean()) {
ordsReader = new CachedOrdinalsReader(ordsReader);
}
diff --git a/lucene/facet/src/test/org/apache/lucene/facet/search/TestFacetsCollector.java b/lucene/facet/src/test/org/apache/lucene/facet/search/TestFacetsCollector.java
deleted file mode 100644
index bca36c6f111..00000000000
--- a/lucene/facet/src/test/org/apache/lucene/facet/search/TestFacetsCollector.java
+++ /dev/null
@@ -1,444 +0,0 @@
-package org.apache.lucene.facet.search;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-import org.apache.lucene.analysis.MockAnalyzer;
-import org.apache.lucene.document.Document;
-import org.apache.lucene.document.Field.Store;
-import org.apache.lucene.document.StringField;
-import org.apache.lucene.facet.FacetTestCase;
-import org.apache.lucene.facet.index.FacetFields;
-import org.apache.lucene.facet.old.AdaptiveFacetsAccumulator;
-import org.apache.lucene.facet.old.OldFacetsAccumulator;
-import org.apache.lucene.facet.params.CategoryListParams;
-import org.apache.lucene.facet.params.FacetIndexingParams;
-import org.apache.lucene.facet.params.FacetSearchParams;
-import org.apache.lucene.facet.params.PerDimensionIndexingParams;
-import org.apache.lucene.facet.range.LongRange;
-import org.apache.lucene.facet.range.RangeAccumulator;
-import org.apache.lucene.facet.range.RangeFacetRequest;
-import org.apache.lucene.facet.sampling.RandomSampler;
-import org.apache.lucene.facet.sampling.Sampler;
-import org.apache.lucene.facet.sampling.SamplingAccumulator;
-import org.apache.lucene.facet.sampling.SamplingParams;
-import org.apache.lucene.facet.sampling.SamplingWrapper;
-import org.apache.lucene.facet.sampling.TakmiSampleFixer;
-import org.apache.lucene.facet.search.FacetRequest.ResultMode;
-import org.apache.lucene.facet.sortedset.SortedSetDocValuesAccumulator;
-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.TaxonomyWriter;
-import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyReader;
-import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyWriter;
-import org.apache.lucene.index.DirectoryReader;
-import org.apache.lucene.index.IndexWriter;
-import org.apache.lucene.search.ConstantScoreQuery;
-import org.apache.lucene.search.IndexSearcher;
-import org.apache.lucene.search.MatchAllDocsQuery;
-import org.apache.lucene.search.MultiCollector;
-import org.apache.lucene.search.TopDocs;
-import org.apache.lucene.search.TopScoreDocCollector;
-import org.apache.lucene.store.Directory;
-import org.apache.lucene.util.IOUtils;
-import org.junit.Test;
-
-/*
- * 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.
- */
-
-public class TestFacetsCollector extends FacetTestCase {
-
- @Test
- public void testSumScoreAggregator() throws Exception {
- Directory indexDir = newDirectory();
- Directory taxoDir = newDirectory();
-
- TaxonomyWriter taxonomyWriter = new DirectoryTaxonomyWriter(taxoDir);
- IndexWriter iw = new IndexWriter(indexDir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
-
- FacetFields facetFields = new FacetFields(taxonomyWriter);
- for(int i = atLeast(30); i > 0; --i) {
- Document doc = new Document();
- if (random().nextBoolean()) { // don't match all documents
- doc.add(new StringField("f", "v", Store.NO));
- }
- facetFields.addFields(doc, Collections.singletonList(new FacetLabel("a")));
- iw.addDocument(doc);
- }
-
- taxonomyWriter.close();
- iw.close();
-
- DirectoryReader r = DirectoryReader.open(indexDir);
- DirectoryTaxonomyReader taxo = new DirectoryTaxonomyReader(taxoDir);
-
- FacetSearchParams fsp = new FacetSearchParams(new SumScoreFacetRequest(new FacetLabel("a"), 10));
- FacetsCollector fc = FacetsCollector.create(fsp, r, taxo);
- TopScoreDocCollector topDocs = TopScoreDocCollector.create(10, false);
- ConstantScoreQuery csq = new ConstantScoreQuery(new MatchAllDocsQuery());
- csq.setBoost(2.0f);
-
- newSearcher(r).search(csq, MultiCollector.wrap(fc, topDocs));
-
- List<FacetResult> res = fc.getFacetResults();
- float value = (float) res.get(0).getFacetResultNode().value;
- TopDocs td = topDocs.topDocs();
- int expected = (int) (td.getMaxScore() * td.totalHits);
- assertEquals(expected, (int) value);
-
- IOUtils.close(taxo, taxoDir, r, indexDir);
- }
-
- @Test
- public void testMultiCountingLists() throws Exception {
- Directory indexDir = newDirectory();
- Directory taxoDir = newDirectory();
-
- TaxonomyWriter taxonomyWriter = new DirectoryTaxonomyWriter(taxoDir);
- IndexWriter iw = new IndexWriter(indexDir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
- FacetIndexingParams fip = new PerDimensionIndexingParams(Collections.singletonMap(new FacetLabel("b"), new CategoryListParams("$b")));
-
- FacetFields facetFields = new FacetFields(taxonomyWriter, fip);
- for(int i = atLeast(30); i > 0; --i) {
- Document doc = new Document();
- doc.add(new StringField("f", "v", Store.NO));
- List<FacetLabel> cats = new ArrayList<FacetLabel>();
- cats.add(new FacetLabel("a"));
- cats.add(new FacetLabel("b"));
- facetFields.addFields(doc, cats);
- iw.addDocument(doc);
- }
-
- taxonomyWriter.close();
- iw.close();
-
- DirectoryReader r = DirectoryReader.open(indexDir);
- DirectoryTaxonomyReader taxo = new DirectoryTaxonomyReader(taxoDir);
-
- FacetSearchParams sParams = new FacetSearchParams(fip,
- new CountFacetRequest(new FacetLabel("a"), 10),
- new CountFacetRequest(new FacetLabel("b"), 10));
- FacetsCollector fc = FacetsCollector.create(sParams, r, taxo);
- newSearcher(r).search(new MatchAllDocsQuery(), fc);
-
- for (FacetResult res : fc.getFacetResults()) {
- assertEquals("unexpected count for " + res, r.maxDoc(), (int) res.getFacetResultNode().value);
- }
-
- IOUtils.close(taxo, taxoDir, r, indexDir);
- }
-
- @Test
- public void testCountAndSumScore() throws Exception {
- Directory indexDir = newDirectory();
- Directory taxoDir = newDirectory();
-
- TaxonomyWriter taxonomyWriter = new DirectoryTaxonomyWriter(taxoDir);
- IndexWriter iw = new IndexWriter(indexDir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
- FacetIndexingParams fip = new PerDimensionIndexingParams(Collections.singletonMap(new FacetLabel("b"), new CategoryListParams("$b")));
-
- FacetFields facetFields = new FacetFields(taxonomyWriter, fip);
- for(int i = atLeast(30); i > 0; --i) {
- Document doc = new Document();
- doc.add(new StringField("f", "v", Store.NO));
- List<FacetLabel> cats = new ArrayList<FacetLabel>();
- cats.add(new FacetLabel("a"));
- cats.add(new FacetLabel("b"));
- facetFields.addFields(doc, cats);
- iw.addDocument(doc);
- }
-
- taxonomyWriter.close();
- iw.close();
-
- DirectoryReader r = DirectoryReader.open(indexDir);
- DirectoryTaxonomyReader taxo = new DirectoryTaxonomyReader(taxoDir);
-
- FacetSearchParams sParams = new FacetSearchParams(fip,
- new CountFacetRequest(new FacetLabel("a"), 10),
- new SumScoreFacetRequest(new FacetLabel("b"), 10));
-
- FacetsCollector fc = FacetsCollector.create(sParams, r, taxo);
- TopScoreDocCollector topDocs = TopScoreDocCollector.create(10, false);
- newSearcher(r).search(new MatchAllDocsQuery(), MultiCollector.wrap(fc, topDocs));
-
- List<FacetResult> facetResults = fc.getFacetResults();
- FacetResult fresA = facetResults.get(0);
- assertEquals("unexpected count for " + fresA, r.maxDoc(), (int) fresA.getFacetResultNode().value);
-
- FacetResult fresB = facetResults.get(1);
- double expected = topDocs.topDocs().getMaxScore() * r.numDocs();
- assertEquals("unexpected value for " + fresB, expected, fresB.getFacetResultNode().value, 1E-10);
-
- IOUtils.close(taxo, taxoDir, r, indexDir);
- }
-
- @Test
- public void testCountRoot() throws Exception {
- // LUCENE-4882: FacetsAccumulator threw NPE if a FacetRequest was defined on CP.EMPTY
- Directory indexDir = newDirectory();
- Directory taxoDir = newDirectory();
-
- TaxonomyWriter taxonomyWriter = new DirectoryTaxonomyWriter(taxoDir);
- IndexWriter iw = new IndexWriter(indexDir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
-
- FacetFields facetFields = new FacetFields(taxonomyWriter);
- for(int i = atLeast(30); i > 0; --i) {
- Document doc = new Document();
- facetFields.addFields(doc, Arrays.asList(new FacetLabel("a"), new FacetLabel("b")));
- iw.addDocument(doc);
- }
-
- taxonomyWriter.close();
- iw.close();
-
- DirectoryReader r = DirectoryReader.open(indexDir);
- DirectoryTaxonomyReader taxo = new DirectoryTaxonomyReader(taxoDir);
-
- FacetSearchParams fsp = new FacetSearchParams(new CountFacetRequest(FacetLabel.EMPTY, 10));
-
- final TaxonomyFacetsAccumulator fa = random().nextBoolean() ? new TaxonomyFacetsAccumulator(fsp, r, taxo) : new OldFacetsAccumulator(fsp, r, taxo);
- FacetsCollector fc = FacetsCollector.create(fa);
- newSearcher(r).search(new MatchAllDocsQuery(), fc);
-
- FacetResult res = fc.getFacetResults().get(0);
- for (FacetResultNode node : res.getFacetResultNode().subResults) {
- assertEquals(r.numDocs(), (int) node.value);
- }
-
- IOUtils.close(taxo, taxoDir, r, indexDir);
- }
-
- @Test
- public void testGetFacetResultsTwice() throws Exception {
- // LUCENE-4893: counts were multiplied as many times as getFacetResults was called.
- Directory indexDir = newDirectory();
- Directory taxoDir = newDirectory();
-
- TaxonomyWriter taxonomyWriter = new DirectoryTaxonomyWriter(taxoDir);
- IndexWriter iw = new IndexWriter(indexDir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
-
- FacetFields facetFields = new FacetFields(taxonomyWriter);
- Document doc = new Document();
- facetFields.addFields(doc, Arrays.asList(new FacetLabel("a/1", '/'), new FacetLabel("b/1", '/')));
- iw.addDocument(doc);
- taxonomyWriter.close();
- iw.close();
-
- DirectoryReader r = DirectoryReader.open(indexDir);
- DirectoryTaxonomyReader taxo = new DirectoryTaxonomyReader(taxoDir);
-
- FacetSearchParams fsp = new FacetSearchParams(
- new CountFacetRequest(new FacetLabel("a"), 10),
- new CountFacetRequest(new FacetLabel("b"), 10));
- final TaxonomyFacetsAccumulator fa = random().nextBoolean() ? new TaxonomyFacetsAccumulator(fsp, r, taxo) : new OldFacetsAccumulator(fsp, r, taxo);
- final FacetsCollector fc = FacetsCollector.create(fa);
- newSearcher(r).search(new MatchAllDocsQuery(), fc);
-
- List<FacetResult> res1 = fc.getFacetResults();
- List<FacetResult> res2 = fc.getFacetResults();
- assertSame("calling getFacetResults twice should return the exact same result", res1, res2);
-
- IOUtils.close(taxo, taxoDir, r, indexDir);
- }
-
- @Test
- public void testReset() throws Exception {
- Directory indexDir = newDirectory();
- Directory taxoDir = newDirectory();
-
- TaxonomyWriter taxonomyWriter = new DirectoryTaxonomyWriter(taxoDir);
- IndexWriter iw = new IndexWriter(indexDir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
-
- FacetFields facetFields = new FacetFields(taxonomyWriter);
- Document doc = new Document();
- facetFields.addFields(doc, Arrays.asList(new FacetLabel("a/1", '/'), new FacetLabel("b/1", '/')));
- iw.addDocument(doc);
- taxonomyWriter.close();
- iw.close();
-
- DirectoryReader r = DirectoryReader.open(indexDir);
- DirectoryTaxonomyReader taxo = new DirectoryTaxonomyReader(taxoDir);
-
- FacetSearchParams fsp = new FacetSearchParams(
- new CountFacetRequest(new FacetLabel("a"), 10),
- new CountFacetRequest(new FacetLabel("b"), 10));
- final TaxonomyFacetsAccumulator fa = random().nextBoolean() ? new TaxonomyFacetsAccumulator(fsp, r, taxo) : new OldFacetsAccumulator(fsp, r, taxo);
- final FacetsCollector fc = FacetsCollector.create(fa);
- // this should populate the cached results, but doing search should clear the cache
- fc.getFacetResults();
- newSearcher(r).search(new MatchAllDocsQuery(), fc);
-
- List<FacetResult> res1 = fc.getFacetResults();
- // verify that we didn't get the cached result
- assertEquals(2, res1.size());
- for (FacetResult res : res1) {
- assertEquals(1, res.getFacetResultNode().subResults.size());
- assertEquals(1, (int) res.getFacetResultNode().subResults.get(0).value);
- }
- fc.reset();
- List<FacetResult> res2 = fc.getFacetResults();
- assertNotSame("reset() should clear the cached results", res1, res2);
-
- IOUtils.close(taxo, taxoDir, r, indexDir);
- }
-
- @Test
- public void testParentOrdinal() throws Exception {
- // LUCENE-4913: root ordinal was always 0 when all children were requested
- Directory indexDir = newDirectory();
- Directory taxoDir = newDirectory();
-
- TaxonomyWriter taxonomyWriter = new DirectoryTaxonomyWriter(taxoDir);
- IndexWriter iw = new IndexWriter(indexDir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
-
- FacetFields facetFields = new FacetFields(taxonomyWriter);
- Document doc = new Document();
- facetFields.addFields(doc, Arrays.asList(new FacetLabel("a/1", '/')));
- iw.addDocument(doc);
- taxonomyWriter.close();
- iw.close();
-
- DirectoryReader r = DirectoryReader.open(indexDir);
- DirectoryTaxonomyReader taxo = new DirectoryTaxonomyReader(taxoDir);
-
- // assert IntFacetResultHandler
- FacetSearchParams fsp = new FacetSearchParams(new CountFacetRequest(new FacetLabel("a"), 10));
- TaxonomyFacetsAccumulator fa = random().nextBoolean() ? new TaxonomyFacetsAccumulator(fsp, r, taxo) : new OldFacetsAccumulator(fsp, r, taxo);
- FacetsCollector fc = FacetsCollector.create(fa);
- newSearcher(r).search(new MatchAllDocsQuery(), fc);
- assertTrue("invalid ordinal for child node: 0", 0 != fc.getFacetResults().get(0).getFacetResultNode().subResults.get(0).ordinal);
-
- // assert IntFacetResultHandler
- fsp = new FacetSearchParams(new SumScoreFacetRequest(new FacetLabel("a"), 10));
- if (random().nextBoolean()) {
- fa = new TaxonomyFacetsAccumulator(fsp, r, taxo);
- } else {
- fa = new OldFacetsAccumulator(fsp, r, taxo);
- }
- fc = FacetsCollector.create(fa);
- newSearcher(r).search(new MatchAllDocsQuery(), fc);
- assertTrue("invalid ordinal for child node: 0", 0 != fc.getFacetResults().get(0).getFacetResultNode().subResults.get(0).ordinal);
-
- IOUtils.close(taxo, taxoDir, r, indexDir);
- }
-
- @Test
- public void testNumValidDescendants() throws Exception {
- // LUCENE-4885: FacetResult.numValidDescendants was not set properly by FacetsAccumulator
- Directory indexDir = newDirectory();
- Directory taxoDir = newDirectory();
-
- TaxonomyWriter taxonomyWriter = new DirectoryTaxonomyWriter(taxoDir);
- IndexWriter iw = new IndexWriter(indexDir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
-
- FacetFields facetFields = new FacetFields(taxonomyWriter);
- for (int i = 0; i < 10; i++) {
- Document doc = new Document();
- facetFields.addFields(doc, Arrays.asList(new FacetLabel("a", Integer.toString(i))));
- iw.addDocument(doc);
- }
-
- taxonomyWriter.close();
- iw.close();
-
- DirectoryReader r = DirectoryReader.open(indexDir);
- DirectoryTaxonomyReader taxo = new DirectoryTaxonomyReader(taxoDir);
-
- CountFacetRequest cfr = new CountFacetRequest(new FacetLabel("a"), 2);
- cfr.setResultMode(random().nextBoolean() ? ResultMode.GLOBAL_FLAT : ResultMode.PER_NODE_IN_TREE);
- FacetSearchParams fsp = new FacetSearchParams(cfr);
- final TaxonomyFacetsAccumulator fa = random().nextBoolean() ? new TaxonomyFacetsAccumulator(fsp, r, taxo) : new OldFacetsAccumulator(fsp, r, taxo);
- FacetsCollector fc = FacetsCollector.create(fa);
- newSearcher(r).search(new MatchAllDocsQuery(), fc);
-
- FacetResult res = fc.getFacetResults().get(0);
- assertEquals(10, res.getNumValidDescendants());
-
- IOUtils.close(taxo, taxoDir, r, indexDir);
- }
-
- @Test
- public void testLabeling() throws Exception {
- Directory indexDir = newDirectory(), taxoDir = newDirectory();
-
- // create the index
- IndexWriter indexWriter = new IndexWriter(indexDir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
- DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir);
- FacetFields facetFields = new FacetFields(taxoWriter);
- Document doc = new Document();
- facetFields.addFields(doc, Arrays.asList(new FacetLabel("A/1", '/')));
- indexWriter.addDocument(doc);
- IOUtils.close(indexWriter, taxoWriter);
-
- DirectoryReader indexReader = DirectoryReader.open(indexDir);
- TaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoDir);
- IndexSearcher searcher = new IndexSearcher(indexReader);
- // ask to count a non-existing category to test labeling
- FacetSearchParams fsp = new FacetSearchParams(new CountFacetRequest(new FacetLabel("B"), 5));
-
- final SamplingParams sampleParams = new SamplingParams();
- sampleParams.setMaxSampleSize(100);
- sampleParams.setMinSampleSize(100);
- sampleParams.setSamplingThreshold(100);
- sampleParams.setOversampleFactor(1.0d);
- if (random().nextBoolean()) {
- sampleParams.setSampleFixer(new TakmiSampleFixer(indexReader, taxoReader, fsp));
- }
- final Sampler sampler = new RandomSampler(sampleParams, random());
-
- TaxonomyFacetsAccumulator[] accumulators = new TaxonomyFacetsAccumulator[] {
- new TaxonomyFacetsAccumulator(fsp, indexReader, taxoReader),
- new OldFacetsAccumulator(fsp, indexReader, taxoReader),
- new SamplingAccumulator(sampler, fsp, indexReader, taxoReader),
- new AdaptiveFacetsAccumulator(fsp, indexReader, taxoReader),
- new SamplingWrapper(new OldFacetsAccumulator(fsp, indexReader, taxoReader), sampler)
- };
-
- for (TaxonomyFacetsAccumulator fa : accumulators) {
- FacetsCollector fc = FacetsCollector.create(fa);
- searcher.search(new MatchAllDocsQuery(), fc);
- List<FacetResult> facetResults = fc.getFacetResults();
- assertNotNull(facetResults);
- assertEquals("incorrect label returned for " + fa, fsp.facetRequests.get(0).categoryPath, facetResults.get(0).getFacetResultNode().label);
- }
-
- try {
- // SortedSetDocValuesAccumulator cannot even be created in such state
- assertNull(new SortedSetDocValuesAccumulator(new SortedSetDocValuesReaderState(indexReader), fsp));
- // if this ever changes, make sure FacetResultNode is labeled correctly
- fail("should not have succeeded to execute a request over a category which wasn't indexed as SortedSetDVField");
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- RangeAccumulator ra = new RangeAccumulator(new RangeFacetRequest<LongRange>("f", new LongRange("grr", 0, true, 1, true)));
- FacetsCollector fc = FacetsCollector.create(ra);
- searcher.search(new MatchAllDocsQuery(), fc);
- List<FacetResult> facetResults = fc.getFacetResults();
- assertNotNull(facetResults);
- assertEquals("incorrect label returned for RangeAccumulator", new FacetLabel("f"), facetResults.get(0).getFacetResultNode().label);
-
- IOUtils.close(indexReader, taxoReader);
-
- IOUtils.close(indexDir, taxoDir);
- }
-
-}
diff --git a/lucene/facet/src/test/org/apache/lucene/facet/search/TestSumValueSourceFacetRequest.java b/lucene/facet/src/test/org/apache/lucene/facet/search/TestSumValueSourceFacetRequest.java
deleted file mode 100644
index e04af0c8375..00000000000
--- a/lucene/facet/src/test/org/apache/lucene/facet/search/TestSumValueSourceFacetRequest.java
+++ /dev/null
@@ -1,185 +0,0 @@
-package org.apache.lucene.facet.search;
-
-import java.io.IOException;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.lucene.analysis.MockAnalyzer;
-import org.apache.lucene.document.Document;
-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.CategoryListParams;
-import org.apache.lucene.facet.params.FacetIndexingParams;
-import org.apache.lucene.facet.params.FacetSearchParams;
-import org.apache.lucene.facet.taxonomy.FacetLabel;
-import org.apache.lucene.facet.taxonomy.TaxonomyWriter;
-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.DirectoryReader;
-import org.apache.lucene.index.IndexWriter;
-import org.apache.lucene.queries.function.FunctionQuery;
-import org.apache.lucene.queries.function.FunctionValues;
-import org.apache.lucene.queries.function.ValueSource;
-import org.apache.lucene.queries.function.docvalues.DoubleDocValues;
-import org.apache.lucene.queries.function.valuesource.LongFieldSource;
-import org.apache.lucene.search.MatchAllDocsQuery;
-import org.apache.lucene.search.MultiCollector;
-import org.apache.lucene.search.Query;
-import org.apache.lucene.search.Scorer;
-import org.apache.lucene.search.TopScoreDocCollector;
-import org.apache.lucene.store.Directory;
-import org.apache.lucene.util.IOUtils;
-import org.junit.Test;
-
-/*
- * 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.
- */
-
-public class TestSumValueSourceFacetRequest extends FacetTestCase {
-
- @Test
- public void testNoScore() throws Exception {
- Directory indexDir = newDirectory();
- Directory taxoDir = newDirectory();
-
- TaxonomyWriter taxonomyWriter = new DirectoryTaxonomyWriter(taxoDir);
- IndexWriter iw = new IndexWriter(indexDir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
-
- FacetFields facetFields = new FacetFields(taxonomyWriter);
- for (int i = 0; i < 4; i++) {
- Document doc = new Document();
- doc.add(new NumericDocValuesField("price", (i+1)));
- facetFields.addFields(doc, Collections.singletonList(new FacetLabel("a", Integer.toString(i % 2))));
- iw.addDocument(doc);
- }
-
- taxonomyWriter.close();
- iw.close();
-
- DirectoryReader r = DirectoryReader.open(indexDir);
- DirectoryTaxonomyReader taxo = new DirectoryTaxonomyReader(taxoDir);
-
- ValueSource valueSource = new LongFieldSource("price");
- FacetSearchParams fsp = new FacetSearchParams(new SumValueSourceFacetRequest(new FacetLabel("a"), 10, valueSource, false));
- FacetsCollector fc = FacetsCollector.create(fsp, r, taxo);
- newSearcher(r).search(new MatchAllDocsQuery(), fc);
-
- List<FacetResult> res = fc.getFacetResults();
- assertEquals("a (0)\n 1 (6)\n 0 (4)\n", FacetTestUtils.toSimpleString(res.get(0)));
-
- IOUtils.close(taxo, taxoDir, r, indexDir);
- }
-
- @Test
- public void testWithScore() throws Exception {
- Directory indexDir = newDirectory();
- Directory taxoDir = newDirectory();
-
- TaxonomyWriter taxonomyWriter = new DirectoryTaxonomyWriter(taxoDir);
- IndexWriter iw = new IndexWriter(indexDir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
-
- FacetFields facetFields = new FacetFields(taxonomyWriter);
- for (int i = 0; i < 4; i++) {
- Document doc = new Document();
- doc.add(new NumericDocValuesField("price", (i+1)));
- facetFields.addFields(doc, Collections.singletonList(new FacetLabel("a", Integer.toString(i % 2))));
- iw.addDocument(doc);
- }
-
- taxonomyWriter.close();
- iw.close();
-
- DirectoryReader r = DirectoryReader.open(indexDir);
- DirectoryTaxonomyReader taxo = new DirectoryTaxonomyReader(taxoDir);
-
- ValueSource valueSource = new ValueSource() {
- @Override
- public FunctionValues getValues(@SuppressWarnings("rawtypes") Map context, AtomicReaderContext readerContext) throws IOException {
- final Scorer scorer = (Scorer) context.get("scorer");
- assert scorer != null;
- return new DoubleDocValues(this) {
- @Override
- public double doubleVal(int document) {
- try {
- return scorer.score();
- } catch (IOException exception) {
- throw new RuntimeException(exception);
- }
- }
- };
- }
-
- @Override public boolean equals(Object o) { return o == this; }
- @Override public int hashCode() { return System.identityHashCode(this); }
- @Override public String description() { return "score()"; }
- };
-
- FacetSearchParams fsp = new FacetSearchParams(new SumValueSourceFacetRequest(new FacetLabel("a"), 10, valueSource, true));
- FacetsCollector fc = FacetsCollector.create(fsp, r, taxo);
- TopScoreDocCollector tsdc = TopScoreDocCollector.create(10, true);
- // score documents by their 'price' field - makes asserting the correct counts for the categories easier
- Query q = new FunctionQuery(new LongFieldSource("price"));
- newSearcher(r).search(q, MultiCollector.wrap(tsdc, fc));
-
- List<FacetResult> res = fc.getFacetResults();
- assertEquals("a (0)\n 1 (6)\n 0 (4)\n", FacetTestUtils.toSimpleString(res.get(0)));
-
- IOUtils.close(taxo, taxoDir, r, indexDir);
- }
-
- @Test
- public void testRollupValues() throws Exception {
- Directory indexDir = newDirectory();
- Directory taxoDir = newDirectory();
-
- TaxonomyWriter taxonomyWriter = new DirectoryTaxonomyWriter(taxoDir);
- IndexWriter iw = new IndexWriter(indexDir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
- FacetIndexingParams fip = new FacetIndexingParams(new CategoryListParams() {
- @Override
- public OrdinalPolicy getOrdinalPolicy(String dimension) {
- return OrdinalPolicy.NO_PARENTS;
- }
- });
- FacetFields facetFields = new FacetFields(taxonomyWriter, fip);
- for (int i = 0; i < 4; i++) {
- Document doc = new Document();
- doc.add(new NumericDocValuesField("price", (i+1)));
- facetFields.addFields(doc, Collections.singletonList(new FacetLabel("a", Integer.toString(i % 2), "1")));
- iw.addDocument(doc);
- }
-
- taxonomyWriter.close();
- iw.close();
-
- DirectoryReader r = DirectoryReader.open(indexDir);
- DirectoryTaxonomyReader taxo = new DirectoryTaxonomyReader(taxoDir);
-
- ValueSource valueSource = new LongFieldSource("price");
- FacetSearchParams fsp = new FacetSearchParams(fip, new SumValueSourceFacetRequest(new FacetLabel("a"), 10, valueSource, false));
- FacetsCollector fc = FacetsCollector.create(fsp, r, taxo);
- newSearcher(r).search(new MatchAllDocsQuery(), fc);
-
- List<FacetResult> res = fc.getFacetResults();
- assertEquals("a (10)\n 1 (6)\n 0 (4)\n", FacetTestUtils.toSimpleString(res.get(0)));
-
- IOUtils.close(taxo, taxoDir, r, indexDir);
- }
-
-}
diff --git a/lucene/facet/src/test/org/apache/lucene/facet/simple/TestDocumentBuilder.java b/lucene/facet/src/test/org/apache/lucene/facet/simple/TestFacetsConfig.java
similarity index 88%
rename from lucene/facet/src/test/org/apache/lucene/facet/simple/TestDocumentBuilder.java
rename to lucene/facet/src/test/org/apache/lucene/facet/simple/TestFacetsConfig.java
index 988367db9c2..d3f17df452d 100644
--- a/lucene/facet/src/test/org/apache/lucene/facet/simple/TestDocumentBuilder.java
+++ b/lucene/facet/src/test/org/apache/lucene/facet/simple/TestFacetsConfig.java
@@ -22,7 +22,7 @@ import java.util.Arrays;
import org.apache.lucene.facet.FacetTestCase;
import org.apache.lucene.util._TestUtil;
-public class TestDocumentBuilder extends FacetTestCase {
+public class TestFacetsConfig extends FacetTestCase {
public void testPathToStringAndBack() throws Exception {
int iters = atLeast(1000);
for(int i=0;i<iters;i++) {
@@ -32,8 +32,8 @@ public class TestDocumentBuilder extends FacetTestCase {
parts[j] = _TestUtil.randomUnicodeString(random());
}
- String s = DocumentBuilder.pathToString(parts);
- String[] parts2 = DocumentBuilder.stringToPath(s);
+ String s = FacetsConfig.pathToString(parts);
+ String[] parts2 = FacetsConfig.stringToPath(s);
assertTrue(Arrays.equals(parts, parts2));
}
}
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 176c4c0d66f..37b38f041e2 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
@@ -111,8 +111,7 @@ public class TestRangeFacets extends FacetTestCase {
Directory td = newDirectory();
DirectoryTaxonomyWriter tw = new DirectoryTaxonomyWriter(td, IndexWriterConfig.OpenMode.CREATE);
- FacetsConfig config = new FacetsConfig();
- DocumentBuilder builder = new DocumentBuilder(tw, config);
+ FacetsConfig config = new FacetsConfig(tw);
for (long l = 0; l < 100; l++) {
Document doc = new Document();
@@ -126,7 +125,7 @@ public class TestRangeFacets extends FacetTestCase {
} else {
doc.add(new FacetField("dim", "b"));
}
- w.addDocument(builder.build(doc));
+ w.addDocument(config.build(doc));
}
final IndexReader r = w.getReader();
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 803bf94d81e..a400c30003b 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
@@ -74,36 +74,35 @@ public class TestSimpleDrillSideways extends FacetTestCase {
// main index:
DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir, IndexWriterConfig.OpenMode.CREATE);
- FacetsConfig config = new FacetsConfig();
+ FacetsConfig config = new FacetsConfig(taxoWriter);
config.setHierarchical("Publish Date", true);
RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
- DocumentBuilder builder = new DocumentBuilder(taxoWriter, config);
Document doc = new Document();
doc.add(new FacetField("Author", "Bob"));
doc.add(new FacetField("Publish Date", "2010", "10", "15"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
doc = new Document();
doc.add(new FacetField("Author", "Lisa"));
doc.add(new FacetField("Publish Date", "2010", "10", "20"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
doc = new Document();
doc.add(new FacetField("Author", "Lisa"));
doc.add(new FacetField("Publish Date", "2012", "1", "1"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
doc = new Document();
doc.add(new FacetField("Author", "Susan"));
doc.add(new FacetField("Publish Date", "2012", "1", "7"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
doc = new Document();
doc.add(new FacetField("Author", "Frank"));
doc.add(new FacetField("Publish Date", "1999", "5", "5"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
// NRT open
IndexSearcher searcher = newSearcher(writer.getReader());
@@ -247,22 +246,18 @@ public class TestSimpleDrillSideways extends FacetTestCase {
// main index:
DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir, IndexWriterConfig.OpenMode.CREATE);
- FacetsConfig config = new FacetsConfig();
+ FacetsConfig config = new FacetsConfig(taxoWriter);
config.setHierarchical("Publish Date", true);
- // Reused across documents, to add the necessary facet
- // fields:
- DocumentBuilder builder = new DocumentBuilder(taxoWriter, config);
-
Document doc = new Document();
doc.add(new FacetField("Author", "Bob"));
doc.add(new FacetField("Publish Date", "2010", "10", "15"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
doc = new Document();
doc.add(new FacetField("Author", "Lisa"));
doc.add(new FacetField("Publish Date", "2010", "10", "20"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
writer.commit();
@@ -270,7 +265,7 @@ public class TestSimpleDrillSideways extends FacetTestCase {
doc = new Document();
doc.add(new FacetField("Foobar", "Lisa"));
doc.add(new FacetField("Publish Date", "2012", "1", "1"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
// NRT open
IndexSearcher searcher = newSearcher(writer.getReader());
@@ -301,40 +296,36 @@ public class TestSimpleDrillSideways extends FacetTestCase {
Directory taxoDir = newDirectory();
RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
- FacetsConfig config = new FacetsConfig();
- config.setHierarchical("dim", true);
-
// Writes facet ords to a separate directory from the
// main index:
DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir, IndexWriterConfig.OpenMode.CREATE);
- // Reused across documents, to add the necessary facet
- // fields:
- DocumentBuilder builder = new DocumentBuilder(taxoWriter, config);
+ FacetsConfig config = new FacetsConfig(taxoWriter);
+ config.setHierarchical("dim", true);
Document doc = new Document();
doc.add(new FacetField("dim", "a", "x"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
doc = new Document();
doc.add(new FacetField("dim", "a", "y"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
doc = new Document();
doc.add(new FacetField("dim", "a", "z"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
doc = new Document();
doc.add(new FacetField("dim", "b"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
doc = new Document();
doc.add(new FacetField("dim", "c"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
doc = new Document();
doc.add(new FacetField("dim", "d"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
// NRT open
IndexSearcher searcher = newSearcher(writer.getReader());
@@ -485,11 +476,10 @@ public class TestSimpleDrillSideways extends FacetTestCase {
iwc.setInfoStream(InfoStream.NO_OUTPUT);
RandomIndexWriter w = new RandomIndexWriter(random(), d, iwc);
DirectoryTaxonomyWriter tw = new DirectoryTaxonomyWriter(td, IndexWriterConfig.OpenMode.CREATE);
- FacetsConfig config = new FacetsConfig();
+ FacetsConfig config = new FacetsConfig(tw);
for(int i=0;i<numDims;i++) {
config.setMultiValued("dim"+i, true);
}
- DocumentBuilder builder = new DocumentBuilder(tw, config);
boolean doUseDV = canUseDV && random().nextBoolean();
@@ -528,7 +518,7 @@ public class TestSimpleDrillSideways extends FacetTestCase {
}
}
- w.addDocument(builder.build(doc));
+ w.addDocument(config.build(doc));
}
if (random().nextBoolean()) {
diff --git a/lucene/facet/src/test/org/apache/lucene/facet/simple/TestSortedSetDocValuesFacets.java b/lucene/facet/src/test/org/apache/lucene/facet/simple/TestSortedSetDocValuesFacets.java
index 30de5227a87..11645c701d2 100644
--- a/lucene/facet/src/test/org/apache/lucene/facet/simple/TestSortedSetDocValuesFacets.java
+++ b/lucene/facet/src/test/org/apache/lucene/facet/simple/TestSortedSetDocValuesFacets.java
@@ -36,33 +36,29 @@ public class TestSortedSetDocValuesFacets extends FacetTestCase {
// randomly uses SortedSetDV
public void testBasic() throws Exception {
- System.out.println("here: " + defaultCodecSupportsSortedSet());
assumeTrue("Test requires SortedSetDV support", defaultCodecSupportsSortedSet());
Directory dir = newDirectory();
FacetsConfig config = new FacetsConfig();
config.setMultiValued("a", true);
RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
- DocumentBuilder builder = new DocumentBuilder(null, config);
Document doc = new Document();
doc.add(new SortedSetDocValuesFacetField("a", "foo"));
doc.add(new SortedSetDocValuesFacetField("a", "bar"));
doc.add(new SortedSetDocValuesFacetField("a", "zoo"));
doc.add(new SortedSetDocValuesFacetField("b", "baz"));
- System.out.println("TEST: now add");
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
if (random().nextBoolean()) {
writer.commit();
}
doc = new Document();
doc.add(new SortedSetDocValuesFacetField("a", "foo"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
// NRT open
IndexSearcher searcher = newSearcher(writer.getReader());
- writer.close();
// Per-top-reader state:
SortedSetDocValuesReaderState state = new SortedSetDocValuesReaderState(searcher.getIndexReader());
@@ -83,8 +79,7 @@ public class TestSortedSetDocValuesFacets extends FacetTestCase {
TopDocs hits = searcher.search(q, 1);
assertEquals(1, hits.totalHits);
- searcher.getIndexReader().close();
- dir.close();
+ IOUtils.close(writer, searcher.getIndexReader(), dir);
}
// LUCENE-5090
@@ -93,22 +88,23 @@ public class TestSortedSetDocValuesFacets extends FacetTestCase {
Directory dir = newDirectory();
RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
- DocumentBuilder builder = new DocumentBuilder(null, new FacetsConfig());
+
+ FacetsConfig config = new FacetsConfig();
Document doc = new Document();
doc.add(new SortedSetDocValuesFacetField("a", "foo"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
IndexReader r = writer.getReader();
SortedSetDocValuesReaderState state = new SortedSetDocValuesReaderState(r);
doc = new Document();
doc.add(new SortedSetDocValuesFacetField("a", "bar"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
doc = new Document();
doc.add(new SortedSetDocValuesFacetField("a", "baz"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
IndexSearcher searcher = newSearcher(writer.getReader());
@@ -135,11 +131,12 @@ public class TestSortedSetDocValuesFacets extends FacetTestCase {
Directory dir = newDirectory();
RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
- DocumentBuilder builder = new DocumentBuilder(null, new FacetsConfig());
+
+ FacetsConfig config = new FacetsConfig();
Document doc = new Document();
doc.add(new SortedSetDocValuesFacetField("a", "foo1"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
if (random().nextBoolean()) {
writer.commit();
@@ -148,7 +145,7 @@ public class TestSortedSetDocValuesFacets extends FacetTestCase {
doc = new Document();
doc.add(new SortedSetDocValuesFacetField("a", "foo2"));
doc.add(new SortedSetDocValuesFacetField("b", "bar1"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
if (random().nextBoolean()) {
writer.commit();
@@ -158,7 +155,7 @@ public class TestSortedSetDocValuesFacets extends FacetTestCase {
doc.add(new SortedSetDocValuesFacetField("a", "foo3"));
doc.add(new SortedSetDocValuesFacetField("b", "bar2"));
doc.add(new SortedSetDocValuesFacetField("c", "baz1"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
// NRT open
IndexSearcher searcher = newSearcher(writer.getReader());
@@ -194,17 +191,18 @@ public class TestSortedSetDocValuesFacets extends FacetTestCase {
Directory dir = newDirectory();
RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
- DocumentBuilder builder = new DocumentBuilder(null, new FacetsConfig());
+
+ FacetsConfig config = new FacetsConfig();
Document doc = new Document();
doc.add(new SortedSetDocValuesFacetField("a", "foo1"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
writer.commit();
doc = new Document();
doc.add(new SortedSetDocValuesFacetField("a", "foo2"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
// NRT open
IndexSearcher searcher = new IndexSearcher(SlowCompositeReaderWrapper.wrap(writer.getReader()));
diff --git a/lucene/facet/src/test/org/apache/lucene/facet/simple/TestTaxonomyFacetAssociations.java b/lucene/facet/src/test/org/apache/lucene/facet/simple/TestTaxonomyFacetAssociations.java
index 24c0560a155..2a0fdd511f8 100644
--- a/lucene/facet/src/test/org/apache/lucene/facet/simple/TestTaxonomyFacetAssociations.java
+++ b/lucene/facet/src/test/org/apache/lucene/facet/simple/TestTaxonomyFacetAssociations.java
@@ -46,7 +46,7 @@ public class TestTaxonomyFacetAssociations extends FacetTestCase {
private static final FacetLabel bint = new FacetLabel("int", "b");
private static final FacetLabel afloat = new FacetLabel("float", "a");
private static final FacetLabel bfloat = new FacetLabel("float", "b");
- private static final FacetsConfig config = new FacetsConfig();
+ private static FacetsConfig config;
@BeforeClass
public static void beforeClass() throws Exception {
@@ -57,13 +57,13 @@ public class TestTaxonomyFacetAssociations extends FacetTestCase {
TaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir);
// Cannot mix ints & floats in the same indexed field:
+ config = new FacetsConfig(taxoWriter);
config.setIndexFieldName("int", "$facets.int");
config.setMultiValued("int", true);
config.setIndexFieldName("float", "$facets.float");
config.setMultiValued("float", true);
RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
- DocumentBuilder builder = new DocumentBuilder(taxoWriter, config);
// index documents, 50% have only 'b' and all have 'a'
for (int i = 0; i < 110; i++) {
@@ -78,7 +78,7 @@ public class TestTaxonomyFacetAssociations extends FacetTestCase {
doc.add(new FloatAssociationFacetField(0.2f, "float", "b"));
}
}
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
}
taxoWriter.close();
@@ -166,15 +166,14 @@ public class TestTaxonomyFacetAssociations extends FacetTestCase {
Directory taxoDir = newDirectory();
TaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir);
- FacetsConfig config = new FacetsConfig();
+ FacetsConfig config = new FacetsConfig(taxoWriter);
RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
- DocumentBuilder builder = new DocumentBuilder(taxoWriter, config);
Document doc = new Document();
doc.add(new IntAssociationFacetField(14, "a", "x"));
doc.add(new FloatAssociationFacetField(55.0f, "b", "y"));
try {
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
fail("did not hit expected exception");
} catch (IllegalArgumentException exc) {
// expected
@@ -187,15 +186,14 @@ public class TestTaxonomyFacetAssociations extends FacetTestCase {
Directory taxoDir = newDirectory();
TaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir);
- FacetsConfig config = new FacetsConfig();
+ FacetsConfig config = new FacetsConfig(taxoWriter);
config.setHierarchical("a", true);
RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
- DocumentBuilder builder = new DocumentBuilder(taxoWriter, config);
Document doc = new Document();
doc.add(new IntAssociationFacetField(14, "a", "x"));
try {
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
fail("did not hit expected exception");
} catch (IllegalArgumentException exc) {
// expected
@@ -208,15 +206,14 @@ public class TestTaxonomyFacetAssociations extends FacetTestCase {
Directory taxoDir = newDirectory();
TaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir);
- FacetsConfig config = new FacetsConfig();
+ FacetsConfig config = new FacetsConfig(taxoWriter);
config.setRequireDimCount("a", true);
RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
- DocumentBuilder builder = new DocumentBuilder(taxoWriter, config);
Document doc = new Document();
doc.add(new IntAssociationFacetField(14, "a", "x"));
try {
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
fail("did not hit expected exception");
} catch (IllegalArgumentException exc) {
// expected
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 a5fdda623b5..39fb0b7f969 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
@@ -26,12 +26,15 @@ 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.taxonomy.TaxonomyReader;
import org.apache.lucene.facet.taxonomy.TaxonomyWriter;
import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyReader;
import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyWriter;
import org.apache.lucene.facet.util.PrintTaxonomyStats;
+import org.apache.lucene.index.DirectoryReader;
+import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.RandomIndexWriter;
import org.apache.lucene.search.IndexSearcher;
@@ -53,36 +56,35 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
// main index:
DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir, IndexWriterConfig.OpenMode.CREATE);
- FacetsConfig config = new FacetsConfig();
+ FacetsConfig config = new FacetsConfig(taxoWriter);
config.setHierarchical("Publish Date", true);
RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
- DocumentBuilder builder = new DocumentBuilder(taxoWriter, config);
Document doc = new Document();
doc.add(new FacetField("Author", "Bob"));
doc.add(new FacetField("Publish Date", "2010", "10", "15"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
doc = new Document();
doc.add(new FacetField("Author", "Lisa"));
doc.add(new FacetField("Publish Date", "2010", "10", "20"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
doc = new Document();
doc.add(new FacetField("Author", "Lisa"));
doc.add(new FacetField("Publish Date", "2012", "1", "1"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
doc = new Document();
doc.add(new FacetField("Author", "Susan"));
doc.add(new FacetField("Publish Date", "2012", "1", "7"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
doc = new Document();
doc.add(new FacetField("Author", "Frank"));
doc.add(new FacetField("Publish Date", "1999", "5", "5"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
// NRT open
IndexSearcher searcher = newSearcher(writer.getReader());
@@ -139,11 +141,11 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir, IndexWriterConfig.OpenMode.CREATE);
RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
- DocumentBuilder builder = new DocumentBuilder(taxoWriter, new FacetsConfig());
+ FacetsConfig config = new FacetsConfig(taxoWriter);
Document doc = new Document();
doc.add(new FacetField("a", "foo1"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
if (random().nextBoolean()) {
writer.commit();
@@ -152,7 +154,7 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
doc = new Document();
doc.add(new FacetField("a", "foo2"));
doc.add(new FacetField("b", "bar1"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
if (random().nextBoolean()) {
writer.commit();
@@ -162,7 +164,7 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
doc.add(new FacetField("a", "foo3"));
doc.add(new FacetField("b", "bar2"));
doc.add(new FacetField("c", "baz1"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
// NRT open
IndexSearcher searcher = newSearcher(writer.getReader());
@@ -194,14 +196,13 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
// main index:
DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir, IndexWriterConfig.OpenMode.CREATE);
- FacetsConfig config = new FacetsConfig();
+ FacetsConfig config = new FacetsConfig(taxoWriter);
config.setIndexFieldName("a", "$facets2");
RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
- DocumentBuilder builder = new DocumentBuilder(taxoWriter, config);
Document doc = new Document();
doc.add(new FacetField("a", "foo1"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
// NRT open
IndexSearcher searcher = newSearcher(writer.getReader());
@@ -264,12 +265,12 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
});
TaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir, IndexWriterConfig.OpenMode.CREATE);
RandomIndexWriter writer = new RandomIndexWriter(random(), dir, iwc);
- DocumentBuilder builder = new DocumentBuilder(taxoWriter, new FacetsConfig());
+ FacetsConfig config = new FacetsConfig(taxoWriter);
Document doc = new Document();
doc.add(newTextField("field", "text", Field.Store.NO));
doc.add(new FacetField("a", "path"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
IOUtils.close(writer, taxoWriter, dir, taxoDir);
}
@@ -277,17 +278,16 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
Directory dir = newDirectory();
Directory taxoDir = newDirectory();
DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir, IndexWriterConfig.OpenMode.CREATE);
- FacetsConfig config = new FacetsConfig();
+ FacetsConfig config = new FacetsConfig(taxoWriter);
config.setHierarchical("a", true);
config.setMultiValued("a", true);
RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
- DocumentBuilder builder = new DocumentBuilder(taxoWriter, config);
Document doc = new Document();
doc.add(newTextField("field", "text", Field.Store.NO));
doc.add(new FacetField("a", "path", "x"));
doc.add(new FacetField("a", "path", "y"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
// NRT open
IndexSearcher searcher = newSearcher(writer.getReader());
@@ -317,15 +317,14 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir, IndexWriterConfig.OpenMode.CREATE);
- FacetsConfig config = new FacetsConfig();
+ FacetsConfig config = new FacetsConfig(taxoWriter);
config.setMultiValued("dim", true);
- DocumentBuilder builder = new DocumentBuilder(taxoWriter, config);
Document doc = new Document();
doc.add(newTextField("field", "text", Field.Store.NO));
doc.add(new FacetField("dim", "test\u001Fone"));
doc.add(new FacetField("dim", "test\u001Etwo"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
// NRT open
IndexSearcher searcher = newSearcher(writer.getReader());
@@ -351,14 +350,13 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir, IndexWriterConfig.OpenMode.CREATE);
- FacetsConfig config = new FacetsConfig();
+ FacetsConfig config = new FacetsConfig(taxoWriter);
config.setMultiValued("dim2", true);
config.setMultiValued("dim3", true);
config.setHierarchical("dim3", true);
config.setRequireDimCount("dim", true);
config.setRequireDimCount("dim2", true);
config.setRequireDimCount("dim3", true);
- DocumentBuilder builder = new DocumentBuilder(taxoWriter, config);
Document doc = new Document();
doc.add(newTextField("field", "text", Field.Store.NO));
@@ -367,7 +365,7 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
doc.add(new FacetField("dim2", "b"));
doc.add(new FacetField("dim3", "a", "b"));
doc.add(new FacetField("dim3", "a", "c"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
// NRT open
IndexSearcher searcher = newSearcher(writer.getReader());
@@ -395,9 +393,8 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
RandomIndexWriter writer = new RandomIndexWriter(random(), dir, iwc);
DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir, IndexWriterConfig.OpenMode.CREATE);
- FacetsConfig config = new FacetsConfig();
+ FacetsConfig config = new FacetsConfig(taxoWriter);
config.setMultiValued("dim", true);
- DocumentBuilder builder = new DocumentBuilder(taxoWriter, config);
int numLabels = _TestUtil.nextInt(random(), 40000, 100000);
@@ -406,7 +403,7 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
for (int i = 0; i < numLabels; i++) {
doc.add(new FacetField("dim", "" + i));
}
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
// NRT open
IndexSearcher searcher = newSearcher(writer.getReader());
@@ -443,14 +440,13 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
Directory taxoDir = newDirectory();
TaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir, IndexWriterConfig.OpenMode.CREATE);
RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
- FacetsConfig config = new FacetsConfig();
- DocumentBuilder builder = new DocumentBuilder(taxoWriter, config);
+ FacetsConfig config = new FacetsConfig(taxoWriter);
Document doc = new Document();
doc.add(newTextField("field", "text", Field.Store.NO));
doc.add(new FacetField("a", "path", "other"));
try {
- builder.build(doc);
+ config.build(doc);
fail("did not hit expected exception");
} catch (IllegalArgumentException iae) {
// expected
@@ -465,19 +461,129 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
Directory taxoDir = newDirectory();
TaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir, IndexWriterConfig.OpenMode.CREATE);
RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
- FacetsConfig config = new FacetsConfig();
- DocumentBuilder builder = new DocumentBuilder(taxoWriter, config);
+ FacetsConfig config = new FacetsConfig(taxoWriter);
Document doc = new Document();
doc.add(newTextField("field", "text", Field.Store.NO));
doc.add(new FacetField("a", "path"));
doc.add(new FacetField("a", "path2"));
try {
- builder.build(doc);
+ config.build(doc);
fail("did not hit expected exception");
} catch (IllegalArgumentException iae) {
// expected
}
IOUtils.close(writer, taxoWriter, dir, taxoDir);
}
+
+ public void testSeparateIndexedFields() throws Exception {
+ Directory indexDir = newDirectory();
+ Directory taxoDir = newDirectory();
+
+ DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir);
+ IndexWriter iw = new IndexWriter(indexDir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
+ FacetsConfig config = new FacetsConfig(taxoWriter);
+ config.setIndexFieldName("b", "$b");
+
+ for(int i = atLeast(30); i > 0; --i) {
+ Document doc = new Document();
+ doc.add(new StringField("f", "v", Field.Store.NO));
+ doc.add(new FacetField("a", "1"));
+ doc.add(new FacetField("b", "1"));
+ iw.addDocument(config.build(doc));
+ }
+
+ DirectoryReader r = DirectoryReader.open(iw, true);
+ DirectoryTaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoWriter);
+
+ SimpleFacetsCollector sfc = new SimpleFacetsCollector();
+ newSearcher(r).search(new MatchAllDocsQuery(), sfc);
+ Facets facets1 = getTaxonomyFacetCounts(taxoReader, config, sfc);
+ Facets facets2 = getTaxonomyFacetCounts(taxoReader, config, sfc, "$b");
+ assertEquals(r.maxDoc(), facets1.getTopChildren(10, "a").value.intValue());
+ assertEquals(r.maxDoc(), facets2.getTopChildren(10, "b").value.intValue());
+ IOUtils.close(taxoWriter, iw, taxoReader, taxoDir, r, indexDir);
+ }
+
+ public void testCountRoot() throws Exception {
+ // LUCENE-4882: FacetsAccumulator threw NPE if a FacetRequest was defined on CP.EMPTY
+ Directory indexDir = newDirectory();
+ Directory taxoDir = newDirectory();
+
+ DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir);
+ IndexWriter iw = new IndexWriter(indexDir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
+ FacetsConfig config = new FacetsConfig(taxoWriter);
+ for(int i = atLeast(30); i > 0; --i) {
+ Document doc = new Document();
+ doc.add(new FacetField("a", "1"));
+ doc.add(new FacetField("b", "1"));
+ iw.addDocument(config.build(doc));
+ }
+
+ DirectoryReader r = DirectoryReader.open(iw, true);
+ DirectoryTaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoWriter);
+
+ SimpleFacetsCollector sfc = new SimpleFacetsCollector();
+ newSearcher(r).search(new MatchAllDocsQuery(), sfc);
+ Facets facets = getTaxonomyFacetCounts(taxoReader, config, sfc);
+ for (SimpleFacetResult result : facets.getAllDims(10)) {
+ assertEquals(r.numDocs(), result.value.intValue());
+ }
+
+ IOUtils.close(taxoWriter, iw, taxoReader, taxoDir, r, indexDir);
+ }
+
+ public void testGetFacetResultsTwice() throws Exception {
+ // LUCENE-4893: counts were multiplied as many times as getFacetResults was called.
+ Directory indexDir = newDirectory();
+ Directory taxoDir = newDirectory();
+
+ DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir);
+ IndexWriter iw = new IndexWriter(indexDir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
+ FacetsConfig config = new FacetsConfig(taxoWriter);
+
+ Document doc = new Document();
+ doc.add(new FacetField("a", "1"));
+ doc.add(new FacetField("b", "1"));
+ iw.addDocument(config.build(doc));
+
+ DirectoryReader r = DirectoryReader.open(iw, true);
+ DirectoryTaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoWriter);
+
+ final SimpleFacetsCollector sfc = new SimpleFacetsCollector();
+ newSearcher(r).search(new MatchAllDocsQuery(), sfc);
+
+ Facets facets = getTaxonomyFacetCounts(taxoReader, config, sfc);
+ List<SimpleFacetResult> res1 = facets.getAllDims(10);
+ List<SimpleFacetResult> res2 = facets.getAllDims(10);
+ assertEquals("calling getFacetResults twice should return the .equals()=true result", res1, res2);
+
+ IOUtils.close(taxoWriter, iw, taxoReader, taxoDir, r, indexDir);
+ }
+
+ public void testChildCount() throws Exception {
+ // LUCENE-4885: FacetResult.numValidDescendants was not set properly by FacetsAccumulator
+ Directory indexDir = newDirectory();
+ Directory taxoDir = newDirectory();
+
+ DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir);
+ IndexWriter iw = new IndexWriter(indexDir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
+ FacetsConfig config = new FacetsConfig(taxoWriter);
+ for (int i = 0; i < 10; i++) {
+ Document doc = new Document();
+ doc.add(new FacetField("a", Integer.toString(i)));
+ iw.addDocument(config.build(doc));
+ }
+
+ DirectoryReader r = DirectoryReader.open(iw, true);
+ DirectoryTaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoWriter);
+
+ SimpleFacetsCollector sfc = new SimpleFacetsCollector();
+ newSearcher(r).search(new MatchAllDocsQuery(), sfc);
+ Facets facets = getTaxonomyFacetCounts(taxoReader, config, sfc);
+
+ assertEquals(10, facets.getTopChildren(2, "a").childCount);
+
+ IOUtils.close(taxoWriter, iw, taxoReader, taxoDir, r, indexDir);
+ }
}
diff --git a/lucene/facet/src/test/org/apache/lucene/facet/simple/TestTaxonomyFacetSumValueSource.java b/lucene/facet/src/test/org/apache/lucene/facet/simple/TestTaxonomyFacetSumValueSource.java
index 3a1b8619971..73e6590e6c0 100644
--- a/lucene/facet/src/test/org/apache/lucene/facet/simple/TestTaxonomyFacetSumValueSource.java
+++ b/lucene/facet/src/test/org/apache/lucene/facet/simple/TestTaxonomyFacetSumValueSource.java
@@ -24,12 +24,15 @@ import java.util.ArrayList;
import java.util.Collections;
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.IntField;
+import org.apache.lucene.document.NumericDocValuesField;
+import org.apache.lucene.document.StringField;
import org.apache.lucene.facet.FacetTestCase;
import org.apache.lucene.facet.taxonomy.FacetLabel;
import org.apache.lucene.facet.taxonomy.TaxonomyReader;
@@ -37,13 +40,26 @@ import org.apache.lucene.facet.taxonomy.TaxonomyWriter;
import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyReader;
import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyWriter;
import org.apache.lucene.facet.util.PrintTaxonomyStats;
+import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.RandomIndexWriter;
+import org.apache.lucene.queries.function.FunctionQuery;
+import org.apache.lucene.queries.function.FunctionValues;
+import org.apache.lucene.queries.function.ValueSource;
+import org.apache.lucene.queries.function.docvalues.DoubleDocValues;
import org.apache.lucene.queries.function.valuesource.IntFieldSource;
+import org.apache.lucene.queries.function.valuesource.LongFieldSource;
+import org.apache.lucene.queries.function.valuesource.QueryValueSource;
+import org.apache.lucene.search.ConstantScoreQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
+import org.apache.lucene.search.MultiCollector;
+import org.apache.lucene.search.Query;
+import org.apache.lucene.search.Scorer;
+import org.apache.lucene.search.TopDocs;
+import org.apache.lucene.search.TopScoreDocCollector;
import org.apache.lucene.search.similarities.DefaultSimilarity;
import org.apache.lucene.search.similarities.PerFieldSimilarityWrapper;
import org.apache.lucene.search.similarities.Similarity;
@@ -64,34 +80,34 @@ public class TestTaxonomyFacetSumValueSource extends FacetTestCase {
DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir, IndexWriterConfig.OpenMode.CREATE);
RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
- DocumentBuilder builder = new DocumentBuilder(taxoWriter, new FacetsConfig());
+ FacetsConfig config = new FacetsConfig(taxoWriter);
// Reused across documents, to add the necessary facet
// fields:
Document doc = new Document();
doc.add(new IntField("num", 10, Field.Store.NO));
doc.add(new FacetField("Author", "Bob"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
doc = new Document();
doc.add(new IntField("num", 20, Field.Store.NO));
doc.add(new FacetField("Author", "Lisa"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
doc = new Document();
doc.add(new IntField("num", 30, Field.Store.NO));
doc.add(new FacetField("Author", "Lisa"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
doc = new Document();
doc.add(new IntField("num", 40, Field.Store.NO));
doc.add(new FacetField("Author", "Susan"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
doc = new Document();
doc.add(new IntField("num", 45, Field.Store.NO));
doc.add(new FacetField("Author", "Frank"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
// NRT open
IndexSearcher searcher = newSearcher(writer.getReader());
@@ -131,12 +147,12 @@ public class TestTaxonomyFacetSumValueSource extends FacetTestCase {
DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir, IndexWriterConfig.OpenMode.CREATE);
RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
- DocumentBuilder builder = new DocumentBuilder(taxoWriter, new FacetsConfig());
+ FacetsConfig config = new FacetsConfig(taxoWriter);
Document doc = new Document();
doc.add(new IntField("num", 10, Field.Store.NO));
doc.add(new FacetField("a", "foo1"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
if (random().nextBoolean()) {
writer.commit();
@@ -146,7 +162,7 @@ public class TestTaxonomyFacetSumValueSource extends FacetTestCase {
doc.add(new IntField("num", 20, Field.Store.NO));
doc.add(new FacetField("a", "foo2"));
doc.add(new FacetField("b", "bar1"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
if (random().nextBoolean()) {
writer.commit();
@@ -157,7 +173,7 @@ public class TestTaxonomyFacetSumValueSource extends FacetTestCase {
doc.add(new FacetField("a", "foo3"));
doc.add(new FacetField("b", "bar2"));
doc.add(new FacetField("c", "baz1"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
// NRT open
IndexSearcher searcher = newSearcher(writer.getReader());
@@ -180,10 +196,7 @@ public class TestTaxonomyFacetSumValueSource extends FacetTestCase {
assertEquals("b (50.0)\n bar2 (30.0)\n bar1 (20.0)\n", results.get(1).toString());
assertEquals("c (30.0)\n baz1 (30.0)\n", results.get(2).toString());
- searcher.getIndexReader().close();
- taxoReader.close();
- taxoDir.close();
- dir.close();
+ IOUtils.close(searcher.getIndexReader(), taxoReader, dir, taxoDir);
}
public void testWrongIndexFieldName() throws Exception {
@@ -195,16 +208,15 @@ public class TestTaxonomyFacetSumValueSource extends FacetTestCase {
// main index:
DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir, IndexWriterConfig.OpenMode.CREATE);
- FacetsConfig config = new FacetsConfig();
+ FacetsConfig config = new FacetsConfig(taxoWriter);
config.setIndexFieldName("a", "$facets2");
RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
- DocumentBuilder builder = new DocumentBuilder(taxoWriter, config);
Document doc = new Document();
doc.add(new IntField("num", 10, Field.Store.NO));
doc.add(new FacetField("a", "foo1"));
- writer.addDocument(builder.build(doc));
+ writer.addDocument(config.build(doc));
// NRT open
IndexSearcher searcher = newSearcher(writer.getReader());
@@ -237,10 +249,184 @@ public class TestTaxonomyFacetSumValueSource extends FacetTestCase {
// expected
}
- searcher.getIndexReader().close();
- taxoReader.close();
- taxoDir.close();
- dir.close();
+ IOUtils.close(searcher.getIndexReader(), taxoReader, dir, taxoDir);
+ }
+
+ public void testSumScoreAggregator() throws Exception {
+ Directory indexDir = newDirectory();
+ Directory taxoDir = newDirectory();
+
+ DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir);
+ IndexWriter iw = new IndexWriter(indexDir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
+
+ FacetsConfig config = new FacetsConfig(taxoWriter);
+
+ for(int i = atLeast(30); i > 0; --i) {
+ Document doc = new Document();
+ if (random().nextBoolean()) { // don't match all documents
+ doc.add(new StringField("f", "v", Field.Store.NO));
+ }
+ doc.add(new FacetField("dim", "a"));
+ iw.addDocument(config.build(doc));
+ }
+
+ DirectoryReader r = DirectoryReader.open(iw, true);
+ DirectoryTaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoWriter);
+
+ SimpleFacetsCollector fc = new SimpleFacetsCollector(true);
+ TopScoreDocCollector topDocs = TopScoreDocCollector.create(10, false);
+ ConstantScoreQuery csq = new ConstantScoreQuery(new MatchAllDocsQuery());
+ csq.setBoost(2.0f);
+
+ newSearcher(r).search(csq, MultiCollector.wrap(fc, topDocs));
+
+ Facets facets = new TaxonomyFacetSumValueSource(taxoReader, config, fc, new TaxonomyFacetSumValueSource.ScoreValueSource());
+
+ TopDocs td = topDocs.topDocs();
+ int expected = (int) (td.getMaxScore() * td.totalHits);
+ assertEquals(expected, facets.getSpecificValue("dim", "a").intValue());
+
+ IOUtils.close(iw, taxoWriter, taxoReader, taxoDir, r, indexDir);
+ }
+
+ public void testNoScore() throws Exception {
+ Directory indexDir = newDirectory();
+ Directory taxoDir = newDirectory();
+
+ DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir);
+ IndexWriter iw = new IndexWriter(indexDir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
+ FacetsConfig config = new FacetsConfig(taxoWriter);
+ for (int i = 0; i < 4; i++) {
+ Document doc = new Document();
+ doc.add(new NumericDocValuesField("price", (i+1)));
+ doc.add(new FacetField("a", Integer.toString(i % 2)));
+ iw.addDocument(config.build(doc));
+ }
+
+ DirectoryReader r = DirectoryReader.open(iw, true);
+ DirectoryTaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoWriter);
+
+ SimpleFacetsCollector sfc = new SimpleFacetsCollector();
+ newSearcher(r).search(new MatchAllDocsQuery(), sfc);
+ Facets facets = new TaxonomyFacetSumValueSource(taxoReader, config, sfc, new LongFieldSource("price"));
+ assertEquals("a (10.0)\n 1 (6.0)\n 0 (4.0)\n", facets.getTopChildren(10, "a").toString());
+
+ IOUtils.close(taxoWriter, iw, taxoReader, taxoDir, r, indexDir);
+ }
+
+ public void testWithScore() throws Exception {
+ Directory indexDir = newDirectory();
+ Directory taxoDir = newDirectory();
+
+ DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir);
+ IndexWriter iw = new IndexWriter(indexDir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
+
+ FacetsConfig config = new FacetsConfig(taxoWriter);
+ for (int i = 0; i < 4; i++) {
+ Document doc = new Document();
+ doc.add(new NumericDocValuesField("price", (i+1)));
+ doc.add(new FacetField("a", Integer.toString(i % 2)));
+ iw.addDocument(config.build(doc));
+ }
+
+ DirectoryReader r = DirectoryReader.open(iw, true);
+ DirectoryTaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoWriter);
+
+ ValueSource valueSource = new ValueSource() {
+ @Override
+ public FunctionValues getValues(@SuppressWarnings("rawtypes") Map context, AtomicReaderContext readerContext) throws IOException {
+ final Scorer scorer = (Scorer) context.get("scorer");
+ assert scorer != null;
+ return new DoubleDocValues(this) {
+ @Override
+ public double doubleVal(int document) {
+ try {
+ return scorer.score();
+ } catch (IOException exception) {
+ throw new RuntimeException(exception);
+ }
+ }
+ };
+ }
+
+ @Override public boolean equals(Object o) { return o == this; }
+ @Override public int hashCode() { return System.identityHashCode(this); }
+ @Override public String description() { return "score()"; }
+ };
+
+ SimpleFacetsCollector sfc = new SimpleFacetsCollector(true);
+ TopScoreDocCollector tsdc = TopScoreDocCollector.create(10, true);
+ // score documents by their 'price' field - makes asserting the correct counts for the categories easier
+ Query q = new FunctionQuery(new LongFieldSource("price"));
+ newSearcher(r).search(q, MultiCollector.wrap(tsdc, sfc));
+ Facets facets = new TaxonomyFacetSumValueSource(taxoReader, config, sfc, valueSource);
+
+ assertEquals("a (10.0)\n 1 (6.0)\n 0 (4.0)\n", facets.getTopChildren(10, "a").toString());
+
+ IOUtils.close(taxoWriter, iw, taxoReader, taxoDir, r, indexDir);
+ }
+
+ public void testRollupValues() throws Exception {
+ Directory indexDir = newDirectory();
+ Directory taxoDir = newDirectory();
+
+ DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir);
+ IndexWriter iw = new IndexWriter(indexDir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
+ FacetsConfig config = new FacetsConfig(taxoWriter);
+ config.setHierarchical("a", true);
+ //config.setRequireDimCount("a", true);
+
+ for (int i = 0; i < 4; i++) {
+ Document doc = new Document();
+ doc.add(new NumericDocValuesField("price", (i+1)));
+ doc.add(new FacetField("a", Integer.toString(i % 2), "1"));
+ iw.addDocument(config.build(doc));
+ }
+
+ DirectoryReader r = DirectoryReader.open(iw, true);
+ DirectoryTaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoWriter);
+
+ ValueSource valueSource = new LongFieldSource("price");
+ SimpleFacetsCollector sfc = new SimpleFacetsCollector();
+ newSearcher(r).search(new MatchAllDocsQuery(), sfc);
+ Facets facets = new TaxonomyFacetSumValueSource(taxoReader, config, sfc, valueSource);
+
+ assertEquals("a (10.0)\n 1 (6.0)\n 0 (4.0)\n", facets.getTopChildren(10, "a").toString());
+
+ IOUtils.close(taxoWriter, iw, taxoReader, taxoDir, r, indexDir);
+ }
+
+ public void testCountAndSumScore() throws Exception {
+ Directory indexDir = newDirectory();
+ Directory taxoDir = newDirectory();
+
+ DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir);
+ IndexWriter iw = new IndexWriter(indexDir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
+ FacetsConfig config = new FacetsConfig(taxoWriter);
+ config.setIndexFieldName("b", "$b");
+
+ for(int i = atLeast(30); i > 0; --i) {
+ Document doc = new Document();
+ doc.add(new StringField("f", "v", Field.Store.NO));
+ doc.add(new FacetField("a", "1"));
+ doc.add(new FacetField("b", "1"));
+ iw.addDocument(config.build(doc));
+ }
+
+ DirectoryReader r = DirectoryReader.open(iw, true);
+ DirectoryTaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoWriter);
+
+ SimpleFacetsCollector sfc = new SimpleFacetsCollector(true);
+ TopScoreDocCollector topDocs = TopScoreDocCollector.create(10, false);
+ newSearcher(r).search(new MatchAllDocsQuery(), MultiCollector.wrap(sfc, topDocs));
+
+ Facets facets1 = getTaxonomyFacetCounts(taxoReader, config, sfc);
+ Facets facets2 = new TaxonomyFacetSumValueSource(new DocValuesOrdinalsReader("$b"), taxoReader, config, sfc, new TaxonomyFacetSumValueSource.ScoreValueSource());
+
+ assertEquals(r.maxDoc(), facets1.getTopChildren(10, "a").value.intValue());
+ double expected = topDocs.topDocs().getMaxScore() * r.numDocs();
+ assertEquals(r.maxDoc(), facets2.getTopChildren(10, "b").value.doubleValue(), 1E-10);
+ IOUtils.close(taxoWriter, iw, taxoReader, taxoDir, r, indexDir);
}
// nocommit in the sparse case test that we are really
diff --git a/lucene/facet/src/test/org/apache/lucene/facet/sortedset/TestSortedSetDocValuesFacets.java b/lucene/facet/src/test/org/apache/lucene/facet/sortedset/TestSortedSetDocValuesFacets.java
deleted file mode 100644
index db62bab74e7..00000000000
--- a/lucene/facet/src/test/org/apache/lucene/facet/sortedset/TestSortedSetDocValuesFacets.java
+++ /dev/null
@@ -1,196 +0,0 @@
-package org.apache.lucene.facet.sortedset;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-import org.apache.lucene.document.Document;
-import org.apache.lucene.facet.FacetTestCase;
-import org.apache.lucene.facet.FacetTestUtils;
-import org.apache.lucene.facet.params.CategoryListParams;
-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.FacetRequest;
-import org.apache.lucene.facet.search.FacetResult;
-import org.apache.lucene.facet.search.FacetsCollector;
-import org.apache.lucene.facet.taxonomy.FacetLabel;
-import org.apache.lucene.index.IndexReader;
-import org.apache.lucene.index.RandomIndexWriter;
-import org.apache.lucene.search.IndexSearcher;
-import org.apache.lucene.search.MatchAllDocsQuery;
-import org.apache.lucene.search.TopDocs;
-import org.apache.lucene.store.Directory;
-
-public class TestSortedSetDocValuesFacets extends FacetTestCase {
-
- // NOTE: TestDrillSideways.testRandom also sometimes
- // randomly uses SortedSetDV
-
- public void testSortedSetDocValuesAccumulator() throws Exception {
- assumeTrue("Test requires SortedSetDV support", defaultCodecSupportsSortedSet());
- Directory dir = newDirectory();
- RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
-
- // Use a custom delim char to make sure the impls
- // respect it:
- final char delim = ':';
- FacetIndexingParams fip = new FacetIndexingParams() {
- @Override
- public char getFacetDelimChar() {
- return delim;
- }
- };
-
- SortedSetDocValuesFacetFields dvFields = new SortedSetDocValuesFacetFields(fip);
-
- Document doc = new Document();
- // Mixup order we add these paths, to verify tie-break
- // order is by label (unicode sort) and has nothing to
- // do w/ order we added them:
- List<FacetLabel> paths = new ArrayList<FacetLabel>();
- paths.add(new FacetLabel("a", "foo"));
- paths.add(new FacetLabel("a", "bar"));
- paths.add(new FacetLabel("a", "zoo"));
- Collections.shuffle(paths, random());
-
- paths.add(new FacetLabel("b", "baz"));
- paths.add(new FacetLabel("b" + FacetIndexingParams.DEFAULT_FACET_DELIM_CHAR, "bazfoo"));
-
- dvFields.addFields(doc, paths);
-
- writer.addDocument(doc);
- if (random().nextBoolean()) {
- writer.commit();
- }
-
- doc = new Document();
- dvFields.addFields(doc, Collections.singletonList(new FacetLabel("a", "foo")));
- writer.addDocument(doc);
-
- // NRT open
- IndexSearcher searcher = newSearcher(writer.getReader());
- writer.close();
-
- List<FacetRequest> requests = new ArrayList<FacetRequest>();
- requests.add(new CountFacetRequest(new FacetLabel("a"), 10));
- requests.add(new CountFacetRequest(new FacetLabel("b"), 10));
- requests.add(new CountFacetRequest(new FacetLabel("b" + FacetIndexingParams.DEFAULT_FACET_DELIM_CHAR), 10));
-
- final boolean doDimCount = random().nextBoolean();
-
- CategoryListParams clp = new CategoryListParams() {
- @Override
- public OrdinalPolicy getOrdinalPolicy(String dimension) {
- return doDimCount ? OrdinalPolicy.NO_PARENTS : OrdinalPolicy.ALL_BUT_DIMENSION;
- }
- };
-
- FacetSearchParams fsp = new FacetSearchParams(new FacetIndexingParams(clp), requests);
-
- // Per-top-reader state:
- SortedSetDocValuesReaderState state = new SortedSetDocValuesReaderState(fip, searcher.getIndexReader());
-
- //SortedSetDocValuesCollector c = new SortedSetDocValuesCollector(state);
- //SortedSetDocValuesCollectorMergeBySeg c = new SortedSetDocValuesCollectorMergeBySeg(state);
-
- FacetsCollector c = FacetsCollector.create(new SortedSetDocValuesAccumulator(state, fsp));
-
- searcher.search(new MatchAllDocsQuery(), c);
-
- //List<FacetResult> results = c.getFacetResults(requests);
- List<FacetResult> results = c.getFacetResults();
-
- assertEquals(3, results.size());
-
- int dimCount = doDimCount ? 4 : 0;
- assertEquals("a (" + dimCount + ")\n foo (2)\n bar (1)\n zoo (1)\n", FacetTestUtils.toSimpleString(results.get(0)));
-
- dimCount = doDimCount ? 1 : 0;
- assertEquals("b (" + dimCount + ")\n baz (1)\n", FacetTestUtils.toSimpleString(results.get(1)));
-
- dimCount = doDimCount ? 1 : 0;
- assertEquals("b" + FacetIndexingParams.DEFAULT_FACET_DELIM_CHAR + " (" + dimCount + ")\n bazfoo (1)\n", FacetTestUtils.toSimpleString(results.get(2)));
-
- // DrillDown:
-
- DrillDownQuery q = new DrillDownQuery(fip);
- q.add(new FacetLabel("a", "foo"));
- q.add(new FacetLabel("b", "baz"));
- TopDocs hits = searcher.search(q, 1);
- assertEquals(1, hits.totalHits);
-
- q = new DrillDownQuery(fip);
- q.add(new FacetLabel("a"));
- hits = searcher.search(q, 1);
- assertEquals(2, hits.totalHits);
-
- searcher.getIndexReader().close();
- dir.close();
- }
-
- // LUCENE-5090
- public void testStaleState() throws Exception {
- assumeTrue("Test requires SortedSetDV support", defaultCodecSupportsSortedSet());
- Directory dir = newDirectory();
- RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
-
- SortedSetDocValuesFacetFields dvFields = new SortedSetDocValuesFacetFields();
-
- Document doc = new Document();
- dvFields.addFields(doc, Collections.singletonList(new FacetLabel("a", "foo")));
- writer.addDocument(doc);
-
- IndexReader r = writer.getReader();
- SortedSetDocValuesReaderState state = new SortedSetDocValuesReaderState(r);
-
- doc = new Document();
- dvFields.addFields(doc, Collections.singletonList(new FacetLabel("a", "bar")));
- writer.addDocument(doc);
-
- doc = new Document();
- dvFields.addFields(doc, Collections.singletonList(new FacetLabel("a", "baz")));
- writer.addDocument(doc);
-
- IndexSearcher searcher = newSearcher(writer.getReader());
-
- List<FacetRequest> requests = new ArrayList<FacetRequest>();
- requests.add(new CountFacetRequest(new FacetLabel("a"), 10));
-
- FacetSearchParams fsp = new FacetSearchParams(requests);
-
- FacetsCollector c = FacetsCollector.create(new SortedSetDocValuesAccumulator(state, fsp));
-
- searcher.search(new MatchAllDocsQuery(), c);
-
- try {
- c.getFacetResults();
- fail("did not hit expected exception");
- } catch (IllegalStateException ise) {
- // expected
- }
-
- r.close();
- writer.close();
- searcher.getIndexReader().close();
- dir.close();
- }
-}