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.document.NumericDocValuesField; 029import org.apache.lucene.expressions.Expression; 030import org.apache.lucene.expressions.SimpleBindings; 031import org.apache.lucene.expressions.js.JavascriptCompiler; 032import org.apache.lucene.facet.DrillDownQuery; 033import org.apache.lucene.facet.DrillSideways; 034import org.apache.lucene.facet.FacetResult; 035import org.apache.lucene.facet.Facets; 036import org.apache.lucene.facet.FacetsCollector; 037import org.apache.lucene.facet.FacetsConfig; 038import org.apache.lucene.facet.range.DoubleRange; 039import org.apache.lucene.facet.range.DoubleRangeFacetCounts; 040import org.apache.lucene.facet.taxonomy.TaxonomyReader; 041import org.apache.lucene.index.DirectoryReader; 042import org.apache.lucene.index.IndexWriter; 043import org.apache.lucene.index.IndexWriterConfig; 044import org.apache.lucene.index.IndexWriterConfig.OpenMode; 045import org.apache.lucene.queries.function.ValueSource; 046import org.apache.lucene.search.BooleanClause; 047import org.apache.lucene.search.BooleanQuery; 048import org.apache.lucene.search.Filter; 049import org.apache.lucene.search.IndexSearcher; 050import org.apache.lucene.search.MatchAllDocsQuery; 051import org.apache.lucene.search.NumericRangeQuery; 052import org.apache.lucene.search.QueryWrapperFilter; 053import org.apache.lucene.search.SortField; 054import org.apache.lucene.search.TopDocs; 055import org.apache.lucene.store.Directory; 056import org.apache.lucene.store.RAMDirectory; 057import org.apache.lucene.util.SloppyMath; 058 059/** Shows simple usage of dynamic range faceting, using the 060 * expressions module to calculate distance. */ 061public class DistanceFacetsExample implements Closeable { 062 063 final DoubleRange ONE_KM = new DoubleRange("< 1 km", 0.0, true, 1.0, false); 064 final DoubleRange TWO_KM = new DoubleRange("< 2 km", 0.0, true, 2.0, false); 065 final DoubleRange FIVE_KM = new DoubleRange("< 5 km", 0.0, true, 5.0, false); 066 final DoubleRange TEN_KM = new DoubleRange("< 10 km", 0.0, true, 10.0, false); 067 068 private final Directory indexDir = new RAMDirectory(); 069 private IndexSearcher searcher; 070 private final FacetsConfig config = new FacetsConfig(); 071 072 /** The "home" latitude. */ 073 public final static double ORIGIN_LATITUDE = 40.7143528; 074 075 /** The "home" longitude. */ 076 public final static double ORIGIN_LONGITUDE = -74.0059731; 077 078 /** Radius of the Earth in KM 079 * 080 * NOTE: this is approximate, because the earth is a bit 081 * wider at the equator than the poles. See 082 * http://en.wikipedia.org/wiki/Earth_radius */ 083 public final static double EARTH_RADIUS_KM = 6371.01; 084 085 /** Empty constructor */ 086 public DistanceFacetsExample() {} 087 088 /** Build the example index. */ 089 public void index() throws IOException { 090 IndexWriter writer = new IndexWriter(indexDir, new IndexWriterConfig( 091 new WhitespaceAnalyzer()).setOpenMode(OpenMode.CREATE)); 092 093 // TODO: we could index in radians instead ... saves all the conversions in getBoundingBoxFilter 094 095 // Add documents with latitude/longitude location: 096 // we index these both as DoubleFields (for bounding box/ranges) and as NumericDocValuesFields (for scoring) 097 Document doc = new Document(); 098 doc.add(new DoubleField("latitude", 40.759011, Field.Store.NO)); 099 doc.add(new NumericDocValuesField("latitude", Double.doubleToRawLongBits(40.759011))); 100 doc.add(new DoubleField("longitude", -73.9844722, Field.Store.NO)); 101 doc.add(new NumericDocValuesField("longitude", Double.doubleToRawLongBits(-73.9844722))); 102 writer.addDocument(doc); 103 104 doc = new Document(); 105 doc.add(new DoubleField("latitude", 40.718266, Field.Store.NO)); 106 doc.add(new NumericDocValuesField("latitude", Double.doubleToRawLongBits(40.718266))); 107 doc.add(new DoubleField("longitude", -74.007819, Field.Store.NO)); 108 doc.add(new NumericDocValuesField("longitude", Double.doubleToRawLongBits(-74.007819))); 109 writer.addDocument(doc); 110 111 doc = new Document(); 112 doc.add(new DoubleField("latitude", 40.7051157, Field.Store.NO)); 113 doc.add(new NumericDocValuesField("latitude", Double.doubleToRawLongBits(40.7051157))); 114 doc.add(new DoubleField("longitude", -74.0088305, Field.Store.NO)); 115 doc.add(new NumericDocValuesField("longitude", Double.doubleToRawLongBits(-74.0088305))); 116 writer.addDocument(doc); 117 118 // Open near-real-time searcher 119 searcher = new IndexSearcher(DirectoryReader.open(writer, true)); 120 writer.close(); 121 } 122 123 private ValueSource getDistanceValueSource() { 124 Expression distance; 125 try { 126 distance = JavascriptCompiler.compile( 127 "haversin(" + ORIGIN_LATITUDE + "," + ORIGIN_LONGITUDE + ",latitude,longitude)"); 128 } catch (ParseException pe) { 129 // Should not happen 130 throw new RuntimeException(pe); 131 } 132 SimpleBindings bindings = new SimpleBindings(); 133 bindings.add(new SortField("latitude", SortField.Type.DOUBLE)); 134 bindings.add(new SortField("longitude", SortField.Type.DOUBLE)); 135 136 return distance.getValueSource(bindings); 137 } 138 139 /** Given a latitude and longitude (in degrees) and the 140 * maximum great circle (surface of the earth) distance, 141 * returns a simple Filter bounding box to "fast match" 142 * candidates. */ 143 public static Filter getBoundingBoxFilter(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 / (SloppyMath.earthDiameter(originLat) / 2.0); 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 f = new BooleanQuery(); 184 185 // Add latitude range filter: 186 f.add(NumericRangeQuery.newDoubleRange("latitude", Math.toDegrees(minLat), Math.toDegrees(maxLat), true, true), 187 BooleanClause.Occur.FILTER); 188 189 // Add longitude range filter: 190 if (minLng > maxLng) { 191 // The bounding box crosses the international date 192 // line: 193 BooleanQuery lonF = new BooleanQuery(); 194 lonF.add(NumericRangeQuery.newDoubleRange("longitude", Math.toDegrees(minLng), null, true, true), 195 BooleanClause.Occur.SHOULD); 196 lonF.add(NumericRangeQuery.newDoubleRange("longitude", null, Math.toDegrees(maxLng), true, true), 197 BooleanClause.Occur.SHOULD); 198 f.add(lonF, BooleanClause.Occur.MUST); 199 } else { 200 f.add(NumericRangeQuery.newDoubleRange("longitude", Math.toDegrees(minLng), Math.toDegrees(maxLng), true, true), 201 BooleanClause.Occur.FILTER); 202 } 203 204 return new QueryWrapperFilter(f); 205 } 206 207 /** User runs a query and counts facets. */ 208 public FacetResult search() throws IOException { 209 210 FacetsCollector fc = new FacetsCollector(); 211 212 searcher.search(new MatchAllDocsQuery(), fc); 213 214 Facets facets = new DoubleRangeFacetCounts("field", getDistanceValueSource(), fc, 215 getBoundingBoxFilter(ORIGIN_LATITUDE, ORIGIN_LONGITUDE, 10.0), 216 ONE_KM, 217 TWO_KM, 218 FIVE_KM, 219 TEN_KM); 220 221 return facets.getTopChildren(10, "field"); 222 } 223 224 /** User drills down on the specified range. */ 225 public TopDocs drillDown(DoubleRange range) throws IOException { 226 227 // Passing no baseQuery means we drill down on all 228 // documents ("browse only"): 229 DrillDownQuery q = new DrillDownQuery(null); 230 final ValueSource vs = getDistanceValueSource(); 231 q.add("field", range.getFilter(getBoundingBoxFilter(ORIGIN_LATITUDE, ORIGIN_LONGITUDE, range.max), vs)); 232 DrillSideways ds = new DrillSideways(searcher, config, (TaxonomyReader) null) { 233 @Override 234 protected Facets buildFacetsResult(FacetsCollector drillDowns, FacetsCollector[] drillSideways, String[] drillSidewaysDims) throws IOException { 235 assert drillSideways.length == 1; 236 return new DoubleRangeFacetCounts("field", vs, drillSideways[0], ONE_KM, TWO_KM, FIVE_KM, TEN_KM); 237 } 238 }; 239 return ds.search(q, 10).hits; 240 } 241 242 @Override 243 public void close() throws IOException { 244 searcher.getIndexReader().close(); 245 indexDir.close(); 246 } 247 248 /** Runs the search and drill-down examples and prints the results. */ 249 public static void main(String[] args) throws Exception { 250 DistanceFacetsExample example = new DistanceFacetsExample(); 251 example.index(); 252 253 System.out.println("Distance facet counting example:"); 254 System.out.println("-----------------------"); 255 System.out.println(example.search()); 256 257 System.out.println("Distance facet drill-down example (field/< 2 km):"); 258 System.out.println("---------------------------------------------"); 259 TopDocs hits = example.drillDown(example.TWO_KM); 260 System.out.println(hits.totalHits + " totalHits"); 261 262 example.close(); 263 } 264}