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 org.apache.lucene.analysis.core.WhitespaceAnalyzer;
020import org.apache.lucene.document.LongPoint;
021import org.apache.lucene.document.Document;
022import org.apache.lucene.document.NumericDocValuesField;
023import org.apache.lucene.facet.DrillDownQuery;
024import org.apache.lucene.facet.FacetResult;
025import org.apache.lucene.facet.Facets;
026import org.apache.lucene.facet.FacetsCollector;
027import org.apache.lucene.facet.FacetsConfig;
028import org.apache.lucene.facet.range.LongRange;
029import org.apache.lucene.facet.range.LongRangeFacetCounts;
030import org.apache.lucene.index.DirectoryReader;
031import org.apache.lucene.index.IndexWriter;
032import org.apache.lucene.index.IndexWriterConfig;
033import org.apache.lucene.index.IndexWriterConfig.OpenMode;
034import org.apache.lucene.search.IndexSearcher;
035import org.apache.lucene.search.MatchAllDocsQuery;
036import org.apache.lucene.search.TopDocs;
037import org.apache.lucene.store.Directory;
038import org.apache.lucene.store.RAMDirectory;
039
040import java.io.Closeable;
041import java.io.IOException;
042
043/** Shows simple usage of dynamic range faceting. */
044public class RangeFacetsExample implements Closeable {
045
046  private final Directory indexDir = new RAMDirectory();
047  private IndexSearcher searcher;
048  private final long nowSec = System.currentTimeMillis();
049
050  final LongRange PAST_HOUR = new LongRange("Past hour", nowSec-3600, true, nowSec, true);
051  final LongRange PAST_SIX_HOURS = new LongRange("Past six hours", nowSec-6*3600, true, nowSec, true);
052  final LongRange PAST_DAY = new LongRange("Past day", nowSec-24*3600, true, nowSec, true);
053
054  /** Empty constructor */
055  public RangeFacetsExample() {}
056  
057  /** Build the example index. */
058  public void index() throws IOException {
059    IndexWriter indexWriter = new IndexWriter(indexDir, new IndexWriterConfig(
060        new WhitespaceAnalyzer()).setOpenMode(OpenMode.CREATE));
061
062    // Add documents with a fake timestamp, 1000 sec before
063    // "now", 2000 sec before "now", ...:
064    for(int i=0;i<100;i++) {
065      Document doc = new Document();
066      long then = nowSec - i * 1000;
067      // Add as doc values field, so we can compute range facets:
068      doc.add(new NumericDocValuesField("timestamp", then));
069      // Add as numeric field so we can drill-down:
070      doc.add(new LongPoint("timestamp", then));
071      indexWriter.addDocument(doc);
072    }
073
074    // Open near-real-time searcher
075    searcher = new IndexSearcher(DirectoryReader.open(indexWriter));
076    indexWriter.close();
077  }
078
079  private FacetsConfig getConfig() {
080    return new FacetsConfig();
081  }
082
083  /** User runs a query and counts facets. */
084  public FacetResult search() throws IOException {
085
086    // Aggregates the facet counts
087    FacetsCollector fc = new FacetsCollector();
088
089    // MatchAllDocsQuery is for "browsing" (counts facets
090    // for all non-deleted docs in the index); normally
091    // you'd use a "normal" query:
092    FacetsCollector.search(searcher, new MatchAllDocsQuery(), 10, fc);
093
094    Facets facets = new LongRangeFacetCounts("timestamp", fc,
095                                             PAST_HOUR,
096                                             PAST_SIX_HOURS,
097                                             PAST_DAY);
098    return facets.getTopChildren(10, "timestamp");
099  }
100  
101  /** User drills down on the specified range. */
102  public TopDocs drillDown(LongRange range) throws IOException {
103
104    // Passing no baseQuery means we drill down on all
105    // documents ("browse only"):
106    DrillDownQuery q = new DrillDownQuery(getConfig());
107
108    q.add("timestamp", LongPoint.newRangeQuery("timestamp", range.min, range.max));
109    return searcher.search(q, 10);
110  }
111
112  @Override
113  public void close() throws IOException {
114    searcher.getIndexReader().close();
115    indexDir.close();
116  }
117
118  /** Runs the search and drill-down examples and prints the results. */
119  public static void main(String[] args) throws Exception {
120    RangeFacetsExample example = new RangeFacetsExample();
121    example.index();
122
123    System.out.println("Facet counting example:");
124    System.out.println("-----------------------");
125    System.out.println(example.search());
126
127    System.out.println("\n");
128    System.out.println("Facet drill-down example (timestamp/Past six hours):");
129    System.out.println("---------------------------------------------");
130    TopDocs hits = example.drillDown(example.PAST_SIX_HOURS);
131    System.out.println(hits.totalHits + " totalHits");
132
133    example.close();
134  }
135}