001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.lucene.demo.facet;
018
019import java.io.IOException;
020import java.text.ParseException;
021import org.apache.lucene.analysis.core.WhitespaceAnalyzer;
022import org.apache.lucene.document.Document;
023import org.apache.lucene.document.Field.Store;
024import org.apache.lucene.document.NumericDocValuesField;
025import org.apache.lucene.document.TextField;
026import org.apache.lucene.expressions.Expression;
027import org.apache.lucene.expressions.SimpleBindings;
028import org.apache.lucene.expressions.js.JavascriptCompiler;
029import org.apache.lucene.facet.FacetField;
030import org.apache.lucene.facet.FacetResult;
031import org.apache.lucene.facet.Facets;
032import org.apache.lucene.facet.FacetsCollector;
033import org.apache.lucene.facet.FacetsConfig;
034import org.apache.lucene.facet.taxonomy.TaxonomyFacetSumValueSource;
035import org.apache.lucene.facet.taxonomy.TaxonomyReader;
036import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyReader;
037import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyWriter;
038import org.apache.lucene.index.DirectoryReader;
039import org.apache.lucene.index.IndexWriter;
040import org.apache.lucene.index.IndexWriterConfig;
041import org.apache.lucene.index.IndexWriterConfig.OpenMode;
042import org.apache.lucene.search.DoubleValuesSource;
043import org.apache.lucene.search.IndexSearcher;
044import org.apache.lucene.search.MatchAllDocsQuery;
045import org.apache.lucene.store.ByteBuffersDirectory;
046import org.apache.lucene.store.Directory;
047
048/** Shows facets aggregation by an expression. */
049public class ExpressionAggregationFacetsExample {
050
051  private final Directory indexDir = new ByteBuffersDirectory();
052  private final Directory taxoDir = new ByteBuffersDirectory();
053  private final FacetsConfig config = new FacetsConfig();
054
055  /** Empty constructor */
056  public ExpressionAggregationFacetsExample() {}
057
058  /** Build the example index. */
059  private void index() throws IOException {
060    IndexWriter indexWriter =
061        new IndexWriter(
062            indexDir, new IndexWriterConfig(new WhitespaceAnalyzer()).setOpenMode(OpenMode.CREATE));
063
064    // Writes facet ords to a separate directory from the main index
065    DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir);
066
067    Document doc = new Document();
068    doc.add(new TextField("c", "foo bar", Store.NO));
069    doc.add(new NumericDocValuesField("popularity", 5L));
070    doc.add(new FacetField("A", "B"));
071    indexWriter.addDocument(config.build(taxoWriter, doc));
072
073    doc = new Document();
074    doc.add(new TextField("c", "foo foo bar", Store.NO));
075    doc.add(new NumericDocValuesField("popularity", 3L));
076    doc.add(new FacetField("A", "C"));
077    indexWriter.addDocument(config.build(taxoWriter, doc));
078
079    indexWriter.close();
080    taxoWriter.close();
081  }
082
083  /** User runs a query and aggregates facets. */
084  private FacetResult search() throws IOException, ParseException {
085    DirectoryReader indexReader = DirectoryReader.open(indexDir);
086    IndexSearcher searcher = new IndexSearcher(indexReader);
087    TaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoDir);
088
089    // Aggregate categories by an expression that combines the document's score
090    // and its popularity field
091    Expression expr = JavascriptCompiler.compile("_score * sqrt(popularity)");
092    SimpleBindings bindings = new SimpleBindings();
093    bindings.add("_score", DoubleValuesSource.SCORES); // the score of the document
094    bindings.add(
095        "popularity",
096        DoubleValuesSource.fromLongField("popularity")); // the value of the 'popularity' field
097
098    // Aggregates the facet values
099    FacetsCollector fc = new FacetsCollector(true);
100
101    // MatchAllDocsQuery is for "browsing" (counts facets
102    // for all non-deleted docs in the index); normally
103    // you'd use a "normal" query:
104    FacetsCollector.search(searcher, new MatchAllDocsQuery(), 10, fc);
105
106    // Retrieve results
107    Facets facets =
108        new TaxonomyFacetSumValueSource(
109            taxoReader, config, fc, expr.getDoubleValuesSource(bindings));
110    FacetResult result = facets.getTopChildren(10, "A");
111
112    indexReader.close();
113    taxoReader.close();
114
115    return result;
116  }
117
118  /** Runs the search example. */
119  public FacetResult runSearch() throws IOException, ParseException {
120    index();
121    return search();
122  }
123
124  /** Runs the search and drill-down examples and prints the results. */
125  public static void main(String[] args) throws Exception {
126    System.out.println("Facet counting example:");
127    System.out.println("-----------------------");
128    FacetResult result = new ExpressionAggregationFacetsExample().runSearch();
129    System.out.println(result);
130  }
131}