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.util.ArrayList;
021import java.util.List;
022import org.apache.lucene.analysis.core.WhitespaceAnalyzer;
023import org.apache.lucene.document.Document;
024import org.apache.lucene.facet.DrillDownQuery;
025import org.apache.lucene.facet.DrillSideways;
026import org.apache.lucene.facet.DrillSideways.DrillSidewaysResult;
027import org.apache.lucene.facet.FacetField;
028import org.apache.lucene.facet.FacetResult;
029import org.apache.lucene.facet.Facets;
030import org.apache.lucene.facet.FacetsCollector;
031import org.apache.lucene.facet.FacetsCollectorManager;
032import org.apache.lucene.facet.FacetsConfig;
033import org.apache.lucene.facet.taxonomy.FastTaxonomyFacetCounts;
034import org.apache.lucene.facet.taxonomy.TaxonomyReader;
035import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyReader;
036import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyWriter;
037import org.apache.lucene.index.DirectoryReader;
038import org.apache.lucene.index.IndexWriter;
039import org.apache.lucene.index.IndexWriterConfig;
040import org.apache.lucene.index.IndexWriterConfig.OpenMode;
041import org.apache.lucene.search.IndexSearcher;
042import org.apache.lucene.search.MatchAllDocsQuery;
043import org.apache.lucene.store.ByteBuffersDirectory;
044import org.apache.lucene.store.Directory;
045import org.apache.lucene.util.IOUtils;
046
047/** Shows simple usage of faceted indexing and search. */
048public class SimpleFacetsExample {
049
050  private final Directory indexDir = new ByteBuffersDirectory();
051  private final Directory taxoDir = new ByteBuffersDirectory();
052  private final FacetsConfig config = new FacetsConfig();
053
054  /** Empty constructor */
055  public SimpleFacetsExample() {
056    config.setHierarchical("Publish Date", true);
057  }
058
059  /** Build the example index. */
060  void index() throws IOException {
061    IndexWriter indexWriter =
062        new IndexWriter(
063            indexDir, new IndexWriterConfig(new WhitespaceAnalyzer()).setOpenMode(OpenMode.CREATE));
064
065    // Writes facet ords to a separate directory from the main index
066    DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir);
067
068    Document doc = new Document();
069    doc.add(new FacetField("Author", "Bob"));
070    doc.add(new FacetField("Publish Date", "2010", "10", "15"));
071    indexWriter.addDocument(config.build(taxoWriter, doc));
072
073    doc = new Document();
074    doc.add(new FacetField("Author", "Lisa"));
075    doc.add(new FacetField("Publish Date", "2010", "10", "20"));
076    indexWriter.addDocument(config.build(taxoWriter, doc));
077
078    doc = new Document();
079    doc.add(new FacetField("Author", "Lisa"));
080    doc.add(new FacetField("Publish Date", "2012", "1", "1"));
081    indexWriter.addDocument(config.build(taxoWriter, doc));
082
083    doc = new Document();
084    doc.add(new FacetField("Author", "Susan"));
085    doc.add(new FacetField("Publish Date", "2012", "1", "7"));
086    indexWriter.addDocument(config.build(taxoWriter, doc));
087
088    doc = new Document();
089    doc.add(new FacetField("Author", "Frank"));
090    doc.add(new FacetField("Publish Date", "1999", "5", "5"));
091    indexWriter.addDocument(config.build(taxoWriter, doc));
092
093    IOUtils.close(indexWriter, taxoWriter);
094  }
095
096  /** User runs a query and counts facets. */
097  List<FacetResult> facetsWithSearch() throws IOException {
098    DirectoryReader indexReader = DirectoryReader.open(indexDir);
099    IndexSearcher searcher = new IndexSearcher(indexReader);
100    TaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoDir);
101
102    FacetsCollectorManager fcm = new FacetsCollectorManager();
103
104    // MatchAllDocsQuery is for "browsing" (counts facets
105    // for all non-deleted docs in the index); normally
106    // you'd use a "normal" query:
107    FacetsCollector fc =
108        FacetsCollectorManager.search(searcher, new MatchAllDocsQuery(), 10, fcm).facetsCollector();
109
110    // Retrieve results
111    List<FacetResult> results = new ArrayList<>();
112
113    // Count both "Publish Date" and "Author" dimensions
114    Facets facets = new FastTaxonomyFacetCounts(taxoReader, config, fc);
115    results.add(facets.getTopChildren(10, "Author"));
116    results.add(facets.getTopChildren(10, "Publish Date"));
117
118    IOUtils.close(indexReader, taxoReader);
119
120    return results;
121  }
122
123  /** User runs a query and counts facets only without collecting the matching documents. */
124  private List<FacetResult> facetsOnly() throws IOException {
125    DirectoryReader indexReader = DirectoryReader.open(indexDir);
126    IndexSearcher searcher = new IndexSearcher(indexReader);
127    TaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoDir);
128
129    // MatchAllDocsQuery is for "browsing" (counts facets
130    // for all non-deleted docs in the index); normally
131    // you'd use a "normal" query:
132    FacetsCollector fc = searcher.search(new MatchAllDocsQuery(), new FacetsCollectorManager());
133
134    // Retrieve results
135    List<FacetResult> results = new ArrayList<>();
136
137    // Count both "Publish Date" and "Author" dimensions
138    Facets facets = new FastTaxonomyFacetCounts(taxoReader, config, fc);
139
140    results.add(facets.getTopChildren(10, "Author"));
141    results.add(facets.getTopChildren(10, "Publish Date"));
142
143    IOUtils.close(indexReader, taxoReader);
144
145    return results;
146  }
147
148  /** User drills down on 'Publish Date/2010', and we return facets for 'Author' */
149  FacetResult drillDown() throws IOException {
150    DirectoryReader indexReader = DirectoryReader.open(indexDir);
151    IndexSearcher searcher = new IndexSearcher(indexReader);
152    TaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoDir);
153
154    // Passing no baseQuery means we drill down on all
155    // documents ("browse only"):
156    DrillDownQuery q = new DrillDownQuery(config);
157
158    // Now user drills down on Publish Date/2010:
159    q.add("Publish Date", "2010");
160    FacetsCollectorManager fcm = new FacetsCollectorManager();
161    FacetsCollector fc = FacetsCollectorManager.search(searcher, q, 10, fcm).facetsCollector();
162
163    // Retrieve results
164    Facets facets = new FastTaxonomyFacetCounts(taxoReader, config, fc);
165    FacetResult result = facets.getTopChildren(10, "Author");
166
167    IOUtils.close(indexReader, taxoReader);
168
169    return result;
170  }
171
172  /**
173   * User drills down on 'Publish Date/2010', and we return facets for both 'Publish Date' and
174   * 'Author', using DrillSideways.
175   */
176  private List<FacetResult> drillSideways() throws IOException {
177    DirectoryReader indexReader = DirectoryReader.open(indexDir);
178    IndexSearcher searcher = new IndexSearcher(indexReader);
179    TaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoDir);
180
181    // Passing no baseQuery means we drill down on all
182    // documents ("browse only"):
183    DrillDownQuery q = new DrillDownQuery(config);
184
185    // Now user drills down on Publish Date/2010:
186    q.add("Publish Date", "2010");
187
188    DrillSideways ds = new DrillSideways(searcher, config, taxoReader);
189    DrillSidewaysResult result = ds.search(q, 10);
190
191    // Retrieve results
192    List<FacetResult> facets = result.facets.getAllDims(10);
193
194    IOUtils.close(indexReader, taxoReader);
195
196    return facets;
197  }
198
199  /** Runs the search example. */
200  public List<FacetResult> runFacetOnly() throws IOException {
201    index();
202    return facetsOnly();
203  }
204
205  /** Runs the search example. */
206  public List<FacetResult> runSearch() throws IOException {
207    index();
208    return facetsWithSearch();
209  }
210
211  /** Runs the drill-down example. */
212  public FacetResult runDrillDown() throws IOException {
213    index();
214    return drillDown();
215  }
216
217  /** Runs the drill-sideways example. */
218  public List<FacetResult> runDrillSideways() throws IOException {
219    index();
220    return drillSideways();
221  }
222
223  /** Runs the search and drill-down examples and prints the results. */
224  public static void main(String[] args) throws Exception {
225    System.out.println("Facet counting example:");
226    System.out.println("-----------------------");
227    SimpleFacetsExample example = new SimpleFacetsExample();
228    List<FacetResult> results1 = example.runFacetOnly();
229    System.out.println("Author: " + results1.get(0));
230    System.out.println("Publish Date: " + results1.get(1));
231
232    System.out.println("Facet counting example (combined facets and search):");
233    System.out.println("-----------------------");
234    List<FacetResult> results = example.runSearch();
235    System.out.println("Author: " + results.get(0));
236    System.out.println("Publish Date: " + results.get(1));
237
238    System.out.println("Facet drill-down example (Publish Date/2010):");
239    System.out.println("---------------------------------------------");
240    System.out.println("Author: " + example.runDrillDown());
241
242    System.out.println("Facet drill-sideways example (Publish Date/2010):");
243    System.out.println("---------------------------------------------");
244    for (FacetResult result : example.runDrillSideways()) {
245      System.out.println(result);
246    }
247  }
248}