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