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 // TODO: Would be nice to augment this example with documents containing multiple "locations", 122 // adding the ability to compute distance facets for the multi-valued case (see LUCENE-10245) 123 private DoubleValuesSource getDistanceValueSource() { 124 Expression distance; 125 try { 126 distance = 127 JavascriptCompiler.compile( 128 "haversin(" + ORIGIN_LATITUDE + "," + ORIGIN_LONGITUDE + ",latitude,longitude)"); 129 } catch (ParseException pe) { 130 // Should not happen 131 throw new RuntimeException(pe); 132 } 133 SimpleBindings bindings = new SimpleBindings(); 134 bindings.add("latitude", DoubleValuesSource.fromDoubleField("latitude")); 135 bindings.add("longitude", DoubleValuesSource.fromDoubleField("longitude")); 136 137 return distance.getDoubleValuesSource(bindings); 138 } 139 140 /** 141 * Given a latitude and longitude (in degrees) and the maximum great circle (surface of the earth) 142 * distance, returns a simple Filter bounding box to "fast match" candidates. 143 */ 144 public static Query getBoundingBoxQuery( 145 double originLat, double originLng, double maxDistanceKM) { 146 147 // Basic bounding box geo math from 148 // http://JanMatuschek.de/LatitudeLongitudeBoundingCoordinates, 149 // licensed under creative commons 3.0: 150 // http://creativecommons.org/licenses/by/3.0 151 152 // TODO: maybe switch to recursive prefix tree instead 153 // (in lucene/spatial)? It should be more efficient 154 // since it's a 2D trie... 155 156 // Degrees -> Radians: 157 double originLatRadians = Math.toRadians(originLat); 158 double originLngRadians = Math.toRadians(originLng); 159 160 double angle = maxDistanceKM / EARTH_RADIUS_KM; 161 162 double minLat = originLatRadians - angle; 163 double maxLat = originLatRadians + angle; 164 165 double minLng; 166 double maxLng; 167 if (minLat > Math.toRadians(-90) && maxLat < Math.toRadians(90)) { 168 double delta = Math.asin(Math.sin(angle) / Math.cos(originLatRadians)); 169 minLng = originLngRadians - delta; 170 if (minLng < Math.toRadians(-180)) { 171 minLng += 2 * Math.PI; 172 } 173 maxLng = originLngRadians + delta; 174 if (maxLng > Math.toRadians(180)) { 175 maxLng -= 2 * Math.PI; 176 } 177 } else { 178 // The query includes a pole! 179 minLat = Math.max(minLat, Math.toRadians(-90)); 180 maxLat = Math.min(maxLat, Math.toRadians(90)); 181 minLng = Math.toRadians(-180); 182 maxLng = Math.toRadians(180); 183 } 184 185 BooleanQuery.Builder f = new BooleanQuery.Builder(); 186 187 // Add latitude range filter: 188 f.add( 189 DoublePoint.newRangeQuery("latitude", Math.toDegrees(minLat), Math.toDegrees(maxLat)), 190 BooleanClause.Occur.FILTER); 191 192 // Add longitude range filter: 193 if (minLng > maxLng) { 194 // The bounding box crosses the international date 195 // line: 196 BooleanQuery.Builder lonF = new BooleanQuery.Builder(); 197 lonF.add( 198 DoublePoint.newRangeQuery("longitude", Math.toDegrees(minLng), Double.POSITIVE_INFINITY), 199 BooleanClause.Occur.SHOULD); 200 lonF.add( 201 DoublePoint.newRangeQuery("longitude", Double.NEGATIVE_INFINITY, Math.toDegrees(maxLng)), 202 BooleanClause.Occur.SHOULD); 203 f.add(lonF.build(), BooleanClause.Occur.MUST); 204 } else { 205 f.add( 206 DoublePoint.newRangeQuery("longitude", Math.toDegrees(minLng), Math.toDegrees(maxLng)), 207 BooleanClause.Occur.FILTER); 208 } 209 210 return f.build(); 211 } 212 213 /** User runs a query and counts facets. */ 214 public FacetResult search() throws IOException { 215 216 FacetsCollector fc = new FacetsCollector(); 217 218 searcher.search(new MatchAllDocsQuery(), fc); 219 220 Facets facets = 221 new DoubleRangeFacetCounts( 222 "field", 223 getDistanceValueSource(), 224 fc, 225 getBoundingBoxQuery(ORIGIN_LATITUDE, ORIGIN_LONGITUDE, 10.0), 226 ONE_KM, 227 TWO_KM, 228 FIVE_KM, 229 TEN_KM); 230 231 return facets.getTopChildren(10, "field"); 232 } 233 234 /** User drills down on the specified range. */ 235 public TopDocs drillDown(DoubleRange range) throws IOException { 236 237 // Passing no baseQuery means we drill down on all 238 // documents ("browse only"): 239 DrillDownQuery q = new DrillDownQuery(null); 240 final DoubleValuesSource vs = getDistanceValueSource(); 241 q.add( 242 "field", 243 range.getQuery(getBoundingBoxQuery(ORIGIN_LATITUDE, ORIGIN_LONGITUDE, range.max), vs)); 244 DrillSideways ds = 245 new DrillSideways(searcher, config, (TaxonomyReader) null) { 246 @Override 247 protected Facets buildFacetsResult( 248 FacetsCollector drillDowns, 249 FacetsCollector[] drillSideways, 250 String[] drillSidewaysDims) 251 throws IOException { 252 assert drillSideways.length == 1; 253 return new DoubleRangeFacetCounts( 254 "field", vs, drillSideways[0], ONE_KM, TWO_KM, FIVE_KM, TEN_KM); 255 } 256 }; 257 return ds.search(q, 10).hits; 258 } 259 260 @Override 261 public void close() throws IOException { 262 searcher.getIndexReader().close(); 263 indexDir.close(); 264 } 265 266 /** Runs the search and drill-down examples and prints the results. */ 267 public static void main(String[] args) throws Exception { 268 DistanceFacetsExample example = new DistanceFacetsExample(); 269 example.index(); 270 271 System.out.println("Distance facet counting example:"); 272 System.out.println("-----------------------"); 273 System.out.println(example.search()); 274 275 System.out.println("Distance facet drill-down example (field/< 2 km):"); 276 System.out.println("---------------------------------------------"); 277 TopDocs hits = example.drillDown(example.TWO_KM); 278 System.out.println(hits.totalHits + " totalHits"); 279 280 example.close(); 281 } 282}