001package org.apache.lucene.demo.facet; 002 003/* 004 * Licensed to the Apache Software Foundation (ASF) under one or more 005 * contributor license agreements. See the NOTICE file distributed with 006 * this work for additional information regarding copyright ownership. 007 * The ASF licenses this file to You under the Apache License, Version 2.0 008 * (the "License"); you may not use this file except in compliance with 009 * the License. You may obtain a copy of the License at 010 * 011 * http://www.apache.org/licenses/LICENSE-2.0 012 * 013 * Unless required by applicable law or agreed to in writing, software 014 * distributed under the License is distributed on an "AS IS" BASIS, 015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 016 * See the License for the specific language governing permissions and 017 * limitations under the License. 018 */ 019 020import java.io.Closeable; 021import java.io.IOException; 022import java.text.ParseException; 023 024import org.apache.lucene.analysis.core.WhitespaceAnalyzer; 025import org.apache.lucene.document.Document; 026import org.apache.lucene.document.DoubleField; 027import org.apache.lucene.document.Field; 028import org.apache.lucene.expressions.Expression; 029import org.apache.lucene.expressions.SimpleBindings; 030import org.apache.lucene.expressions.js.JavascriptCompiler; 031import org.apache.lucene.facet.DrillDownQuery; 032import org.apache.lucene.facet.DrillSideways; 033import org.apache.lucene.facet.FacetResult; 034import org.apache.lucene.facet.Facets; 035import org.apache.lucene.facet.FacetsCollector; 036import org.apache.lucene.facet.FacetsConfig; 037import org.apache.lucene.facet.range.DoubleRange; 038import org.apache.lucene.facet.range.DoubleRangeFacetCounts; 039import org.apache.lucene.facet.taxonomy.TaxonomyReader; 040import org.apache.lucene.index.DirectoryReader; 041import org.apache.lucene.index.IndexWriter; 042import org.apache.lucene.index.IndexWriterConfig; 043import org.apache.lucene.queries.BooleanFilter; 044import org.apache.lucene.queries.function.ValueSource; 045import org.apache.lucene.search.BooleanClause; 046import org.apache.lucene.search.Filter; 047import org.apache.lucene.search.IndexSearcher; 048import org.apache.lucene.search.MatchAllDocsQuery; 049import org.apache.lucene.search.NumericRangeFilter; 050import org.apache.lucene.search.SortField; 051import org.apache.lucene.search.TopDocs; 052import org.apache.lucene.store.Directory; 053import org.apache.lucene.store.RAMDirectory; 054import org.apache.lucene.util.SloppyMath; 055 056 057 058/** Shows simple usage of dynamic range faceting, using the 059 * expressions module to calculate distance. */ 060public class DistanceFacetsExample implements Closeable { 061 062 final DoubleRange ONE_KM = new DoubleRange("< 1 km", 0.0, true, 1.0, false); 063 final DoubleRange TWO_KM = new DoubleRange("< 2 km", 0.0, true, 2.0, false); 064 final DoubleRange FIVE_KM = new DoubleRange("< 5 km", 0.0, true, 5.0, false); 065 final DoubleRange TEN_KM = new DoubleRange("< 10 km", 0.0, true, 10.0, false); 066 067 private final Directory indexDir = new RAMDirectory(); 068 private IndexSearcher searcher; 069 private final FacetsConfig config = new FacetsConfig(); 070 071 /** The "home" latitude. */ 072 public final static double ORIGIN_LATITUDE = 40.7143528; 073 074 /** The "home" longitude. */ 075 public final static double ORIGIN_LONGITUDE = -74.0059731; 076 077 /** Radius of the Earth in KM 078 * 079 * NOTE: this is approximate, because the earth is a bit 080 * wider at the equator than the poles. See 081 * http://en.wikipedia.org/wiki/Earth_radius */ 082 public final static double EARTH_RADIUS_KM = 6371.01; 083 084 /** Empty constructor */ 085 public DistanceFacetsExample() {} 086 087 /** Build the example index. */ 088 public void index() throws IOException { 089 IndexWriter writer = new IndexWriter(indexDir, new IndexWriterConfig(FacetExamples.EXAMPLES_VER, 090 new WhitespaceAnalyzer(FacetExamples.EXAMPLES_VER))); 091 092 // TODO: we could index in radians instead ... saves all the conversions in getBoundingBoxFilter 093 094 // Add documents with latitude/longitude location: 095 Document doc = new Document(); 096 doc.add(new DoubleField("latitude", 40.759011, Field.Store.NO)); 097 doc.add(new DoubleField("longitude", -73.9844722, Field.Store.NO)); 098 writer.addDocument(doc); 099 100 doc = new Document(); 101 doc.add(new DoubleField("latitude", 40.718266, Field.Store.NO)); 102 doc.add(new DoubleField("longitude", -74.007819, Field.Store.NO)); 103 writer.addDocument(doc); 104 105 doc = new Document(); 106 doc.add(new DoubleField("latitude", 40.7051157, Field.Store.NO)); 107 doc.add(new DoubleField("longitude", -74.0088305, Field.Store.NO)); 108 writer.addDocument(doc); 109 110 // Open near-real-time searcher 111 searcher = new IndexSearcher(DirectoryReader.open(writer, true)); 112 writer.close(); 113 } 114 115 private ValueSource getDistanceValueSource() { 116 Expression distance; 117 try { 118 distance = JavascriptCompiler.compile( 119 "haversin(" + ORIGIN_LATITUDE + "," + ORIGIN_LONGITUDE + ",latitude,longitude)"); 120 } catch (ParseException pe) { 121 // Should not happen 122 throw new RuntimeException(pe); 123 } 124 SimpleBindings bindings = new SimpleBindings(); 125 bindings.add(new SortField("latitude", SortField.Type.DOUBLE)); 126 bindings.add(new SortField("longitude", SortField.Type.DOUBLE)); 127 128 return distance.getValueSource(bindings); 129 } 130 131 /** Given a latitude and longitude (in degrees) and the 132 * maximum great circle (surface of the earth) distance, 133 * returns a simple Filter bounding box to "fast match" 134 * candidates. */ 135 public static Filter getBoundingBoxFilter(double originLat, double originLng, double maxDistanceKM) { 136 137 // Basic bounding box geo math from 138 // http://JanMatuschek.de/LatitudeLongitudeBoundingCoordinates, 139 // licensed under creative commons 3.0: 140 // http://creativecommons.org/licenses/by/3.0 141 142 // TODO: maybe switch to recursive prefix tree instead 143 // (in lucene/spatial)? It should be more efficient 144 // since it's a 2D trie... 145 146 // Degrees -> Radians: 147 double originLatRadians = Math.toRadians(originLat); 148 double originLngRadians = Math.toRadians(originLng); 149 150 double angle = maxDistanceKM / (SloppyMath.earthDiameter(originLat) / 2.0); 151 152 double minLat = originLatRadians - angle; 153 double maxLat = originLatRadians + angle; 154 155 double minLng; 156 double maxLng; 157 if (minLat > Math.toRadians(-90) && maxLat < Math.toRadians(90)) { 158 double delta = Math.asin(Math.sin(angle)/Math.cos(originLatRadians)); 159 minLng = originLngRadians - delta; 160 if (minLng < Math.toRadians(-180)) { 161 minLng += 2 * Math.PI; 162 } 163 maxLng = originLngRadians + delta; 164 if (maxLng > Math.toRadians(180)) { 165 maxLng -= 2 * Math.PI; 166 } 167 } else { 168 // The query includes a pole! 169 minLat = Math.max(minLat, Math.toRadians(-90)); 170 maxLat = Math.min(maxLat, Math.toRadians(90)); 171 minLng = Math.toRadians(-180); 172 maxLng = Math.toRadians(180); 173 } 174 175 BooleanFilter f = new BooleanFilter(); 176 177 // Add latitude range filter: 178 f.add(NumericRangeFilter.newDoubleRange("latitude", Math.toDegrees(minLat), Math.toDegrees(maxLat), true, true), 179 BooleanClause.Occur.MUST); 180 181 // Add longitude range filter: 182 if (minLng > maxLng) { 183 // The bounding box crosses the international date 184 // line: 185 BooleanFilter lonF = new BooleanFilter(); 186 lonF.add(NumericRangeFilter.newDoubleRange("longitude", Math.toDegrees(minLng), null, true, true), 187 BooleanClause.Occur.SHOULD); 188 lonF.add(NumericRangeFilter.newDoubleRange("longitude", null, Math.toDegrees(maxLng), true, true), 189 BooleanClause.Occur.SHOULD); 190 f.add(lonF, BooleanClause.Occur.MUST); 191 } else { 192 f.add(NumericRangeFilter.newDoubleRange("longitude", Math.toDegrees(minLng), Math.toDegrees(maxLng), true, true), 193 BooleanClause.Occur.MUST); 194 } 195 196 return f; 197 } 198 199 /** User runs a query and counts facets. */ 200 public FacetResult search() throws IOException { 201 202 FacetsCollector fc = new FacetsCollector(); 203 204 searcher.search(new MatchAllDocsQuery(), fc); 205 206 Facets facets = new DoubleRangeFacetCounts("field", getDistanceValueSource(), fc, 207 getBoundingBoxFilter(ORIGIN_LATITUDE, ORIGIN_LONGITUDE, 10.0), 208 ONE_KM, 209 TWO_KM, 210 FIVE_KM, 211 TEN_KM); 212 213 return facets.getTopChildren(10, "field"); 214 } 215 216 /** User drills down on the specified range. */ 217 public TopDocs drillDown(DoubleRange range) throws IOException { 218 219 // Passing no baseQuery means we drill down on all 220 // documents ("browse only"): 221 DrillDownQuery q = new DrillDownQuery(null); 222 final ValueSource vs = getDistanceValueSource(); 223 q.add("field", range.getFilter(getBoundingBoxFilter(ORIGIN_LATITUDE, ORIGIN_LONGITUDE, range.max), vs)); 224 DrillSideways ds = new DrillSideways(searcher, config, (TaxonomyReader) null) { 225 @Override 226 protected Facets buildFacetsResult(FacetsCollector drillDowns, FacetsCollector[] drillSideways, String[] drillSidewaysDims) throws IOException { 227 assert drillSideways.length == 1; 228 return new DoubleRangeFacetCounts("field", vs, drillSideways[0], ONE_KM, TWO_KM, FIVE_KM, TEN_KM); 229 } 230 }; 231 return ds.search(q, 10).hits; 232 } 233 234 @Override 235 public void close() throws IOException { 236 searcher.getIndexReader().close(); 237 indexDir.close(); 238 } 239 240 /** Runs the search and drill-down examples and prints the results. */ 241 @SuppressWarnings("unchecked") 242 public static void main(String[] args) throws Exception { 243 DistanceFacetsExample example = new DistanceFacetsExample(); 244 example.index(); 245 246 System.out.println("Distance facet counting example:"); 247 System.out.println("-----------------------"); 248 System.out.println(example.search()); 249 250 System.out.println("\n"); 251 System.out.println("Distance facet drill-down example (field/< 2 km):"); 252 System.out.println("---------------------------------------------"); 253 TopDocs hits = example.drillDown(example.TWO_KM); 254 System.out.println(hits.totalHits + " totalHits"); 255 256 example.close(); 257 } 258}