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