From 5517dda5560503f14ffbfa29dd9603df86aba5f5 Mon Sep 17 00:00:00 2001 From: Colin Goodheart-Smithe Date: Tue, 12 Aug 2014 21:12:38 +0100 Subject: [PATCH] Geo: fixes computation of geohash neighbours The geohash grid it 8 cells wide and 4 cells tall. GeoHashUtils.neighbor(String,int,int.int) set the limit of the number of cells in y to < 3 rather than <= 3 resulting in it either not finding all neighbours or incorrectly searching for a neighbour in a different parent cell. Closes #7226 --- .../common/geo/GeoHashUtils.java | 4 ++-- .../index/search/geo/GeoHashUtilsTests.java | 21 ++++++++++++++++++- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/elasticsearch/common/geo/GeoHashUtils.java b/src/main/java/org/elasticsearch/common/geo/GeoHashUtils.java index 17d163913495f..a3b98ccbfc629 100644 --- a/src/main/java/org/elasticsearch/common/geo/GeoHashUtils.java +++ b/src/main/java/org/elasticsearch/common/geo/GeoHashUtils.java @@ -185,7 +185,7 @@ private final static String neighbor(String geohash, int level, int dx, int dy) // encode the cell directly. Otherwise find the cell next to this // cell recursively. Since encoding wraps around within a cell // it can be encoded here. - if (nx >= 0 && nx <= xLimit && ny >= 0 && ny < yLimit) { + if (nx >= 0 && nx <= xLimit && ny >= 0 && ny <= yLimit) { return geohash.substring(0, level - 1) + encode(nx, ny); } else { String neighbor = neighbor(geohash, level - 1, dx, dy); @@ -511,5 +511,5 @@ private static double[] decodeCell(long geohash) { } } return interval; - } + } } \ No newline at end of file diff --git a/src/test/java/org/elasticsearch/index/search/geo/GeoHashUtilsTests.java b/src/test/java/org/elasticsearch/index/search/geo/GeoHashUtilsTests.java index 7e872e1fd7f33..60842b51ed4c0 100644 --- a/src/test/java/org/elasticsearch/index/search/geo/GeoHashUtilsTests.java +++ b/src/test/java/org/elasticsearch/index/search/geo/GeoHashUtilsTests.java @@ -24,7 +24,9 @@ import org.elasticsearch.test.ElasticsearchTestCase; import org.junit.Test; -import static org.junit.Assert.assertEquals; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; /** * @@ -86,4 +88,21 @@ public void testDecodeEncode() { assertEquals(geoHash, GeoHashUtils.encode(decode.lat(), decode.lon())); } + + @Test + public void testNeighbours() { + String geohash = "gcpv"; + List expectedNeighbors = new ArrayList<>(); + expectedNeighbors.add("gcpw"); + expectedNeighbors.add("gcpy"); + expectedNeighbors.add("u10n"); + expectedNeighbors.add("gcpt"); + expectedNeighbors.add("u10j"); + expectedNeighbors.add("gcps"); + expectedNeighbors.add("gcpu"); + expectedNeighbors.add("u10h"); + Collection neighbors = new ArrayList<>(); + GeoHashUtils.addNeighbors(geohash, neighbors ); + assertEquals(expectedNeighbors, neighbors); + } }