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