Java Code Examples for org.apache.lucene.geo.GeoEncodingUtils

The following examples show how to use org.apache.lucene.geo.GeoEncodingUtils. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: crate   Source File: GeoPointColumnReference.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Point value() {
    try {
        if (values.advanceExact(docId)) {
            switch (values.docValueCount()) {
                case 1:
                    long encoded = values.nextValue();
                    return new PointImpl(
                        GeoEncodingUtils.decodeLongitude((int) encoded),
                        GeoEncodingUtils.decodeLatitude((int) (encoded >>> 32)),
                        JtsSpatialContext.GEO
                    );

                default:
                    throw new GroupByOnArrayUnsupportedException(columnName);
            }
        } else {
            return null;
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 2
Source Project: lucene-solr   Source File: LatLonShapeQuery.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Relation relateRangeBBoxToQuery(int minXOffset, int minYOffset, byte[] minTriangle,
                                          int maxXOffset, int maxYOffset, byte[] maxTriangle) {

  double minLat = GeoEncodingUtils.decodeLatitude(NumericUtils.sortableBytesToInt(minTriangle, minYOffset));
  double minLon = GeoEncodingUtils.decodeLongitude(NumericUtils.sortableBytesToInt(minTriangle, minXOffset));
  double maxLat = GeoEncodingUtils.decodeLatitude(NumericUtils.sortableBytesToInt(maxTriangle, maxYOffset));
  double maxLon = GeoEncodingUtils.decodeLongitude(NumericUtils.sortableBytesToInt(maxTriangle, maxXOffset));

  // check internal node against query
  return component2D.relate(minLon, maxLon, minLat, maxLat);
}
 
Example 3
private double getDistanceKeyFromEncoded(long encoded) {
  int latitudeBits = (int)(encoded >> 32);
  int longitudeBits = (int)(encoded & 0xFFFFFFFF);
  double lat = GeoEncodingUtils.decodeLatitude(latitudeBits);
  double lon = GeoEncodingUtils.decodeLongitude(longitudeBits);
  return SloppyMath.haversinSortKey(originLat, originLon, lat, lon);
}
 
Example 4
Source Project: lucene-solr   Source File: LatLonDocValuesBoxQuery.java    License: Apache License 2.0 5 votes vote down vote up
LatLonDocValuesBoxQuery(String field, double minLatitude, double maxLatitude, double minLongitude, double maxLongitude) {
  GeoUtils.checkLatitude(minLatitude);
  GeoUtils.checkLatitude(maxLatitude);
  GeoUtils.checkLongitude(minLongitude);
  GeoUtils.checkLongitude(maxLongitude);
  if (field == null) {
    throw new IllegalArgumentException("field must not be null");
  }
  this.field = field;
  this.crossesDateline = minLongitude > maxLongitude; // make sure to compute this before rounding
  this.minLatitude = GeoEncodingUtils.encodeLatitudeCeil(minLatitude);
  this.maxLatitude = GeoEncodingUtils.encodeLatitude(maxLatitude);
  this.minLongitude = GeoEncodingUtils.encodeLongitudeCeil(minLongitude);
  this.maxLongitude = GeoEncodingUtils.encodeLongitude(maxLongitude);
}
 
Example 5
Source Project: lucene-solr   Source File: LatLonDocValuesBoxQuery.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String toString(String field) {
  StringBuilder sb = new StringBuilder();
  if (!this.field.equals(field)) {
    sb.append(this.field);
    sb.append(':');
  }
  sb.append("box(minLat=").append(GeoEncodingUtils.decodeLatitude(minLatitude));
  sb.append(", maxLat=").append(GeoEncodingUtils.decodeLatitude(maxLatitude));
  sb.append(", minLon=").append(GeoEncodingUtils.decodeLongitude(minLongitude));
  sb.append(", maxLon=").append(GeoEncodingUtils.decodeLongitude(maxLongitude));
  return sb.append(")").toString();
}
 
Example 6
Source Project: lucene-solr   Source File: TestLatLonShape.java    License: Apache License 2.0 5 votes vote down vote up
public void testIndexAndQuerySamePolygon() throws Exception {
  Directory dir = newDirectory();
  RandomIndexWriter w = new RandomIndexWriter(random(), dir);
  Document doc = new Document();
  Polygon polygon;
  while(true) {
    try {
      polygon = GeoTestUtil.nextPolygon();
      // quantize the polygon
      double[] lats = new double[polygon.numPoints()];
      double[] lons = new double[polygon.numPoints()];
      for (int i = 0; i < polygon.numPoints(); i++) {
        lats[i] = GeoEncodingUtils.decodeLatitude(GeoEncodingUtils.encodeLatitude(polygon.getPolyLat(i)));
        lons[i] = GeoEncodingUtils.decodeLongitude(GeoEncodingUtils.encodeLongitude(polygon.getPolyLon(i)));
      }
      polygon = new Polygon(lats, lons);
      Tessellator.tessellate(polygon);
      break;
    } catch (Exception e) {
      // invalid polygon, try a new one
    }
  }
  addPolygonsToDoc(FIELDNAME, doc, polygon);
  w.addDocument(doc);
  w.forceMerge(1);

  ///// search //////
  IndexReader reader = w.getReader();
  w.close();
  IndexSearcher searcher = newSearcher(reader);

  Query q = LatLonShape.newPolygonQuery(FIELDNAME, QueryRelation.WITHIN, polygon);
  assertEquals(1, searcher.count(q));
  q = LatLonShape.newPolygonQuery(FIELDNAME, QueryRelation.INTERSECTS, polygon);
  assertEquals(1, searcher.count(q));
  q = LatLonShape.newPolygonQuery(FIELDNAME, QueryRelation.DISJOINT, polygon);
  assertEquals(0, searcher.count(q));

  IOUtils.close(w, reader, dir);
}
 
Example 7
Source Project: lucene-solr   Source File: LatLonPointSpatialField.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Decodes the docValues number into latitude and longitude components, formatting as "lat,lon".
 * The encoding is governed by {@code LatLonDocValuesField}.  The decimal output representation is reflective
 * of the available precision.
 * @param value Non-null; stored location field data
 * @return Non-null; "lat, lon"
 */
public static String decodeDocValueToString(long value) {
  final double latDouble = GeoEncodingUtils.decodeLatitude((int) (value >> 32));
  final double lonDouble = GeoEncodingUtils.decodeLongitude((int) (value & 0xFFFFFFFFL));
  // This # decimal places gets us close to our available precision to 1.40cm; we have a test for it.
  // CEILING round-trips (decode then re-encode then decode to get identical results). Others did not. It also
  //   reverses the "floor" that occurred when we encoded.
  final int DECIMAL_PLACES = 7;
  final RoundingMode ROUND_MODE = CEILING;
  BigDecimal latitudeDecoded = BigDecimal.valueOf(latDouble).setScale(DECIMAL_PLACES, ROUND_MODE);
  BigDecimal longitudeDecoded = BigDecimal.valueOf(lonDouble).setScale(DECIMAL_PLACES, ROUND_MODE);
  return latitudeDecoded.stripTrailingZeros().toPlainString() + ","
      + longitudeDecoded.stripTrailingZeros().toPlainString();
  // return ((float)latDouble) + "," + ((float)lonDouble);  crude but not quite as accurate
}
 
Example 8
Source Project: lucene-solr   Source File: TestNearest.java    License: Apache License 2.0 4 votes vote down vote up
private double quantizeLat(double latRaw) {
  return GeoEncodingUtils.decodeLatitude(GeoEncodingUtils.encodeLatitude(latRaw));
}
 
Example 9
Source Project: lucene-solr   Source File: TestNearest.java    License: Apache License 2.0 4 votes vote down vote up
private double quantizeLon(double lonRaw) {
  return GeoEncodingUtils.decodeLongitude(GeoEncodingUtils.encodeLongitude(lonRaw));
}
 
Example 10
@Override
public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException {

  return new ConstantScoreWeight(this, boost) {

    final Component2D tree = LatLonGeometry.create(polygons);
    final GeoEncodingUtils.PolygonPredicate polygonPredicate = GeoEncodingUtils.createComponentPredicate(tree);

    @Override
    public Scorer scorer(LeafReaderContext context) throws IOException {
      final SortedNumericDocValues values = context.reader().getSortedNumericDocValues(field);
      if (values == null) {
        return null;
      }

      final TwoPhaseIterator iterator = new TwoPhaseIterator(values) {

        @Override
        public boolean matches() throws IOException {
          for (int i = 0, count = values.docValueCount(); i < count; ++i) {
            final long value = values.nextValue();
            final int lat = (int) (value >>> 32);
            final int lon = (int) (value & 0xFFFFFFFF);
            if (polygonPredicate.test(lat, lon)) {
              return true;
            }
          }
          return false;
        }

        @Override
        public float matchCost() {
          return 1000f; // TODO: what should it be?
        }
      };
      return new ConstantScoreScorer(this, boost, scoreMode, iterator);
    }

    @Override
    public boolean isCacheable(LeafReaderContext ctx) {
      return DocValues.isCacheable(ctx, field);
    }

  };
}
 
Example 11
Source Project: lucene-solr   Source File: LatLonDocValuesDistanceQuery.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException {
  return new ConstantScoreWeight(this, boost) {

    private final GeoEncodingUtils.DistancePredicate distancePredicate = GeoEncodingUtils.createDistancePredicate(latitude, longitude, radiusMeters);

    @Override
    public Scorer scorer(LeafReaderContext context) throws IOException {
      final SortedNumericDocValues values = context.reader().getSortedNumericDocValues(field);
      if (values == null) {
        return null;
      }

      final TwoPhaseIterator iterator = new TwoPhaseIterator(values) {

        @Override
        public boolean matches() throws IOException {
          for (int i = 0, count = values.docValueCount(); i < count; ++i) {
            final long value = values.nextValue();
            final int lat = (int) (value >>> 32);
            final int lon = (int) (value & 0xFFFFFFFF);
            if (distancePredicate.test(lat, lon)) {
              return true;
            }
          }
          return false;
        }

        @Override
        public float matchCost() {
          return 100f; // TODO: what should it be?
        }

      };
      return new ConstantScoreScorer(this, boost, scoreMode, iterator);
    }

    @Override
    public boolean isCacheable(LeafReaderContext ctx) {
      return DocValues.isCacheable(ctx, field);
    }

  };
}
 
Example 12
Source Project: lucene-solr   Source File: TestLatLonDocValuesQueries.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected double quantizeLat(double latRaw) {
  return GeoEncodingUtils.decodeLatitude(GeoEncodingUtils.encodeLatitude(latRaw));
}
 
Example 13
Source Project: lucene-solr   Source File: TestLatLonDocValuesQueries.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected double quantizeLon(double lonRaw) {
  return GeoEncodingUtils.decodeLongitude(GeoEncodingUtils.encodeLongitude(lonRaw));
}
 
Example 14
Source Project: lucene-solr   Source File: TestLatLonPointQueries.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected double quantizeLat(double latRaw) {
  return GeoEncodingUtils.decodeLatitude(GeoEncodingUtils.encodeLatitude(latRaw));
}
 
Example 15
Source Project: lucene-solr   Source File: TestLatLonPointQueries.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected double quantizeLon(double lonRaw) {
  return GeoEncodingUtils.decodeLongitude(GeoEncodingUtils.encodeLongitude(lonRaw));
}
 
Example 16
public void testBasics() throws IOException {
  Directory dir = newDirectory();
  RandomIndexWriter w = new RandomIndexWriter(random(), dir, newIndexWriterConfig()
      .setMergePolicy(newLogMergePolicy(random().nextBoolean())));
  Document doc = new Document();
  LatLonPoint point = new LatLonPoint("foo", 0.0, 0.0);
  doc.add(point);
  LatLonDocValuesField docValue = new LatLonDocValuesField("foo",0.0, 0.0);
  doc.add(docValue);

  double pivotDistance = 5000;//5k

  point.setLocationValue(-7, -7);
  docValue.setLocationValue(-7, -7);
  w.addDocument(doc);

  point.setLocationValue(9, 9);
  docValue.setLocationValue(9, 9);
  w.addDocument(doc);


  point.setLocationValue(8, 8);
  docValue.setLocationValue(8, 8);
  w.addDocument(doc);

  point.setLocationValue(4, 4);
  docValue.setLocationValue(4, 4);
  w.addDocument(doc);

  point.setLocationValue(-1, -1);
  docValue.setLocationValue(-1, -1);
  w.addDocument(doc);

  DirectoryReader reader = w.getReader();
  IndexSearcher searcher = newSearcher(reader);
  
  Query q = LatLonPoint.newDistanceFeatureQuery("foo", 3, 10, 10, pivotDistance);
  TopScoreDocCollector collector = TopScoreDocCollector.create(2, null, 1);
  searcher.search(q, collector);
  TopDocs topHits = collector.topDocs();
  assertEquals(2, topHits.scoreDocs.length);

  double distance1 = SloppyMath.haversinMeters(GeoEncodingUtils.decodeLatitude(GeoEncodingUtils.encodeLatitude(9)) , GeoEncodingUtils.decodeLongitude(GeoEncodingUtils.encodeLongitude(9)), 10,10);
  double distance2 = SloppyMath.haversinMeters(GeoEncodingUtils.decodeLatitude(GeoEncodingUtils.encodeLatitude(8)) , GeoEncodingUtils.decodeLongitude(GeoEncodingUtils.encodeLongitude(8)), 10,10);

  CheckHits.checkEqual(q,
      new ScoreDoc[] {
          new ScoreDoc(1, (float) (3f * (pivotDistance / (pivotDistance + distance1)))),
          new ScoreDoc(2, (float) (3f * (pivotDistance / (pivotDistance + distance2))))
      },
      topHits.scoreDocs);

  distance1 = SloppyMath.haversinMeters(GeoEncodingUtils.decodeLatitude(GeoEncodingUtils.encodeLatitude(9)) , GeoEncodingUtils.decodeLongitude(GeoEncodingUtils.encodeLongitude(9)), 9,9);
  distance2 = SloppyMath.haversinMeters(GeoEncodingUtils.decodeLatitude(GeoEncodingUtils.encodeLatitude(8)) , GeoEncodingUtils.decodeLongitude(GeoEncodingUtils.encodeLongitude(8)), 9,9);

  q = LatLonPoint.newDistanceFeatureQuery("foo", 3, 9, 9,  pivotDistance);
  collector = TopScoreDocCollector.create(2, null, 1);
  searcher.search(q, collector);
  topHits = collector.topDocs();
  assertEquals(2, topHits.scoreDocs.length);
  CheckHits.checkExplanations(q, "", searcher);

  CheckHits.checkEqual(q,
      new ScoreDoc[] {
          new ScoreDoc(1, (float) (3f * (pivotDistance / (pivotDistance + distance1)))),
          new ScoreDoc(2, (float) (3f * (pivotDistance / (pivotDistance + distance2))))
      },
      topHits.scoreDocs);
  
  reader.close();
  w.close();
  dir.close();
}
 
Example 17
public void testCrossesDateLine() throws IOException {
  Directory dir = newDirectory();
  RandomIndexWriter w = new RandomIndexWriter(random(), dir, newIndexWriterConfig()
      .setMergePolicy(newLogMergePolicy(random().nextBoolean())));
  Document doc = new Document();
  LatLonPoint point = new LatLonPoint("foo", 0.0, 0.0);
  doc.add(point);
  LatLonDocValuesField docValue = new LatLonDocValuesField("foo",0.0, 0.0);
  doc.add(docValue);

  double pivotDistance = 5000;//5k

  point.setLocationValue(0, -179);
  docValue.setLocationValue(0, -179);
  w.addDocument(doc);

  point.setLocationValue(0, 176);
  docValue.setLocationValue(0, 176);
  w.addDocument(doc);

  point.setLocationValue(0, -150);
  docValue.setLocationValue(0, -150);
  w.addDocument(doc);

  point.setLocationValue(0, -140);
  docValue.setLocationValue(0, -140);
  w.addDocument(doc);

  point.setLocationValue(0, 140);
  docValue.setLocationValue(01, 140);
  w.addDocument(doc);

  DirectoryReader reader = w.getReader();
  IndexSearcher searcher = newSearcher(reader);

  Query q = LatLonPoint.newDistanceFeatureQuery("foo", 3, 0, 179, pivotDistance);
  TopScoreDocCollector collector = TopScoreDocCollector.create(2, null, 1);
  searcher.search(q, collector);
  TopDocs topHits = collector.topDocs();
  assertEquals(2, topHits.scoreDocs.length);

  double distance1 = SloppyMath.haversinMeters(GeoEncodingUtils.decodeLatitude(GeoEncodingUtils.encodeLatitude(0)) , GeoEncodingUtils.decodeLongitude(GeoEncodingUtils.encodeLongitude(-179)), 0,179);
  double distance2 = SloppyMath.haversinMeters(GeoEncodingUtils.decodeLatitude(GeoEncodingUtils.encodeLatitude(0)) , GeoEncodingUtils.decodeLongitude(GeoEncodingUtils.encodeLongitude(176)), 0,179);

  CheckHits.checkEqual(q,
      new ScoreDoc[] {
          new ScoreDoc(0, (float) (3f * (pivotDistance / (pivotDistance + distance1)))),
          new ScoreDoc(1, (float) (3f * (pivotDistance / (pivotDistance + distance2))))
      },
      topHits.scoreDocs);

  reader.close();
  w.close();
  dir.close();
}
 
Example 18
public void testMissingValue() throws IOException {
  Directory dir = newDirectory();
  RandomIndexWriter w = new RandomIndexWriter(random(), dir, newIndexWriterConfig()
      .setMergePolicy(newLogMergePolicy(random().nextBoolean())));
  Document doc = new Document();
  LatLonPoint point = new LatLonPoint("foo", 0, 0);
  doc.add(point);
  LatLonDocValuesField docValue = new LatLonDocValuesField("foo", 0, 0);
  doc.add(docValue);

  point.setLocationValue(3, 3);
  docValue.setLocationValue(3, 3);
  w.addDocument(doc);

  w.addDocument(new Document());

  point.setLocationValue(7, 7);
  docValue.setLocationValue(7, 7);
  w.addDocument(doc);

  DirectoryReader reader = w.getReader();
  IndexSearcher searcher = newSearcher(reader);
  
  Query q = LatLonPoint.newDistanceFeatureQuery("foo", 3, 10, 10, 5);
  TopScoreDocCollector collector = TopScoreDocCollector.create(3, null, 1);
  searcher.search(q, collector);
  TopDocs topHits = collector.topDocs();
  assertEquals(2, topHits.scoreDocs.length);

  double distance1 = SloppyMath.haversinMeters(GeoEncodingUtils.decodeLatitude(GeoEncodingUtils.encodeLatitude(7)) , GeoEncodingUtils.decodeLongitude(GeoEncodingUtils.encodeLongitude(7)), 10,10);
  double distance2 = SloppyMath.haversinMeters(GeoEncodingUtils.decodeLatitude(GeoEncodingUtils.encodeLatitude(3)) , GeoEncodingUtils.decodeLongitude(GeoEncodingUtils.encodeLongitude(3)), 10,10);

  CheckHits.checkEqual(q,
      new ScoreDoc[] {
          new ScoreDoc(2, (float) (3f * (5. / (5. + distance1)))),
          new ScoreDoc(0, (float) (3f * (5. / (5. + distance2))))
      },
      topHits.scoreDocs);

  CheckHits.checkExplanations(q, "", searcher);

  reader.close();
  w.close();
  dir.close();
}
 
Example 19
Source Project: lucene-solr   Source File: TestLatLonShapeEncoding.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected int encodeX(double x) {
  return GeoEncodingUtils.encodeLongitude(x);
}
 
Example 20
Source Project: lucene-solr   Source File: TestLatLonShapeEncoding.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected int encodeY(double y) {
  return GeoEncodingUtils.encodeLatitude(y);
}
 
Example 21
Source Project: lucene-solr   Source File: TestLatLonShapeEncoding.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected double decodeX(int xEncoded) {
  return GeoEncodingUtils.decodeLongitude(xEncoded);
}
 
Example 22
Source Project: lucene-solr   Source File: TestLatLonShapeEncoding.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected double decodeY(int yEncoded) {
  return GeoEncodingUtils.decodeLatitude(yEncoded);
}
 
Example 23
public static long encodeLatLon(double lat, double lon) {
    return (Integer.toUnsignedLong(GeoEncodingUtils.encodeLatitude(lat)) << 32) |
            Integer.toUnsignedLong(GeoEncodingUtils.encodeLongitude(lon));
}
 
Example 24
public static double decodeLatitude(long encodedLatLon) {
    return GeoEncodingUtils.decodeLatitude((int) (encodedLatLon >>> 32));
}
 
Example 25
public static double decodeLongitude(long encodedLatLon) {
    return GeoEncodingUtils.decodeLongitude((int) (encodedLatLon & 0xFFFFFFFFL));
}