本文主要研究一下redis的GEO的使用html
時間複雜度爲O(log(N))git
geoadd cityGeo 116.405285 39.904989 "北京" geoadd cityGeo 121.472644 31.231706 "上海"
時間複雜度爲O(log(N))redis
127.0.0.1:6379> geopos cityGeo 北京 1) 1) "116.40528291463851929" 2) "39.9049884229125027"
時間複雜度爲O(log(N))segmentfault
127.0.0.1:6379> geodist cityGeo 北京 上海 "1067597.9668" 127.0.0.1:6379> geodist cityGeo 北京 上海 km "1067.5980"
時間複雜度爲O(N+log(M)),N爲指定半徑範圍內的元素個數,M爲要返回的個數api
georadius cityGeo 116.405285 39.904989 100 km WITHDIST WITHCOORD ASC COUNT 5
時間複雜度爲O(log(N)+M),N爲指定半徑範圍內的元素個數,M爲要返回的個數code
georadiusbymember cityGeo 北京 100 km WITHDIST WITHCOORD ASC COUNT 5
查找一個位置的時間複雜度爲O(log(N))htm
127.0.0.1:6379> geohash cityGeo 北京 1) "wx4g0b7xrt0"
@Test public void testAdd(){ Long addedNum = redisTemplate.opsForGeo() .add(cityGeoKey,new Point(116.405285,39.904989),"北京"); System.out.println(addedNum); } @Test public void testGeoGet(){ List<Point> points = redisTemplate.opsForGeo().position(cityGeoKey,"北京","上海","深圳"); System.out.println(points); } @Test public void testDist(){ Distance distance = redisTemplate.opsForGeo() .distance(cityGeoKey,"北京","上海", RedisGeoCommands.DistanceUnit.KILOMETERS); System.out.println(distance); } @Test public void testNearByXY(){ //longitude,latitude Circle circle = new Circle(116.405285,39.904989, Metrics.KILOMETERS.getMultiplier()); RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance().includeCoordinates().sortAscending().limit(5); GeoResults<RedisGeoCommands.GeoLocation<String>> results = redisTemplate.opsForGeo() .radius(cityGeoKey,circle,args); System.out.println(results); } @Test public void testNearByPlace(){ Distance distance = new Distance(5,Metrics.KILOMETERS); RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance().includeCoordinates().sortAscending().limit(5); GeoResults<RedisGeoCommands.GeoLocation<String>> results = redisTemplate.opsForGeo() .radius(cityGeoKey,"北京",distance,args); System.out.println(results); } @Test public void testGeoHash(){ List<String> results = redisTemplate.opsForGeo() .hash(cityGeoKey,"北京","上海","深圳"); System.out.println(results); }
redis爲GEO提供了豐富的操做,RedisTemplate也封裝了對應的api,使用起來很是方便。排序