Apache Lucene open-source search software
LUCENE-5339: remove old sorted set
Michael McCandless92b1e230715d
diff --git a/lucene/facet/src/java/org/apache/lucene/facet/search/DrillSideways.java b/lucene/facet/src/java/org/apache/lucene/facet/search/DrillSideways.javadeleted file mode 100644index 661164f4025..00000000000--- a/lucene/facet/src/java/org/apache/lucene/facet/search/DrillSideways.java+++ /dev/null@@ -1,560 +0,0 @@-package org.apache.lucene.facet.search;--/*- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import java.io.IOException;-import java.util.ArrayList;-import java.util.HashSet;-import java.util.LinkedHashMap;-import java.util.List;-import java.util.Map;-import java.util.Set;--import org.apache.lucene.facet.index.FacetFields;-import org.apache.lucene.facet.params.FacetSearchParams;-import org.apache.lucene.facet.sortedset.SortedSetDocValuesFacetFields;-import org.apache.lucene.facet.sortedset.SortedSetDocValuesReaderState;-import org.apache.lucene.facet.taxonomy.TaxonomyReader;-import org.apache.lucene.index.IndexReader;-import org.apache.lucene.index.Term;-import org.apache.lucene.search.BooleanClause;-import org.apache.lucene.search.BooleanQuery;-import org.apache.lucene.search.Collector;-import org.apache.lucene.search.ConstantScoreQuery;-import org.apache.lucene.search.FieldDoc;-import org.apache.lucene.search.Filter;-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.ScoreDoc;-import org.apache.lucene.search.Sort;-import org.apache.lucene.search.TermQuery;-import org.apache.lucene.search.TopDocs;-import org.apache.lucene.search.TopFieldCollector;-import org.apache.lucene.search.TopScoreDocCollector;-import org.apache.lucene.search.Weight;--/**- * Computes drill down and sideways counts for the provided- * {@link DrillDownQuery}. Drill sideways counts include- * alternative values/aggregates for the drill-down- * dimensions so that a dimension does not disappear after- * the user drills down into it.- *- * <p> Use one of the static search- * methods to do the search, and then get the hits and facet- * results from the returned {@link DrillSidewaysResult}.- *- * <p><b>NOTE</b>: this allocates one {@link- * FacetsCollector} for each drill-down, plus one. If your- * index has high number of facet labels then this will- * multiply your memory usage.- *- * @lucene.experimental- */--public class DrillSideways {-- protected final IndexSearcher searcher;- protected final TaxonomyReader taxoReader;- protected final SortedSetDocValuesReaderState state;-- /**- * Create a new {@code DrillSideways} instance, assuming the categories were- * indexed with {@link FacetFields}.- */- public DrillSideways(IndexSearcher searcher, TaxonomyReader taxoReader) {- this.searcher = searcher;- this.taxoReader = taxoReader;- this.state = null;- }-- /**- * Create a new {@code DrillSideways} instance, assuming the categories were- * indexed with {@link SortedSetDocValuesFacetFields}.- */- public DrillSideways(IndexSearcher searcher, SortedSetDocValuesReaderState state) {- this.searcher = searcher;- this.taxoReader = null;- this.state = state;- }-- /** Moves any drill-downs that don't have a corresponding- * facet request into the baseQuery. This is unusual,- * yet allowed, because typically the added drill-downs are because- * the user has clicked on previously presented facets,- * and those same facets would be computed this time- * around. */- private static DrillDownQuery moveDrillDownOnlyClauses(DrillDownQuery in, FacetSearchParams fsp) {- Set<String> facetDims = new HashSet<String>();- for(FacetRequest fr : fsp.facetRequests) {- if (fr.categoryPath.length == 0) {- throw new IllegalArgumentException("all FacetRequests must have CategoryPath with length > 0");- }- facetDims.add(fr.categoryPath.components[0]);- }-- BooleanClause[] clauses = in.getBooleanQuery().getClauses();- Map<String,Integer> drillDownDims = in.getDims();-- String[] dimsByIndex = new String[drillDownDims.size()];- for(Map.Entry<String,Integer> ent : drillDownDims.entrySet()) {- dimsByIndex[ent.getValue()] = ent.getKey();- }-- int startClause;- if (clauses.length == drillDownDims.size()) {- startClause = 0;- } else {- assert clauses.length == 1+drillDownDims.size();- startClause = 1;- }-- // Break out drill-down clauses that have no- // corresponding facet request and move them inside the- // baseQuery:- List<Query> nonFacetClauses = new ArrayList<Query>();- List<Query> facetClauses = new ArrayList<Query>();- Map<String,Integer> dimToIndex = new LinkedHashMap<String,Integer>();- for(int i=startClause;i<clauses.length;i++) {- Query q = clauses[i].getQuery();- String dim = dimsByIndex[i-startClause];- if (!facetDims.contains(dim)) {- nonFacetClauses.add(q);- } else {- facetClauses.add(q);- dimToIndex.put(dim, dimToIndex.size());- }- }-- if (!nonFacetClauses.isEmpty()) {- BooleanQuery newBaseQuery = new BooleanQuery(true);- if (startClause == 1) {- // Add original basaeQuery:- newBaseQuery.add(clauses[0].getQuery(), BooleanClause.Occur.MUST);- }- for(Query q : nonFacetClauses) {- newBaseQuery.add(q, BooleanClause.Occur.MUST);- }-- return new DrillDownQuery(fsp.indexingParams, newBaseQuery, facetClauses, dimToIndex);- } else {- // No change:- return in;- }- }-- /**- * Search, collecting hits with a {@link Collector}, and- * computing drill down and sideways counts.- */- @SuppressWarnings({"rawtypes","unchecked"})- public DrillSidewaysResult search(DrillDownQuery query,- Collector hitCollector, FacetSearchParams fsp) throws IOException {-- if (query.fip != fsp.indexingParams) {- throw new IllegalArgumentException("DrillDownQuery's FacetIndexingParams should match FacetSearchParams'");- }-- query = moveDrillDownOnlyClauses(query, fsp);-- Map<String,Integer> drillDownDims = query.getDims();-- if (drillDownDims.isEmpty()) {- // Just do ordinary search when there are no drill-downs:- FacetsCollector c = FacetsCollector.create(getDrillDownAccumulator(fsp));- searcher.search(query, MultiCollector.wrap(hitCollector, c));- return new DrillSidewaysResult(c.getFacetResults(), null);- }-- List<FacetRequest> ddRequests = new ArrayList<FacetRequest>();- for(FacetRequest fr : fsp.facetRequests) {- assert fr.categoryPath.length > 0;- if (!drillDownDims.containsKey(fr.categoryPath.components[0])) {- ddRequests.add(fr);- }- }- FacetSearchParams fsp2;- if (!ddRequests.isEmpty()) {- fsp2 = new FacetSearchParams(fsp.indexingParams, ddRequests);- } else {- fsp2 = null;- }-- BooleanQuery ddq = query.getBooleanQuery();- BooleanClause[] clauses = ddq.getClauses();-- Query baseQuery;- int startClause;- if (clauses.length == drillDownDims.size()) {- // TODO: we could optimize this pure-browse case by- // making a custom scorer instead:- baseQuery = new MatchAllDocsQuery();- startClause = 0;- } else {- assert clauses.length == 1+drillDownDims.size();- baseQuery = clauses[0].getQuery();- startClause = 1;- }-- FacetsCollector drillDownCollector = fsp2 == null ? null : FacetsCollector.create(getDrillDownAccumulator(fsp2));-- FacetsCollector[] drillSidewaysCollectors = new FacetsCollector[drillDownDims.size()];-- int idx = 0;- for(String dim : drillDownDims.keySet()) {- List<FacetRequest> requests = new ArrayList<FacetRequest>();- for(FacetRequest fr : fsp.facetRequests) {- assert fr.categoryPath.length > 0;- if (fr.categoryPath.components[0].equals(dim)) {- requests.add(fr);- }- }- // We already moved all drill-downs that didn't have a- // FacetRequest, in moveDrillDownOnlyClauses above:- assert !requests.isEmpty();- drillSidewaysCollectors[idx++] = FacetsCollector.create(getDrillSidewaysAccumulator(dim, new FacetSearchParams(fsp.indexingParams, requests)));- }-- boolean useCollectorMethod = scoreSubDocsAtOnce();-- Term[][] drillDownTerms = null;-- if (!useCollectorMethod) {- // Optimistic: assume subQueries of the DDQ are either- // TermQuery or BQ OR of TermQuery; if this is wrong- // then we detect it and fallback to the mome general- // but slower DrillSidewaysCollector:- drillDownTerms = new Term[clauses.length-startClause][];- for(int i=startClause;i<clauses.length;i++) {- Query q = clauses[i].getQuery();-- // DrillDownQuery always wraps each subQuery in- // ConstantScoreQuery:- assert q instanceof ConstantScoreQuery;-- q = ((ConstantScoreQuery) q).getQuery();-- if (q instanceof TermQuery) {- drillDownTerms[i-startClause] = new Term[] {((TermQuery) q).getTerm()};- } else if (q instanceof BooleanQuery) {- BooleanQuery q2 = (BooleanQuery) q;- BooleanClause[] clauses2 = q2.getClauses();- drillDownTerms[i-startClause] = new Term[clauses2.length];- for(int j=0;j<clauses2.length;j++) {- if (clauses2[j].getQuery() instanceof TermQuery) {- drillDownTerms[i-startClause][j] = ((TermQuery) clauses2[j].getQuery()).getTerm();- } else {- useCollectorMethod = true;- break;- }- }- } else {- useCollectorMethod = true;- }- }- }-- if (useCollectorMethod) {- // TODO: maybe we could push the "collector method"- // down into the optimized scorer to have a tighter- // integration ... and so TermQuery clauses could- // continue to run "optimized"- collectorMethod(query, baseQuery, startClause, hitCollector, drillDownCollector, drillSidewaysCollectors);- } else {- DrillSidewaysQuery dsq = new DrillSidewaysQuery(baseQuery, drillDownCollector, drillSidewaysCollectors, drillDownTerms);- searcher.search(dsq, hitCollector);- }-- int numDims = drillDownDims.size();- List<FacetResult>[] drillSidewaysResults = new List[numDims];- List<FacetResult> drillDownResults = null;-- List<FacetResult> mergedResults = new ArrayList<FacetResult>();- int[] requestUpto = new int[drillDownDims.size()];- int ddUpto = 0;- for(int i=0;i<fsp.facetRequests.size();i++) {- FacetRequest fr = fsp.facetRequests.get(i);- assert fr.categoryPath.length > 0;- Integer dimIndex = drillDownDims.get(fr.categoryPath.components[0]);- if (dimIndex == null) {- // Pure drill down dim (the current query didn't- // drill down on this dim):- if (drillDownResults == null) {- // Lazy init, in case all requests were against- // drill-sideways dims:- drillDownResults = drillDownCollector.getFacetResults();- //System.out.println("get DD results");- }- //System.out.println("add dd results " + i);- mergedResults.add(drillDownResults.get(ddUpto++));- } else {- // Drill sideways dim:- int dim = dimIndex.intValue();- List<FacetResult> sidewaysResult = drillSidewaysResults[dim];- if (sidewaysResult == null) {- // Lazy init, in case no facet request is against- // a given drill down dim:- sidewaysResult = drillSidewaysCollectors[dim].getFacetResults();- drillSidewaysResults[dim] = sidewaysResult;- }- mergedResults.add(sidewaysResult.get(requestUpto[dim]));- requestUpto[dim]++;- }- }-- return new DrillSidewaysResult(mergedResults, null);- }-- /** Uses the more general but slower method of sideways- * counting. This method allows an arbitrary subQuery to- * implement the drill down for a given dimension. */- private void collectorMethod(DrillDownQuery ddq, Query baseQuery, int startClause, Collector hitCollector, Collector drillDownCollector, Collector[] drillSidewaysCollectors) throws IOException {-- BooleanClause[] clauses = ddq.getBooleanQuery().getClauses();-- Map<String,Integer> drillDownDims = ddq.getDims();-- BooleanQuery topQuery = new BooleanQuery(true);- final DrillSidewaysCollector collector = new DrillSidewaysCollector(hitCollector, drillDownCollector, drillSidewaysCollectors,- drillDownDims);-- // TODO: if query is already a BQ we could copy that and- // add clauses to it, instead of doing BQ inside BQ- // (should be more efficient)? Problem is this can- // affect scoring (coord) ... too bad we can't disable- // coord on a clause by clause basis:- topQuery.add(baseQuery, BooleanClause.Occur.MUST);-- // NOTE: in theory we could just make a single BQ, with- // +query a b c minShouldMatch=2, but in this case,- // annoyingly, BS2 wraps a sub-scorer that always- // returns 2 as the .freq(), not how many of the- // SHOULD clauses matched:- BooleanQuery subQuery = new BooleanQuery(true);-- Query wrappedSubQuery = new QueryWrapper(subQuery,- new SetWeight() {- @Override- public void set(Weight w) {- collector.setWeight(w, -1);- }- });- Query constantScoreSubQuery = new ConstantScoreQuery(wrappedSubQuery);-- // Don't impact score of original query:- constantScoreSubQuery.setBoost(0.0f);-- topQuery.add(constantScoreSubQuery, BooleanClause.Occur.MUST);-- // Unfortunately this sub-BooleanQuery- // will never get BS1 because today BS1 only works- // if topScorer=true... and actually we cannot use BS1- // anyways because we need subDocsScoredAtOnce:- int dimIndex = 0;- for(int i=startClause;i<clauses.length;i++) {- Query q = clauses[i].getQuery();- // DrillDownQuery always wraps each subQuery in- // ConstantScoreQuery:- assert q instanceof ConstantScoreQuery;- q = ((ConstantScoreQuery) q).getQuery();-- final int finalDimIndex = dimIndex;- subQuery.add(new QueryWrapper(q,- new SetWeight() {- @Override- public void set(Weight w) {- collector.setWeight(w, finalDimIndex);- }- }),- BooleanClause.Occur.SHOULD);- dimIndex++;- }-- // TODO: we could better optimize the "just one drill- // down" case w/ a separate [specialized]- // collector...- int minShouldMatch = drillDownDims.size()-1;- if (minShouldMatch == 0) {- // Must add another "fake" clause so BQ doesn't erase- // itself by rewriting to the single clause:- Query end = new MatchAllDocsQuery();- end.setBoost(0.0f);- subQuery.add(end, BooleanClause.Occur.SHOULD);- minShouldMatch++;- }-- subQuery.setMinimumNumberShouldMatch(minShouldMatch);-- // System.out.println("EXE " + topQuery);-- // Collects against the passed-in- // drillDown/SidewaysCollectors as a side effect:- searcher.search(topQuery, collector);- }-- /**- * Search, sorting by {@link Sort}, and computing- * drill down and sideways counts.- */- public DrillSidewaysResult search(DrillDownQuery query,- Filter filter, FieldDoc after, int topN, Sort sort, boolean doDocScores,- boolean doMaxScore, FacetSearchParams fsp) throws IOException {- if (filter != null) {- query = new DrillDownQuery(filter, query);- }- if (sort != null) {- int limit = searcher.getIndexReader().maxDoc();- if (limit == 0) {- limit = 1; // the collector does not alow numHits = 0- }- topN = Math.min(topN, limit);- final TopFieldCollector hitCollector = TopFieldCollector.create(sort,- topN,- after,- true,- doDocScores,- doMaxScore,- true);- DrillSidewaysResult r = search(query, hitCollector, fsp);- return new DrillSidewaysResult(r.facetResults, hitCollector.topDocs());- } else {- return search(after, query, topN, fsp);- }- }-- /**- * Search, sorting by score, and computing- * drill down and sideways counts.- */- public DrillSidewaysResult search(ScoreDoc after,- DrillDownQuery query, int topN, FacetSearchParams fsp) throws IOException {- int limit = searcher.getIndexReader().maxDoc();- if (limit == 0) {- limit = 1; // the collector does not alow numHits = 0- }- topN = Math.min(topN, limit);- TopScoreDocCollector hitCollector = TopScoreDocCollector.create(topN, after, true);- DrillSidewaysResult r = search(query, hitCollector, fsp);- return new DrillSidewaysResult(r.facetResults, hitCollector.topDocs());- }-- /** Override this to use a custom drill-down {@link- * FacetsAccumulator}. */- protected FacetsAccumulator getDrillDownAccumulator(FacetSearchParams fsp) throws IOException {- if (taxoReader != null) {- return FacetsAccumulator.create(fsp, searcher.getIndexReader(), taxoReader, null);- } else {- return FacetsAccumulator.create(fsp, state, null);- }- }-- /** Override this to use a custom drill-sideways {@link- * FacetsAccumulator}. */- protected FacetsAccumulator getDrillSidewaysAccumulator(String dim, FacetSearchParams fsp) throws IOException {- if (taxoReader != null) {- return FacetsAccumulator.create(fsp, searcher.getIndexReader(), taxoReader, null);- } else {- return FacetsAccumulator.create(fsp, state, null);- }- }-- /** Override this and return true if your collector- * (e.g., ToParentBlockJoinCollector) expects all- * sub-scorers to be positioned on the document being- * collected. This will cause some performance loss;- * default is false. Note that if you return true from- * this method (in a subclass) be sure your collector- * also returns false from {@link- * Collector#acceptsDocsOutOfOrder}: this will trick- * BooleanQuery into also scoring all subDocs at once. */- protected boolean scoreSubDocsAtOnce() {- return false;- }-- /**- * Represents the returned result from a drill sideways search. Note that if- * you called- * {@link DrillSideways#search(DrillDownQuery, Collector, FacetSearchParams)},- * then {@link #hits} will be {@code null}.- */- public static class DrillSidewaysResult {- /** Combined drill down & sideways results. */- public final List<FacetResult> facetResults;-- /** Hits. */- public final TopDocs hits;-- public DrillSidewaysResult(List<FacetResult> facetResults, TopDocs hits) {- this.facetResults = facetResults;- this.hits = hits;- }- }-- private interface SetWeight {- public void set(Weight w);- }-- /** Just records which Weight was given out for the- * (possibly rewritten) Query. */- private static class QueryWrapper extends Query {- private final Query originalQuery;- private final SetWeight setter;-- public QueryWrapper(Query originalQuery, SetWeight setter) {- this.originalQuery = originalQuery;- this.setter = setter;- }-- @Override- public Weight createWeight(final IndexSearcher searcher) throws IOException {- Weight w = originalQuery.createWeight(searcher);- setter.set(w);- return w;- }-- @Override- public Query rewrite(IndexReader reader) throws IOException {- Query rewritten = originalQuery.rewrite(reader);- if (rewritten != originalQuery) {- return new QueryWrapper(rewritten, setter);- } else {- return this;- }- }-- @Override- public String toString(String s) {- return originalQuery.toString(s);- }-- @Override- public boolean equals(Object o) {- if (!(o instanceof QueryWrapper)) return false;- final QueryWrapper other = (QueryWrapper) o;- return super.equals(o) && originalQuery.equals(other.originalQuery);- }-- @Override- public int hashCode() {- return super.hashCode() * 31 + originalQuery.hashCode();- }- }-}-diff --git a/lucene/facet/src/java/org/apache/lucene/facet/search/FacetsAccumulator.java b/lucene/facet/src/java/org/apache/lucene/facet/search/FacetsAccumulator.javaindex 47d9885b377..9494c71a232 100644--- a/lucene/facet/src/java/org/apache/lucene/facet/search/FacetsAccumulator.java+++ b/lucene/facet/src/java/org/apache/lucene/facet/search/FacetsAccumulator.java@@ -8,8 +8,6 @@ import org.apache.lucene.facet.old.OldFacetsAccumulator;import org.apache.lucene.facet.params.FacetIndexingParams;import org.apache.lucene.facet.params.FacetSearchParams;import org.apache.lucene.facet.search.FacetsCollector.MatchingDocs;-import org.apache.lucene.facet.sortedset.SortedSetDocValuesAccumulator;-import org.apache.lucene.facet.sortedset.SortedSetDocValuesReaderState;import org.apache.lucene.facet.taxonomy.TaxonomyReader;import org.apache.lucene.index.IndexReader;@@ -77,35 +75,6 @@ public abstract class FacetsAccumulator {return new TaxonomyFacetsAccumulator(fsp, indexReader, taxoReader, arrays);}- /**- * Creates a {@link FacetsAccumulator} for the given facet requests. This- * method supports {@link RangeAccumulator} and- * {@link SortedSetDocValuesAccumulator} by dividing the facet requests into- * {@link RangeFacetRequest} and the rest.- * <p>- * If both types of facet requests are used, it returns a- * {@link MultiFacetsAccumulator} and the facet results returned from- * {@link #accumulate(List)} may not be in the same order as the given facet- * requests.- *- * @param fsp- * the search params define the facet requests and the- * {@link FacetIndexingParams}- * @param state- * the {@link SortedSetDocValuesReaderState} needed for accumulating- * the categories- * @param arrays- * the {@link FacetArrays} which the accumulator should use to- * store the categories weights in. Can be {@code null}.- */- public static FacetsAccumulator create(FacetSearchParams fsp, SortedSetDocValuesReaderState state, FacetArrays arrays) throws IOException {- if (fsp.indexingParams.getPartitionSize() != Integer.MAX_VALUE) {- throw new IllegalArgumentException("only default partition size is supported by this method: " + fsp.indexingParams.getPartitionSize());- }-- return new SortedSetDocValuesAccumulator(state, fsp, arrays);- }-/** Returns an empty {@link FacetResult}. */protected static FacetResult emptyResult(int ordinal, FacetRequest fr) {FacetResultNode root = new FacetResultNode(ordinal, 0);diff --git a/lucene/facet/src/java/org/apache/lucene/facet/sortedset/SortedSetDocValuesAccumulator.java b/lucene/facet/src/java/org/apache/lucene/facet/sortedset/SortedSetDocValuesAccumulator.javadeleted file mode 100644index b15bb4689e7..00000000000--- a/lucene/facet/src/java/org/apache/lucene/facet/sortedset/SortedSetDocValuesAccumulator.java+++ /dev/null@@ -1,324 +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.io.IOException;-import java.util.ArrayList;-import java.util.Arrays;-import java.util.Collections;-import java.util.Comparator;-import java.util.List;--import org.apache.lucene.facet.params.CategoryListParams;-import org.apache.lucene.facet.params.FacetSearchParams;-import org.apache.lucene.facet.search.CountFacetRequest;-import org.apache.lucene.facet.search.FacetArrays;-import org.apache.lucene.facet.search.FacetRequest;-import org.apache.lucene.facet.search.FacetResult;-import org.apache.lucene.facet.search.FacetResultNode;-import org.apache.lucene.facet.search.FacetsAccumulator;-import org.apache.lucene.facet.search.FacetsCollector.MatchingDocs;-import org.apache.lucene.facet.taxonomy.FacetLabel;-import org.apache.lucene.index.AtomicReader;-import org.apache.lucene.index.IndexReader;-import org.apache.lucene.index.MultiDocValues;-import org.apache.lucene.index.MultiDocValues.MultiSortedSetDocValues;-import org.apache.lucene.index.ReaderUtil;-import org.apache.lucene.index.SortedSetDocValues;-import org.apache.lucene.util.BytesRef;-import org.apache.lucene.util.PriorityQueue;--/** A {@link FacetsAccumulator} that uses previously- * indexed {@link SortedSetDocValuesFacetFields} to perform faceting,- * without require a separate taxonomy index. Faceting is- * a bit slower (~25%), and there is added cost on every- * {@link IndexReader} open to create a new {@link- * SortedSetDocValuesReaderState}. Furthermore, this does- * not support hierarchical facets; only flat (dimension +- * label) facets, but it uses quite a bit less RAM to do so. */-public class SortedSetDocValuesAccumulator extends FacetsAccumulator {-- final SortedSetDocValuesReaderState state;- final SortedSetDocValues dv;- final String field;- final FacetArrays facetArrays;-- /** Constructor with the given facet search params. */- public SortedSetDocValuesAccumulator(SortedSetDocValuesReaderState state, FacetSearchParams fsp)- throws IOException {- this(state, fsp, null);- }-- public SortedSetDocValuesAccumulator(SortedSetDocValuesReaderState state, FacetSearchParams fsp, FacetArrays arrays)- throws IOException {- super(fsp);- this.state = state;- this.field = state.getField();- this.facetArrays = arrays == null ? new FacetArrays(state.getSize()) : arrays;- dv = state.getDocValues();-- // Check params:- for (FacetRequest fr : fsp.facetRequests) {- if (!(fr instanceof CountFacetRequest)) {- throw new IllegalArgumentException("this accumulator only supports CountFacetRequest; got " + fr);- }- if (fr.categoryPath.length != 1) {- throw new IllegalArgumentException("this accumulator only supports 1-level CategoryPath; got " + fr.categoryPath);- }- if (fr.getDepth() != 1) {- throw new IllegalArgumentException("this accumulator only supports depth=1; got " + fr.getDepth());- }- String dim = fr.categoryPath.components[0];-- SortedSetDocValuesReaderState.OrdRange ordRange = state.getOrdRange(dim);- if (ordRange == null) {- throw new IllegalArgumentException("dim \"" + dim + "\" does not exist");- }- }- }-- /** Keeps highest count results. */- static class TopCountPQ extends PriorityQueue<FacetResultNode> {- public TopCountPQ(int topN) {- super(topN, false);- }-- @Override- protected boolean lessThan(FacetResultNode a, FacetResultNode b) {- if (a.value < b.value) {- return true;- } else if (a.value > b.value) {- return false;- } else {- return a.ordinal > b.ordinal;- }- }- }-- static class SortedSetAggregator {-- private final SortedSetDocValuesReaderState state;- private final String field;- private final SortedSetDocValues dv;-- public SortedSetAggregator(String field, SortedSetDocValuesReaderState state, SortedSetDocValues dv) {- this.field = field;- this.state = state;- this.dv = dv;- }-- public void aggregate(MatchingDocs matchingDocs, FacetArrays facetArrays) throws IOException {-- AtomicReader reader = matchingDocs.context.reader();-- // LUCENE-5090: make sure the provided reader context "matches"- // the top-level reader passed to the- // SortedSetDocValuesReaderState, else cryptic- // AIOOBE can happen:- if (ReaderUtil.getTopLevelContext(matchingDocs.context).reader() != state.origReader) {- throw new IllegalStateException("the SortedSetDocValuesReaderState provided to this class does not match the reader being searched; you must create a new SortedSetDocValuesReaderState every time you open a new IndexReader");- }-- SortedSetDocValues segValues = reader.getSortedSetDocValues(field);- if (segValues == null) {- return;- }-- final int[] counts = facetArrays.getIntArray();- final int maxDoc = reader.maxDoc();- assert maxDoc == matchingDocs.bits.length();-- if (dv instanceof MultiSortedSetDocValues) {- MultiDocValues.OrdinalMap ordinalMap = ((MultiSortedSetDocValues) dv).mapping;- int segOrd = matchingDocs.context.ord;-- int numSegOrds = (int) segValues.getValueCount();-- if (matchingDocs.totalHits < numSegOrds/10) {- // Remap every ord to global ord as we iterate:- int doc = 0;- while (doc < maxDoc && (doc = matchingDocs.bits.nextSetBit(doc)) != -1) {- segValues.setDocument(doc);- int term = (int) segValues.nextOrd();- while (term != SortedSetDocValues.NO_MORE_ORDS) {- counts[(int) ordinalMap.getGlobalOrd(segOrd, term)]++;- term = (int) segValues.nextOrd();- }- ++doc;- }- } else {-- // First count in seg-ord space:- final int[] segCounts = new int[numSegOrds];- int doc = 0;- while (doc < maxDoc && (doc = matchingDocs.bits.nextSetBit(doc)) != -1) {- segValues.setDocument(doc);- int term = (int) segValues.nextOrd();- while (term != SortedSetDocValues.NO_MORE_ORDS) {- segCounts[term]++;- term = (int) segValues.nextOrd();- }- ++doc;- }-- // Then, migrate to global ords:- for(int ord=0;ord<numSegOrds;ord++) {- int count = segCounts[ord];- if (count != 0) {- counts[(int) ordinalMap.getGlobalOrd(segOrd, ord)] += count;- }- }- }- } else {- // No ord mapping (e.g., single segment index):- // just aggregate directly into counts:-- int doc = 0;- while (doc < maxDoc && (doc = matchingDocs.bits.nextSetBit(doc)) != -1) {- segValues.setDocument(doc);- int term = (int) segValues.nextOrd();- while (term != SortedSetDocValues.NO_MORE_ORDS) {- counts[term]++;- term = (int) segValues.nextOrd();- }- ++doc;- }- }- }-- }-- @Override- public List<FacetResult> accumulate(List<MatchingDocs> matchingDocs) throws IOException {-- SortedSetAggregator aggregator = new SortedSetAggregator(field, state, dv);- for (MatchingDocs md : matchingDocs) {- aggregator.aggregate(md, facetArrays);- }-- // compute top-K- List<FacetResult> results = new ArrayList<FacetResult>();-- int[] counts = facetArrays.getIntArray();-- BytesRef scratch = new BytesRef();-- for (FacetRequest request : searchParams.facetRequests) {- String dim = request.categoryPath.components[0];- SortedSetDocValuesReaderState.OrdRange ordRange = state.getOrdRange(dim);- // checked in ctor:- assert ordRange != null;-- if (request.numResults >= ordRange.end - ordRange.start + 1) {- // specialize this case, user is interested in all available results- ArrayList<FacetResultNode> nodes = new ArrayList<FacetResultNode>();- int dimCount = 0;- for(int ord=ordRange.start; ord<=ordRange.end; ord++) {- //System.out.println(" ord=" + ord + " count= "+ counts[ord] + " bottomCount=" + bottomCount);- if (counts[ord] != 0) {- dimCount += counts[ord];- FacetResultNode node = new FacetResultNode(ord, counts[ord]);- dv.lookupOrd(ord, scratch);- node.label = new FacetLabel(scratch.utf8ToString().split(state.separatorRegex, 2));- nodes.add(node);- }- }-- Collections.sort(nodes, new Comparator<FacetResultNode>() {- @Override- public int compare(FacetResultNode o1, FacetResultNode o2) {- // First by highest count- int value = (int) (o2.value - o1.value);- if (value == 0) {- // ... then by lowest ord:- value = o1.ordinal - o2.ordinal;- }- return value;- }- });-- CategoryListParams.OrdinalPolicy op = searchParams.indexingParams.getCategoryListParams(request.categoryPath).getOrdinalPolicy(dim);- if (op == CategoryListParams.OrdinalPolicy.ALL_BUT_DIMENSION) {- dimCount = 0;- }-- FacetResultNode rootNode = new FacetResultNode(-1, dimCount);- rootNode.label = new FacetLabel(new String[] {dim});- rootNode.subResults = nodes;- results.add(new FacetResult(request, rootNode, nodes.size()));- continue;- }-- TopCountPQ q = new TopCountPQ(request.numResults);-- int bottomCount = 0;-- //System.out.println("collect");- int dimCount = 0;- int childCount = 0;- FacetResultNode reuse = null;- for(int ord=ordRange.start; ord<=ordRange.end; ord++) {- //System.out.println(" ord=" + ord + " count= "+ counts[ord] + " bottomCount=" + bottomCount);- if (counts[ord] > 0) {- childCount++;- if (counts[ord] > bottomCount) {- dimCount += counts[ord];- //System.out.println(" keep");- if (reuse == null) {- reuse = new FacetResultNode(ord, counts[ord]);- } else {- reuse.ordinal = ord;- reuse.value = counts[ord];- }- reuse = q.insertWithOverflow(reuse);- if (q.size() == request.numResults) {- bottomCount = (int) q.top().value;- //System.out.println(" new bottom=" + bottomCount);- }- }- }- }-- CategoryListParams.OrdinalPolicy op = searchParams.indexingParams.getCategoryListParams(request.categoryPath).getOrdinalPolicy(dim);- if (op == CategoryListParams.OrdinalPolicy.ALL_BUT_DIMENSION) {- dimCount = 0;- }-- FacetResultNode rootNode = new FacetResultNode(-1, dimCount);- rootNode.label = new FacetLabel(new String[] {dim});-- FacetResultNode[] childNodes = new FacetResultNode[q.size()];- for(int i=childNodes.length-1;i>=0;i--) {- childNodes[i] = q.pop();- dv.lookupOrd(childNodes[i].ordinal, scratch);- childNodes[i].label = new FacetLabel(scratch.utf8ToString().split(state.separatorRegex, 2));- }- rootNode.subResults = Arrays.asList(childNodes);-- results.add(new FacetResult(request, rootNode, childCount));- }-- return results;- }-- @Override- public boolean requiresDocScores() {- return false;- }--}diff --git a/lucene/facet/src/java/org/apache/lucene/facet/sortedset/SortedSetDocValuesFacetFields.java b/lucene/facet/src/java/org/apache/lucene/facet/sortedset/SortedSetDocValuesFacetFields.javadeleted file mode 100644index 18d94a75e47..00000000000--- a/lucene/facet/src/java/org/apache/lucene/facet/sortedset/SortedSetDocValuesFacetFields.java+++ /dev/null@@ -1,86 +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.io.IOException;-import java.util.Map.Entry;-import java.util.Map;--import org.apache.lucene.document.Document;-import org.apache.lucene.document.Field;-import org.apache.lucene.document.SortedSetDocValuesField;-import org.apache.lucene.facet.index.DrillDownStream;-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.taxonomy.FacetLabel;-import org.apache.lucene.util.BytesRef;--/** Use this to index facets if you intend to- * use {@link SortedSetDocValuesAccumulator} to count facets- * at search time. Note that this only supports flat- * facets (dimension + label). Instantiate this class- * once, and then call {@link #addFields} to add the- * necessary fields to each {@link Document}. */--public class SortedSetDocValuesFacetFields extends FacetFields {-- /** Create a {@code SortedSetDocValuesFacetField} with the- * provided {@link FacetLabel}. */- public SortedSetDocValuesFacetFields() {- this(FacetIndexingParams.DEFAULT);- }-- /** Create a {@code SortedSetDocValuesFacetField} with the- * provided {@link FacetLabel}, and custom {@link- * FacetIndexingParams}. */- public SortedSetDocValuesFacetFields(FacetIndexingParams fip) {- super(null, fip);- if (fip.getPartitionSize() != Integer.MAX_VALUE) {- throw new IllegalArgumentException("partitions are not supported");- }- }-- @Override- public void addFields(Document doc, Iterable<FacetLabel> categories) throws IOException {- if (categories == null) {- throw new IllegalArgumentException("categories should not be null");- }-- final Map<CategoryListParams,Iterable<FacetLabel>> categoryLists = createCategoryListMapping(categories);- for (Entry<CategoryListParams, Iterable<FacetLabel>> e : categoryLists.entrySet()) {-- CategoryListParams clp = e.getKey();- String dvField = clp.field + SortedSetDocValuesReaderState.FACET_FIELD_EXTENSION;-- // Add sorted-set DV fields, one per value:- for(FacetLabel cp : e.getValue()) {- if (cp.length != 2) {- throw new IllegalArgumentException("only flat facets (dimension + label) are currently supported; got " + cp);- }- doc.add(new SortedSetDocValuesField(dvField, new BytesRef(cp.toString(indexingParams.getFacetDelimChar()))));- }-- // add the drill-down field- DrillDownStream drillDownStream = getDrillDownStream(e.getValue());- Field drillDown = new Field(clp.field, drillDownStream, drillDownFieldType());- doc.add(drillDown);- }- }-}-diff --git a/lucene/facet/src/java/org/apache/lucene/facet/sortedset/SortedSetDocValuesReaderState.java b/lucene/facet/src/java/org/apache/lucene/facet/sortedset/SortedSetDocValuesReaderState.javadeleted file mode 100644index b890353eefc..00000000000--- a/lucene/facet/src/java/org/apache/lucene/facet/sortedset/SortedSetDocValuesReaderState.java+++ /dev/null@@ -1,155 +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.io.IOException;-import java.util.HashMap;-import java.util.Map;-import java.util.regex.Pattern;--import org.apache.lucene.facet.params.CategoryListParams;-import org.apache.lucene.facet.params.FacetIndexingParams;-import org.apache.lucene.index.AtomicReader;-import org.apache.lucene.index.CompositeReader;-import org.apache.lucene.index.IndexReader;-import org.apache.lucene.index.SlowCompositeReaderWrapper;-import org.apache.lucene.index.SortedSetDocValues;-import org.apache.lucene.util.BytesRef;--/** Wraps a {@link IndexReader} and resolves ords- * using existing {@link SortedSetDocValues} APIs without a- * separate taxonomy index. This only supports flat facets- * (dimension + label), and it makes faceting a bit- * slower, adds some cost at reopen time, but avoids- * managing the separate taxonomy index. It also requires- * less RAM than the taxonomy index, as it manages the flat- * (2-level) hierarchy more efficiently. In addition, the- * tie-break during faceting is now meaningful (in label- * sorted order).- *- * <p><b>NOTE</b>: creating an instance of this class is- * somewhat costly, as it computes per-segment ordinal maps,- * so you should create it once and re-use that one instance- * for a given {@link IndexReader}. */--public final class SortedSetDocValuesReaderState {-- private final String field;- private final AtomicReader topReader;- private final int valueCount;- final IndexReader origReader;- final char separator;- final String separatorRegex;-- /** Extension added to {@link CategoryListParams#field}- * to determin which field to read/write facet ordinals from/to. */- public static final String FACET_FIELD_EXTENSION = "_sorted_doc_values";-- /** Holds start/end range of ords, which maps to one- * dimension (someday we may generalize it to map to- * hierarchies within one dimension). */- static final class OrdRange {- /** Start of range, inclusive: */- public final int start;- /** End of range, inclusive: */- public final int end;-- /** Start and end are inclusive. */- public OrdRange(int start, int end) {- this.start = start;- this.end = end;- }- }-- private final Map<String,OrdRange> prefixToOrdRange = new HashMap<String,OrdRange>();-- /** Create an instance, scanning the {@link- * SortedSetDocValues} from the provided reader, with- * default {@link FacetIndexingParams}. */- public SortedSetDocValuesReaderState(IndexReader reader) throws IOException {- this(FacetIndexingParams.DEFAULT, reader);- }-- /** Create an instance, scanning the {@link- * SortedSetDocValues} from the provided reader and- * {@link FacetIndexingParams}. */- public SortedSetDocValuesReaderState(FacetIndexingParams fip, IndexReader reader) throws IOException {-- this.field = fip.getCategoryListParams(null).field + FACET_FIELD_EXTENSION;- this.separator = fip.getFacetDelimChar();- this.separatorRegex = Pattern.quote(Character.toString(separator));- this.origReader = reader;-- // We need this to create thread-safe MultiSortedSetDV- // per collector:- topReader = SlowCompositeReaderWrapper.wrap(reader);- SortedSetDocValues dv = topReader.getSortedSetDocValues(field);- if (dv == null) {- throw new IllegalArgumentException("field \"" + field + "\" was not indexed with SortedSetDocValues");- }- if (dv.getValueCount() > Integer.MAX_VALUE) {- throw new IllegalArgumentException("can only handle valueCount < Integer.MAX_VALUE; got " + dv.getValueCount());- }- valueCount = (int) dv.getValueCount();-- // TODO: we can make this more efficient if eg we can be- // "involved" when OrdinalMap is being created? Ie see- // each term/ord it's assigning as it goes...- String lastDim = null;- int startOrd = -1;- BytesRef spare = new BytesRef();-- // TODO: this approach can work for full hierarchy?;- // TaxoReader can't do this since ords are not in- // "sorted order" ... but we should generalize this to- // support arbitrary hierarchy:- for(int ord=0;ord<valueCount;ord++) {- dv.lookupOrd(ord, spare);- String[] components = spare.utf8ToString().split(separatorRegex, 2);- if (components.length != 2) {- throw new IllegalArgumentException("this class can only handle 2 level hierarchy (dim/value); got: " + spare.utf8ToString());- }- if (!components[0].equals(lastDim)) {- if (lastDim != null) {- prefixToOrdRange.put(lastDim, new OrdRange(startOrd, ord-1));- }- startOrd = ord;- lastDim = components[0];- }- }-- if (lastDim != null) {- prefixToOrdRange.put(lastDim, new OrdRange(startOrd, valueCount-1));- }- }-- SortedSetDocValues getDocValues() throws IOException {- return topReader.getSortedSetDocValues(field);- }-- OrdRange getOrdRange(String dim) {- return prefixToOrdRange.get(dim);- }-- String getField() {- return field;- }-- int getSize() {- return valueCount;- }-}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.javaindex 6a1cc4f3c18..f69d480b3da 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@@ -49,7 +49,6 @@ import org.apache.lucene.facet.search.FacetResultNode;import org.apache.lucene.facet.search.FacetsAccumulator;import org.apache.lucene.facet.search.FacetsCollector;import org.apache.lucene.facet.simple.SimpleDrillSideways.SimpleDrillSidewaysResult;-import org.apache.lucene.facet.sortedset.SortedSetDocValuesReaderState;import org.apache.lucene.facet.taxonomy.FacetLabel;import org.apache.lucene.facet.taxonomy.TaxonomyReader;import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyReader;