001package org.apache.lucene.demo.facet;
002
003/*
004 * Licensed to the Apache Software Foundation (ASF) under one or more
005 * contributor license agreements.  See the NOTICE file distributed with
006 * this work for additional information regarding copyright ownership.
007 * The ASF licenses this file to You under the Apache License, Version 2.0
008 * (the "License"); you may not use this file except in compliance with
009 * the License.  You may obtain a copy of the License at
010 *
011 *     http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing, software
014 * distributed under the License is distributed on an "AS IS" BASIS,
015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
016 * See the License for the specific language governing permissions and
017 * limitations under the License.
018 */
019
020import java.io.Closeable;
021import java.io.IOException;
022
023import org.apache.lucene.analysis.core.WhitespaceAnalyzer;
024import org.apache.lucene.document.Document;
025import org.apache.lucene.document.Field;
026import org.apache.lucene.document.LongField;
027import org.apache.lucene.document.NumericDocValuesField;
028import org.apache.lucene.facet.DrillDownQuery;
029import org.apache.lucene.facet.FacetResult;
030import org.apache.lucene.facet.Facets;
031import org.apache.lucene.facet.FacetsCollector;
032import org.apache.lucene.facet.FacetsConfig;
033import org.apache.lucene.facet.range.LongRange;
034import org.apache.lucene.facet.range.LongRangeFacetCounts;
035import org.apache.lucene.index.DirectoryReader;
036import org.apache.lucene.index.IndexWriter;
037import org.apache.lucene.index.IndexWriterConfig;
038import org.apache.lucene.search.IndexSearcher;
039import org.apache.lucene.search.MatchAllDocsQuery;
040import org.apache.lucene.search.NumericRangeQuery;
041import org.apache.lucene.search.TopDocs;
042import org.apache.lucene.store.Directory;
043import org.apache.lucene.store.RAMDirectory;
044
045
046
047/** Shows simple usage of dynamic range faceting. */
048public class RangeFacetsExample implements Closeable {
049
050  private final Directory indexDir = new RAMDirectory();
051  private IndexSearcher searcher;
052  private final long nowSec = System.currentTimeMillis();
053
054  final LongRange PAST_HOUR = new LongRange("Past hour", nowSec-3600, true, nowSec, true);
055  final LongRange PAST_SIX_HOURS = new LongRange("Past six hours", nowSec-6*3600, true, nowSec, true);
056  final LongRange PAST_DAY = new LongRange("Past day", nowSec-24*3600, true, nowSec, true);
057
058  /** Empty constructor */
059  public RangeFacetsExample() {}
060  
061  /** Build the example index. */
062  public void index() throws IOException {
063    IndexWriter indexWriter = new IndexWriter(indexDir, new IndexWriterConfig(FacetExamples.EXAMPLES_VER, 
064        new WhitespaceAnalyzer(FacetExamples.EXAMPLES_VER)));
065
066    // Add documents with a fake timestamp, 1000 sec before
067    // "now", 2000 sec before "now", ...:
068    for(int i=0;i<100;i++) {
069      Document doc = new Document();
070      long then = nowSec - i * 1000;
071      // Add as doc values field, so we can compute range facets:
072      doc.add(new NumericDocValuesField("timestamp", then));
073      // Add as numeric field so we can drill-down:
074      doc.add(new LongField("timestamp", then, Field.Store.NO));
075      indexWriter.addDocument(doc);
076    }
077
078    // Open near-real-time searcher
079    searcher = new IndexSearcher(DirectoryReader.open(indexWriter, true));
080    indexWriter.close();
081  }
082
083  private FacetsConfig getConfig() {
084    return new FacetsConfig();
085  }
086
087  /** User runs a query and counts facets. */
088  public FacetResult search() throws IOException {
089
090    // Aggregates the facet counts
091    FacetsCollector fc = new FacetsCollector();
092
093    // MatchAllDocsQuery is for "browsing" (counts facets
094    // for all non-deleted docs in the index); normally
095    // you'd use a "normal" query:
096    FacetsCollector.search(searcher, new MatchAllDocsQuery(), 10, fc);
097
098    Facets facets = new LongRangeFacetCounts("timestamp", fc,
099                                             PAST_HOUR,
100                                             PAST_SIX_HOURS,
101                                             PAST_DAY);
102    return facets.getTopChildren(10, "timestamp");
103  }
104  
105  /** User drills down on the specified range. */
106  public TopDocs drillDown(LongRange range) throws IOException {
107
108    // Passing no baseQuery means we drill down on all
109    // documents ("browse only"):
110    DrillDownQuery q = new DrillDownQuery(getConfig());
111
112    q.add("timestamp", NumericRangeQuery.newLongRange("timestamp", range.min, range.max, range.minInclusive, range.maxInclusive));
113
114    return searcher.search(q, 10);
115  }
116
117  @Override
118  public void close() throws IOException {
119    searcher.getIndexReader().close();
120    indexDir.close();
121  }
122
123  /** Runs the search and drill-down examples and prints the results. */
124  @SuppressWarnings("unchecked")
125  public static void main(String[] args) throws Exception {
126    RangeFacetsExample example = new RangeFacetsExample();
127    example.index();
128
129    System.out.println("Facet counting example:");
130    System.out.println("-----------------------");
131    System.out.println(example.search());
132
133    System.out.println("\n");
134    System.out.println("Facet drill-down example (timestamp/Past six hours):");
135    System.out.println("---------------------------------------------");
136    TopDocs hits = example.drillDown(example.PAST_SIX_HOURS);
137    System.out.println(hits.totalHits + " totalHits");
138
139    example.close();
140  }
141}