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 java.text.ParseException;
022import org.apache.lucene.analysis.core.WhitespaceAnalyzer;
023import org.apache.lucene.document.Document;
024import org.apache.lucene.document.DoublePoint;
025import org.apache.lucene.document.NumericDocValuesField;
026import org.apache.lucene.expressions.Expression;
027import org.apache.lucene.expressions.SimpleBindings;
028import org.apache.lucene.expressions.js.JavascriptCompiler;
029import org.apache.lucene.facet.DrillDownQuery;
030import org.apache.lucene.facet.DrillSideways;
031import org.apache.lucene.facet.FacetResult;
032import org.apache.lucene.facet.Facets;
033import org.apache.lucene.facet.FacetsCollector;
034import org.apache.lucene.facet.FacetsConfig;
035import org.apache.lucene.facet.range.DoubleRange;
036import org.apache.lucene.facet.range.DoubleRangeFacetCounts;
037import org.apache.lucene.facet.taxonomy.TaxonomyReader;
038import org.apache.lucene.index.DirectoryReader;
039import org.apache.lucene.index.IndexWriter;
040import org.apache.lucene.index.IndexWriterConfig;
041import org.apache.lucene.index.IndexWriterConfig.OpenMode;
042import org.apache.lucene.search.BooleanClause;
043import org.apache.lucene.search.BooleanQuery;
044import org.apache.lucene.search.DoubleValuesSource;
045import org.apache.lucene.search.IndexSearcher;
046import org.apache.lucene.search.MatchAllDocsQuery;
047import org.apache.lucene.search.Query;
048import org.apache.lucene.search.TopDocs;
049import org.apache.lucene.store.ByteBuffersDirectory;
050import org.apache.lucene.store.Directory;
051
052/**
053 * Shows simple usage of dynamic range faceting, using the expressions module to calculate distance.
054 */
055public class DistanceFacetsExample implements Closeable {
056
057  final DoubleRange ONE_KM = new DoubleRange("< 1 km", 0.0, true, 1.0, false);
058  final DoubleRange TWO_KM = new DoubleRange("< 2 km", 0.0, true, 2.0, false);
059  final DoubleRange FIVE_KM = new DoubleRange("< 5 km", 0.0, true, 5.0, false);
060  final DoubleRange TEN_KM = new DoubleRange("< 10 km", 0.0, true, 10.0, false);
061
062  private final Directory indexDir = new ByteBuffersDirectory();
063  private IndexSearcher searcher;
064  private final FacetsConfig config = new FacetsConfig();
065
066  /** The "home" latitude. */
067  public static final double ORIGIN_LATITUDE = 40.7143528;
068
069  /** The "home" longitude. */
070  public static final double ORIGIN_LONGITUDE = -74.0059731;
071
072  /**
073   * Mean radius of the Earth in KM
074   *
075   * <p>NOTE: this is approximate, because the earth is a bit wider at the equator than the poles.
076   * See http://en.wikipedia.org/wiki/Earth_radius
077   */
078  // see http://earth-info.nga.mil/GandG/publications/tr8350.2/wgs84fin.pdf
079  public static final double EARTH_RADIUS_KM = 6_371.0087714;
080
081  /** Empty constructor */
082  public DistanceFacetsExample() {}
083
084  /** Build the example index. */
085  public void index() throws IOException {
086    IndexWriter writer =
087        new IndexWriter(
088            indexDir, new IndexWriterConfig(new WhitespaceAnalyzer()).setOpenMode(OpenMode.CREATE));
089
090    // TODO: we could index in radians instead ... saves all the conversions in getBoundingBoxFilter
091
092    // Add documents with latitude/longitude location:
093    // we index these both as DoublePoints (for bounding box/ranges) and as NumericDocValuesFields
094    // (for scoring)
095    Document doc = new Document();
096    doc.add(new DoublePoint("latitude", 40.759011));
097    doc.add(new NumericDocValuesField("latitude", Double.doubleToRawLongBits(40.759011)));
098    doc.add(new DoublePoint("longitude", -73.9844722));
099    doc.add(new NumericDocValuesField("longitude", Double.doubleToRawLongBits(-73.9844722)));
100    writer.addDocument(doc);
101
102    doc = new Document();
103    doc.add(new DoublePoint("latitude", 40.718266));
104    doc.add(new NumericDocValuesField("latitude", Double.doubleToRawLongBits(40.718266)));
105    doc.add(new DoublePoint("longitude", -74.007819));
106    doc.add(new NumericDocValuesField("longitude", Double.doubleToRawLongBits(-74.007819)));
107    writer.addDocument(doc);
108
109    doc = new Document();
110    doc.add(new DoublePoint("latitude", 40.7051157));
111    doc.add(new NumericDocValuesField("latitude", Double.doubleToRawLongBits(40.7051157)));
112    doc.add(new DoublePoint("longitude", -74.0088305));
113    doc.add(new NumericDocValuesField("longitude", Double.doubleToRawLongBits(-74.0088305)));
114    writer.addDocument(doc);
115
116    // Open near-real-time searcher
117    searcher = new IndexSearcher(DirectoryReader.open(writer));
118    writer.close();
119  }
120
121  private DoubleValuesSource getDistanceValueSource() {
122    Expression distance;
123    try {
124      distance =
125          JavascriptCompiler.compile(
126              "haversin(" + ORIGIN_LATITUDE + "," + ORIGIN_LONGITUDE + ",latitude,longitude)");
127    } catch (ParseException pe) {
128      // Should not happen
129      throw new RuntimeException(pe);
130    }
131    SimpleBindings bindings = new SimpleBindings();
132    bindings.add("latitude", DoubleValuesSource.fromDoubleField("latitude"));
133    bindings.add("longitude", DoubleValuesSource.fromDoubleField("longitude"));
134
135    return distance.getDoubleValuesSource(bindings);
136  }
137
138  /**
139   * Given a latitude and longitude (in degrees) and the maximum great circle (surface of the earth)
140   * distance, returns a simple Filter bounding box to "fast match" candidates.
141   */
142  public static Query getBoundingBoxQuery(
143      double originLat, double originLng, double maxDistanceKM) {
144
145    // Basic bounding box geo math from
146    // http://JanMatuschek.de/LatitudeLongitudeBoundingCoordinates,
147    // licensed under creative commons 3.0:
148    // http://creativecommons.org/licenses/by/3.0
149
150    // TODO: maybe switch to recursive prefix tree instead
151    // (in lucene/spatial)?  It should be more efficient
152    // since it's a 2D trie...
153
154    // Degrees -> Radians:
155    double originLatRadians = Math.toRadians(originLat);
156    double originLngRadians = Math.toRadians(originLng);
157
158    double angle = maxDistanceKM / EARTH_RADIUS_KM;
159
160    double minLat = originLatRadians - angle;
161    double maxLat = originLatRadians + angle;
162
163    double minLng;
164    double maxLng;
165    if (minLat > Math.toRadians(-90) && maxLat < Math.toRadians(90)) {
166      double delta = Math.asin(Math.sin(angle) / Math.cos(originLatRadians));
167      minLng = originLngRadians - delta;
168      if (minLng < Math.toRadians(-180)) {
169        minLng += 2 * Math.PI;
170      }
171      maxLng = originLngRadians + delta;
172      if (maxLng > Math.toRadians(180)) {
173        maxLng -= 2 * Math.PI;
174      }
175    } else {
176      // The query includes a pole!
177      minLat = Math.max(minLat, Math.toRadians(-90));
178      maxLat = Math.min(maxLat, Math.toRadians(90));
179      minLng = Math.toRadians(-180);
180      maxLng = Math.toRadians(180);
181    }
182
183    BooleanQuery.Builder f = new BooleanQuery.Builder();
184
185    // Add latitude range filter:
186    f.add(
187        DoublePoint.newRangeQuery("latitude", Math.toDegrees(minLat), Math.toDegrees(maxLat)),
188        BooleanClause.Occur.FILTER);
189
190    // Add longitude range filter:
191    if (minLng > maxLng) {
192      // The bounding box crosses the international date
193      // line:
194      BooleanQuery.Builder lonF = new BooleanQuery.Builder();
195      lonF.add(
196          DoublePoint.newRangeQuery("longitude", Math.toDegrees(minLng), Double.POSITIVE_INFINITY),
197          BooleanClause.Occur.SHOULD);
198      lonF.add(
199          DoublePoint.newRangeQuery("longitude", Double.NEGATIVE_INFINITY, Math.toDegrees(maxLng)),
200          BooleanClause.Occur.SHOULD);
201      f.add(lonF.build(), BooleanClause.Occur.MUST);
202    } else {
203      f.add(
204          DoublePoint.newRangeQuery("longitude", Math.toDegrees(minLng), Math.toDegrees(maxLng)),
205          BooleanClause.Occur.FILTER);
206    }
207
208    return f.build();
209  }
210
211  /** User runs a query and counts facets. */
212  public FacetResult search() throws IOException {
213
214    FacetsCollector fc = new FacetsCollector();
215
216    searcher.search(new MatchAllDocsQuery(), fc);
217
218    Facets facets =
219        new DoubleRangeFacetCounts(
220            "field",
221            getDistanceValueSource(),
222            fc,
223            getBoundingBoxQuery(ORIGIN_LATITUDE, ORIGIN_LONGITUDE, 10.0),
224            ONE_KM,
225            TWO_KM,
226            FIVE_KM,
227            TEN_KM);
228
229    return facets.getTopChildren(10, "field");
230  }
231
232  /** User drills down on the specified range. */
233  public TopDocs drillDown(DoubleRange range) throws IOException {
234
235    // Passing no baseQuery means we drill down on all
236    // documents ("browse only"):
237    DrillDownQuery q = new DrillDownQuery(null);
238    final DoubleValuesSource vs = getDistanceValueSource();
239    q.add(
240        "field",
241        range.getQuery(getBoundingBoxQuery(ORIGIN_LATITUDE, ORIGIN_LONGITUDE, range.max), vs));
242    DrillSideways ds =
243        new DrillSideways(searcher, config, (TaxonomyReader) null) {
244          @Override
245          protected Facets buildFacetsResult(
246              FacetsCollector drillDowns,
247              FacetsCollector[] drillSideways,
248              String[] drillSidewaysDims)
249              throws IOException {
250            assert drillSideways.length == 1;
251            return new DoubleRangeFacetCounts(
252                "field", vs, drillSideways[0], ONE_KM, TWO_KM, FIVE_KM, TEN_KM);
253          }
254        };
255    return ds.search(q, 10).hits;
256  }
257
258  @Override
259  public void close() throws IOException {
260    searcher.getIndexReader().close();
261    indexDir.close();
262  }
263
264  /** Runs the search and drill-down examples and prints the results. */
265  public static void main(String[] args) throws Exception {
266    DistanceFacetsExample example = new DistanceFacetsExample();
267    example.index();
268
269    System.out.println("Distance facet counting example:");
270    System.out.println("-----------------------");
271    System.out.println(example.search());
272
273    System.out.println("Distance facet drill-down example (field/< 2 km):");
274    System.out.println("---------------------------------------------");
275    TopDocs hits = example.drillDown(example.TWO_KM);
276    System.out.println(hits.totalHits + " totalHits");
277
278    example.close();
279  }
280}