程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Introduction to the principle of geohash, summary of redis geo command, and python using redis geo module

編輯:Python

Geohash

One .GeoHash Code introduction

Reference resources :

https://hogwartsrico.github.io/2015/01/22/About-GeoHash/

Geohash principle - Simple books (jianshu.com)

1.Geohash know

GeoHash Essentially, it's a way of spatial indexing , The basic principle is to understand the earth as a two-dimensional plane , Divide the plane recursively into smaller sub blocks , Each sub block has the same code in a certain latitude and longitude range . With GeoHash How to build a spatial index , Can improve on space poi The efficiency of data retrieval in latitude and longitude .

GeoHash Convert two-dimensional latitude and longitude to string , For example, the picture below shows Beijing 9 Area GeoHash character string , Namely WX4ER,WX4G2、WX4G3 wait , Each string represents a rectangular area . in other words , All the points in this rectangle ( Latitude and longitude coordinates ) All share the same GeoHash character string , This can protect privacy ( It only shows the general location of the area, not the specific point ), It's easier to cache .

​ Geohash In the encoding , Similar strings represent close distances ( The special situation will be explained later ), In this way, you can use prefix matching of strings to query the nearby POI Information . As shown in the following two figures , One is in the city , One is in the suburbs , In the city GeoHash Strings are similar , Suburban strings are also similar , And urban and suburban GeoHash String similarity is lower . Besides , Different encoding lengths , Indicates a different range range , The longer the string , The more accurate the range is .

2.GeoHash Algorithm

​ In latitude and longitude :(116.389550, 39.928167) Explain the algorithm , Right latitude 39.928167 Do approximation coding ( The latitude range of the earth is [-90,90]

a. Section [-90,90] To divide into two parts [-90,0),[0,90], It's called the left and right intervals , Can be determined 39.928167 It belongs to the right range [0,90], Mark as 1

b. And then I'll take the interval [0,90] To divide into two parts [0,45),[45,90], Can be determined 39.928167 It belongs to the left range [0,45), Mark as 0

c. Recurse the above procedure 39.928167 Always in a certain range [a,b]. With each iteration interval [a,b] Always shrinking , And getting closer 39.928167

d. If given latitude x(39.928167) It belongs to the left range , Record 0, If it belongs to the right interval, record 1, The length of a sequence is related to the number of times a given interval is divided , Here's the picture

​ e. Empathy , The longitude range of the earth is [-180,180], It's OK for longitude 116.389550 Encoding . By the above calculation , Longitude is encoded as 1 1 0 1 0 0 1 0 1 1 0 0 0 1 0, Latitude is encoded as 1 0 1 1 1 0 0 0 1 1 0 0 0 1 1

​ f. Merge : Longitude in even Numbers (0,2,4,6,8), Odd place latitude (1,3,5,7,9), hold 2 The new string generated by the string encoding combination is shown in the figure below ( Put the longitude first , Back latitude

​ g. First of all, will 11100 11101 00100 01111 0000 01101 Turn into Decimal system , Corresponding 28、29、4、15,0,13 The decimal system corresponds to base32 code Namely wx4g0e, Here's the picture .

Base32 code :

First, the binary string is divided into each 5 One by one , Insufficient 5 Place complement 0.

Then put the... Of each group 5 Bit binary string to decimal (5bits Corresponding 10 The decimal value is 0-31).

use 0-9、b-z( Get rid of a、i、l、o) this 32 A letter for Base32 code , That is, convert it into a string by comparing the subscript .

​ h. Empathy , The decoding algorithm that converts the encoding to latitude and longitude is the opposite .

3.GeoHash principle

​ Geohash In fact, it is to divide the whole map or the area obtained by a certain division , Because of the use of base32 Encoding mode , namely Geohash Every letter or number in ( Such as wx4g0e Medium w) It's all by 5bits form (2^5 = 32,base32), this 5bits There can be 32 Different combinations in (0~31), So we can divide the whole map area into 32 Regions , adopt 00000 ~ 11111 To identify this 32 Regions . The situation after the first map division is shown in the figure below ( The number in each area corresponds to the code corresponding to that area )).

​ Geohash Of 0、1 The string sequence is longitude 0、1 Sequence and latitude 0、1 The numbers in a sequence are arranged alternately , The sequence corresponding to even digits is longitude sequence , The sequence corresponding to odd digits is latitude sequence , In the first division ,Geohash0、1 The first... In the sequence 5 individual bits(11100), So this 5bits There is 3bits It means longitude ,2bits It means latitude , So the first division , Is to divide longitude into 8 Sections (2^3 = 8), Divide latitude into 4 Sections (2^2 = 4), In this way 32 Regions . Here's the picture

​ Empathy , The first division can be done in the same way as the first division 32 The areas are divided again .

​ As mentioned above GeoHash The calculation steps of , Just say what it is and not why ? Why encode longitude and dimension respectively ? Why do we need to cross combine the two codes of longitude and latitude into one code ? This section attempts to answer the question .

​ As shown in the figure , We fill in the result of binary encoding into space , When you divide the space into four pieces , The order of coding is the lower left corner 00, top left corner 01, Right lower foot 10, Upper right corner 11, Which is similar to Z The curve of , When we recursively decompose each block into smaller sub blocks , The order of coding is self similar ( fractal ), Every one of them will soon form Z curve , This type of curve is called Peano Space filling curve .

​ The advantage of this type of space filling curve is to convert two-dimensional space into one-dimensional curve ( It's actually a fractal dimension ), For the most part , Similar coding distance is also close , but Peano The biggest disadvantage of space filling curve is the mutation , Some codes are adjacent but far apart , such as 0111 And 1000, The code is adjacent , But the distance is very different .

​ except Peano Space filling curve outside , There's a lot of space to fill the curve , As shown in the figure , Among them, it is generally accepted that the effect is better Hilbert Space filling curve , Compare with Peano In terms of curve ,Hilbert There is no big mutation in the curve . But because of Peano Curve implementation is simpler , Cooperate with certain solutions when using , It can meet most of the needs well , therefore TD Inside Geohash The algorithm uses Peano Space filling curve .

4.GeoHash Advantages and disadvantages

advantage :

Geohash The advantages are obvious , It USES Z Order curve . and Z Order curve can convert all points in two-dimensional or multi-dimensional space into one-dimensional curve . In mathematics, it becomes fractal dimension . also Z Second order curves also have local order preserving property .

Z The order curve simply calculates the coordinates of points in multi-dimensional degree through the binary representation of the coordinate values of interleaving points z value . Once the data is added to the sort , Any one-dimensional data structure , For example, binary search tree ,B Trees , Jump table or ( Truncated with low significant bits ) Hashtable Can be used to process data . adopt Z The order obtained by the order curve can be equally described as the order obtained from the depth first traversal of the quadtree .

This is also Geohash Another advantage of , Searching for nearby points is faster .

shortcoming :

Geohash One of the disadvantages of is also from Z Degree curve .

Z There is a serious problem with the order curve , Although there is local order preservation , But it also has mutations . At every Z The corner of the letter , It's possible to have a sequence mutation .

Geohash Another disadvantage of is , If you don't choose the right grid size , Judging proximity can be cumbersome .

5. Use caution

a. because GeoHash It is to divide the area into regular rectangles , And code each rectangle , This is near the inquiry POI Information can cause the following problems , For example, the red dot is our position , The two green spots are two restaurants nearby , But when you check, you will find that the restaurant is far away GeoHash The code is the same as us ( Because in the same GeoHash On the block ), And closer to the restaurant GeoHash The code is not consistent with us . This problem often arises at the border .

​ The solution is simple , When we inquired , In addition to using anchor points GeoHash Code to match outside , Also use around 8 Area GeoHash code , This can avoid the problem .

b. We already know the existing GeoHash The algorithm uses Peano Space filling curve , This kind of curve will produce mutation , It causes the problem that although the coding is similar, the distance may be very different , So when you look up a restaurant nearby , First, screen GeoHash Code similar POI spot , Then calculate the actual distance .

c. GeoHash Base32 Coding length and accuracy . It can be seen that , When geohash base32 The encoding length is 8 when , Precision in 19 Rice or so , And when the encoding length is 9 when , Precision in 2 Rice or so , The coding length needs to be selected according to the data situation .

6. Calculate all... In the fence Geohash

I understand geohash After the basic principle of the algorithm , This section will introduce a common scenario in practical application : Calculate all... Within the fence Geohash code . This scenario is encapsulated as a function and can be represented as follows : Enter the set of latitude and longitude coordinates of the points that make up the fence and the specified geohash length , Output a set of geohash code .

​ public static Set getHashByFence(List points, int length)

​ The specific algorithm steps are as follows :

  1. Enter the fence point coordinate set List points And specified geohash length length

  2. Calculate the coordinates of the upper left corner and the lower right corner of the enclosure rectangle lat_min、lat_max、lng_min、lng_max

  3. according to lat_min、lat_max、lng_min、lng_max, Calculate the distance between the diagonal points of the outer rectangle d

  4. Take the center point of the outer rectangle as the center , With d/2 Make a circle for the radius , Calculate the geohash

4.1 obtain The outer rectangle of a circle The longitude and latitude of the fixed-point coordinates at the upper left corner and the lower right corner , Store in double[] locs

4.2 according to geohash Character length calculates the length geohash Code the corresponding latitude and longitude interval (latA,lngA)

4.3 according to latA and lngA, To calculate the locs The longitude and latitude of the upper left corner and the lower right corner of the rectangle , stay geohash Index of divided grid ( That's the number one ), Write them down as lat_min,lat_max,lng_min,lng_max

4.4 Calculation lat_min,lat_max,lng_min,lng_max In the corresponding range geohash Binary code of , And then the latitude and longitude binary code uncode by geohash Character encoding , Save as Set sets

  1. To eliminate sets in geohash The center point of the corresponding rectangle is not in points Within the fence geohash, To get the final geohash Result set

Two .Redis Of GEO modular

1. Precision problem

reids stay 3.2 The geographical location is added after the version Geo modular

GeoHash The algorithm will continue to do this integer once base32 code (09,az, Get rid of a、i、l、o Four letters ) It becomes a string . stay Redis Inside , Latitude and longitude use 52 The whole number of bits is encoded , Put it in zset Inside ,zset Of value It's elemental key,score yes GeoHash Of 52 Bit integer value .zset Of score Although it's a floating-point number , But for 52 Integer value of bit , It can store without damage .

double The type accuracy is 52 position ;
geohash In order to base32(5 One code per bit ) The way to code ,52bits Up to storage 10 position geohash value , The corresponding geographic area size is 0.6*0.6 Meter lattice . In other words, by Redis geo The transformed position will theoretically be about 0.3 *1.414=0.424 The error of meters .
【 source :https://python.iitter.com/other/12028.html】

Redis Of double type :

​ Redis The score type of is double,64 Bit double precision floating-point numbers have only 52 Significant digits , The range of integers that it can accurately express is -253 To 253, The highest can only mean 16 A decimal integer ( The maximum value is 9007199254740992, In fact, even 16 Nor can bits completely represent ).

Range and precision of data types :

1) Range

float and double Of Range By Number of digits of index To decide .
float The index of is 8 position , and double The index of is 11 position , The distribution is as follows :

  • float:(32 position ,4 byte )
    1bit( Sign bit ) 8bits( Exponential position ) 23bits( mantissa )

  • double:(64 position ,8 byte )
    1bit( Sign bit ) 11bits( Exponential position ) 52bits( mantissa )

    therefore ,float The index range of is -127—+128, and double The index range of is -1023----+1024, And the number of digits is divided according to the form of complement .
    Among them, the negative index determines the minimum non-zero number of absolute value that a floating-point number can express ; The positive index determines the maximum absolute value that a floating-point number can express , That is to say, it determines the value range of floating-point numbers .
    float For the range of -2^128 ~ +2^128, That is to say -3.40E+38 ~ +3.40E+38;double For the range of -2^1024 ~ +2^1024, That is to say -1.79E+308 ~ +1.79E+308.

2) precision

float and double Of precision By The number of digits of mantissa To decide . Floating point numbers are stored in memory by scientific counting , The whole part of it is always an implied “1”, Because it's constant , So it can't affect the accuracy .
float:2^23 = 8388608, There are seven of you , This means that there can be at most 7 Significant digits , But what is absolutely guaranteed is 6 position , That is to say float The accuracy of is 6~7 Significant digits ;
double:2^52 = 4503599627370496, altogether 16 position , Empathy ,double The accuracy of is 15~16 position .

2.Redis Of Geo Instructions

problem

Our common requirement is to find n rice Points in the range , that n rice And GeoHash How to realize the mapping between code bits ? because GeoHash Code is by 5 Bit binary code , Every one less , Precision will be lost 2e(5/2).

Of course, there are ways , We will be binary GeoHash Code can be directly indexed , But a very long index length can lead to B Trees The efficiency of index query will decrease rapidly .

programme

So we went on to find a solution , Since the use of base32 Convert to 32 Binary code It will be difficult to control the accuracy , Keeping binary causes the index length to be too long , Is there a balance between the number of decimal digits and the index length ?

in addition Redis Of sorted set Support 64 position Of double Type of score, We put binary GeoHash Convert the code to decimal and put it in Redis Of sorted set in , It's not possible Realization log(n) The query efficiency of Why? .

3.Redis Of Geo The command basically uses

Redis Provided Geo Instructions only 6 individual , Readers can master in an instant . When using , The reader must recall , It's just an ordinary zset structure .

geoadd Coordinates used to increase geographical location , You can add geographic locations in batches
geodist Used to get the distance between two geographical locations
geopos You can get the coordinates of the geographical location , The coordinates of multiple geographical locations can be obtained in batch
geohash You can get the longitude and latitude encoding string of the element
georadius The geographic location set within the specified range can be obtained according to the given geographic location coordinates
georadiusbymember You can get the geographic location collection within the specified range according to the given geographic location

increase

geoadd The instruction carries the set name and multiple triples of latitude and longitude names , Note that multiple triples can be added here

127.0.0.1:6379> geoadd company 116.48105 39.996794 juejin
(integer) 1
127.0.0.1:6379> geoadd company 116.514203 39.905409 ireader
(integer) 1
127.0.0.1:6379> geoadd company 116.489033 40.007669 meituan
(integer) 1
127.0.0.1:6379> geoadd company 116.562108 39.787602 jd 116.334255 40.027400 xiaomi
(integer) 2

distance

geodist Instructions can be used to calculate the distance between two elements , Carry the name of the collection 、2 Names and distance units .

127.0.0.1:6379> geodist company juejin ireader km
"10.5501"
127.0.0.1:6379> geodist company juejin meituan km
"1.3878"
127.0.0.1:6379> geodist company juejin jd km
"24.2739"
127.0.0.1:6379> geodist company juejin xiaomi km
"12.9606"
127.0.0.1:6379> geodist company juejin juejin km
"0.0000"

We can see that nuggets are closest to the US regiment , Because they are all in Wangjing . The distance unit can be m、km、ml、ft, They represent meters 、 km 、 Miles and feet .

Get element location

geopos The command can get the latitude and longitude coordinates of any element in the set , You can get more than one at a time .

127.0.0.1:6379> geopos company juejin
1) 1) "116.48104995489120483"
2) "39.99679348858259686"
127.0.0.1:6379> geopos company ireader
1) 1) "116.5142020583152771"
2) "39.90540918662494363"
127.0.0.1:6379> geopos company juejin ireader
1) 1) "116.48104995489120483"
2) "39.99679348858259686"
2) 1) "116.5142020583152771"
2) "39.90540918662494363"

We observe the latitude and longitude coordinates obtained and geoadd There's a slight error in the coordinates , as a result of geohash One dimensional mapping of two-dimensional coordinates is lossy , The values restored through mapping will have a small difference . about 「 The man near the 」 For this function , This error is nothing .

Fetch element hash value

geohash You can get the longitude and latitude encoding string of the element , As mentioned above , It is base32 code . You can use this coded value to http://geohash.org/${hash} Direct positioning in , It is geohash Standard coding value of .

127.0.0.1:6379> geohash company ireader
1) "wx4g52e1ce0"
127.0.0.1:6379> geohash company juejin
1) "wx4gd94yjn0"

Nearby companies

georadiusbymember Instruction is the most critical instruction , It can be used to query other elements near the specified element
plain , Its parameters are very complex .

# Range 20 The most in kilometers 3 The elements are arranged by distance , It doesn't exclude itself 
127.0.0.1:6379> georadiusbymember company ireader 20 km count 3 asc
1) "ireader"
2) "juejin"
3) "meituan"
# Range 20 The most in kilometers 3 Elements are inverted by distance 
127.0.0.1:6379> georadiusbymember company ireader 20 km count 3 desc
1) "jd"
2) "meituan"
3) "juejin"
# Three optional parameters withcoord withdist withhash Used to carry additional parameters 
# withdist It is useful to , It can be used to show distance 
127.0.0.1:6379> georadiusbymember company ireader 20 km withcoord withdist withhash count 3 asc
1) 1) "ireader"
2) "0.0000"
3) (integer) 4069886008361398
4) 1) "116.5142020583152771"
2) "39.90540918662494363"
2) 1) "juejin"
2) "10.5501"
3) (integer) 4069887154388167
4) 1) "116.48104995489120483"
2) "39.99679348858259686"
3) 1) "meituan"
2) "11.5748"
3) (integer) 4069887179083478
4) 1) "116.48903220891952515"
2) "40.00766997707732031"

except georadiusbymember Instruction to query the nearby elements according to the elements ,Redis It also provides querying nearby elements according to coordinate values , This command is more useful , It can be calculated according to the user's location 「 Nearby cars 」,「 A restaurant nearby 」 etc. . Its parameters and georadiusbymember Almost the same , In addition to changing the target element to the latitude and longitude coordinates .

127.0.0.1:6379> georadius company 116.514202 39.905409 20 km withdist count 3 asc
1) 1) "ireader"
2) "0.0000"
2) 1) "juejin"
2) "10.5501"
3) 1) "meituan"
2) "11.5748"

Summary & matters needing attention

In a map application , Car data 、 Restaurant data 、 There could be millions of human data , If you use Redis Of Geo data structure , They will all be in one zset Collection . stay Redis In the cluster environment , Collections may migrate from one node to another , If single key The data is too large , It will have a great impact on the migration of the cluster , Single... In a clustered environment key The corresponding amount of data should not exceed 1M, Otherwise, the cluster migration will be stuck , Affect the normal operation of online services .

therefore , Here's the advice Geo Using separate Redis Instance deployment , No cluster environment .

If the amount of data is over 100 million or more , You need to be right about Geo Split the data , Split by country 、 Split by province , Split by market , In a city with a large population, it can even be divided into districts . This can significantly reduce the number of individual zset The size of the collection .

3、 ... and 、python Use Redis Of Geo modular

#redis.Redis.******
pool = redis.ConnectionPool(host='10.3.1.151', port=6379,password='mca321', decode_responses=True) # Connect redis
redis_connect = redis.Redis(connection_pool=pool)
redis_connect.geoadd()
 Methods inherited from redis.commands.core.GeoCommands:
### 1. Additive elements ,geohash code Adds the specified geospatial item to the “`name`` The specified key for parameter identification . Geospatial projects as ``values`` Parametric Orderly Members provide , Each item or location is defined by the longitude of the triad 、 Latitude and name make up .values Is ordered .-------# values The parameters of are longitude 、 Element name 、 latitude 
geoadd(self, name, values, nx=False, xx=False, ch=False)
Add the specified geospatial items to the specified key identified
by the ``name`` argument. The Geospatial items are given as ordered members of the ``values`` argument, each item or place is formed by the triad longitude, latitude and name. # Tips : have access to ZREM Remove elements , Its essence is to use zset Storage  Note: You can use ZREM to remove elements. # nx=True Only new elements are created , The values of existing elements are not updated . The normal default is false, Will update the value of the existing element  ``nx`` forces ZADD to only create new elements and not to update scores for elements that already exist. # xx=true When forced, only the existing elements will be updated score, No new elements will be created . The normal default is true, Elements can be created normally  ``xx`` forces ZADD to only update scores of elements that already exist. New elements will not be added. # ch=true Will change the return value to the changed number of elements . The changed elements include new elements added and score Changed element . ``ch`` modifies the return value to be the numbers of elements changed. Changed elements include new elements that were added and elements whose scores changed. For more information check https://redis.io/commands/geoadd # 2. return ``name`` Keyed ``place1`` and ``place2`` The distance between members .unit Must be one of the following units : m, km mi, ft. By default m. geodist(self, name, place1, place2, unit=None) Return the distance between ``place1`` and ``place2`` members of the ``name`` key. The units must be one of the following : m, km mi, ft. By default meters are used. For more information check https://redis.io/commands/geodist # 3. Return from ``name`` Parameter identifies the of the specified key ``values`` For each item of the member geohash character string . geohash(self, name, *values) Return the geo hash string for each item of ``values`` members of the specified key identified by the ``name`` argument. For more information check https://redis.io/commands/geohash # 4. Return each ``values`` The location of the item , As ``name`` Parameter identifies the member of the specified key . Each location is represented by lon and lat Pair representation . geopos(self, name, *values) Return the positions of each item of ``values`` as members of the specified key identified by the ``name`` argument. Each position is represented by the pairs lon and lat. For more information check https://redis.io/commands/geopos ### 5. Return from ``name`` Parameter identifies the member of the specified key , These members are located by `` latitude `` and `` longitude `` Within the boundary of the area specified by the location , And the distance is determined by `` radius `` Value specifies the maximum distance from the center .----- Return to in (lon,lat) Centred , With radis Is within the radius value Elements georadius(self, name, longitude, latitude, radius, unit=None, withdist=False, withcoord=False, withhash=False, count=None, sort=None, store=None, store_dist=None, any=False) Return the members of the specified key identified by the ``name`` argument which are within the borders of the area specified with the ``latitude`` and ``longitude`` location and the maximum distance from the center specified by the ``radius`` value. # The units could be m, km mi, ft, The default is m The units must be one of the following : m, km mi, ft. By default # withdist=true Represents the distance to return to each position , The default is false, No return . ``withdist`` indicates to return the distances of each place. # withcoord=true It means to return the latitude and longitude of each place , The default is false, No return . ``withcoord`` indicates to return the latitude and longitude of each place. # withhash=true Represents the return of... For each location geohash character string , The default is false, No return . ``withhash`` indicates to return the geohash string of each place. # count=N Indicates that the return does not exceed N The number of elements , By default, the number is not limited  ``count`` indicates to return the number of elements up to N. ### sort Means to return the position by sorting ,sort=ASC It means nearest to farthest ,sort=DESC From the farthest to the nearest . ``sort`` indicates to return the places in a sorted way, ASC for nearest to fairest and DESC for fairest to nearest. # store Indicates that you want to save place names in a sort set named for a specific key , Each element in the target sort set will be populated with the score. ``store`` indicates to save the places names in a sorted set named with a specific key, each element of the destination sorted set is populated with the score got from the original geo sorted set. # store_dist It means place name (value) The element is stored in a sort set named with a specific key , instead of ``store`` Sort set , The destination score is set by distance . ``store_dist`` indicates to save the places names in a sorted set named with a specific key, instead of ``store`` the sorted set destination score is set with the distance. For more information check https://redis.io/commands/georadius ### 6. This command is associated with “georadius” Exactly the same , The only difference is , It does not take the longitude and latitude values as the center of the region to be queried , Instead, the names of existing members in the geospatial index represented by sorted sets .--- With value Element as the center  georadiusbymember(self, name, member, radius, unit=None, withdist=False, withcoord=False, withhash=False, count=None, sort=None, store=None, store_dist=None, any=False) This command is exactly like ``georadius`` with the sole difference that instead of taking, as the center of the area to query, a longitude and latitude value, it takes the name of a member already existing inside the geospatial index represented by the sorted set. For more information check https://redis.io/commands/georadiusbymember ###### 7. Return from ``name`` Parameter identifies the member of the specified key , These members are within the boundaries of the specified area of a given shape . This command extends GEORADIUS command , So in addition to searching in a circular area , It also supports searching in rectangular areas . This command should be used instead of the deprecated GEORADIUS and GEORADIUSBYMEMBER command .-------------- Supports searching in rectangular areas geosearch(self, name, member=None, longitude=None, latitude=None, unit='m', radius=None, width=None, height=None, sort=None, count=None, any=False, withcoord=False, withdist=False, withhash=False) Return the members of specified key identified by the ``name`` argument, which are within the borders of the area specified by a given shape. This command extends the GEORADIUS command, so in addition to searching within circular areas, it supports searching within rectangular areas. This command should be used in place of the deprecated GEORADIUS and GEORADIUSBYMEMBER commands. # member Use the location of existing elements in the collection ?? As the center , Cannot be associated with ``longitude`` and ``latitude`` Parameters are used at the same time ``member`` Use the position of the given existing member in the sorted set. Can't be given with ``longitude`` and ``latitude``. # ``longitude`` and ``latitude`` Specify latitude and longitude as the center , Cannot be associated with member Parameters are used at the same time ``longitude`` and ``latitude`` Use the position given by this coordinates. Can't be given with ``member`` # radius Specify the radius of the circular area , Cannot be associated with ``height`` and ``width`` Parameters are used at the same time ``radius`` Similar to GEORADIUS, search inside circular area according the given radius. Can't be given with ``height`` and ``width``. # ``height`` and ``width`` Search within an axis aligned rectangle , Determined by a given height and width . Cannot be associated with radius Parameters are used at the same time ``height`` and ``width`` Search inside an axis-aligned rectangle, determined by the given height and width. Can't be given with ``radius`` # unit The unit must be m, km, mi, ft. ``unit`` must be one of the following : m, km, mi, ft. `m` for meters (the default value), `km` for kilometers, `mi` for miles and `ft` for feet. # sort Indicates that the element is returned in a sort manner ,sort=ASC Represents from nearest to farthest ,sort=DESC Represents from the farthest to the nearest  ``sort`` indicates to return the places in a sorted way, ASC for nearest to farest and DESC for farest to nearest. # `count`` Limit the result to the first count of matches . ``count`` limit the results to the first count matching items. # `` If you will any`` Set to True, As long as enough matches are found (count Count ), The command will return . No, count Parameters cannot be used ``any`` is set to True, the command will return as soon as enough matches are found. Can't be provided without ``count`` # ``withdist=true`` Represents the distance to return to each position . ``withdist`` indicates to return the distances of each place. # ``withcoord=true`` Indicates to return the latitude and longitude of each place . ``withcoord`` indicates to return the latitude and longitude of each place. # ``withhash`` Indicates that the hash code ``withhash`` indicates to return the geohash string of each place. For more information check https://redis.io/commands/geosearch # 8. This command is similar to GEOSEARCH, But store the results in “dest” in . By default , It stores the results together with its geospatial information in the target sort set . If ``store_dist`` Set to True, Then the command will store the items in the sorted collection , Fill the distance to the center of a circle or box in the form of a floating point number .---- Store the sorting results in dest Collection geosearchstore(self, dest, name, member=None, longitude=None, latitude=None, unit='m', radius=None, width=None, height=None, sort=None, count=None, any=False, storedist=False) This command is like GEOSEARCH, but stores the result in ``dest``. By default, it stores the results in the destination sorted set with their geospatial information. if ``store_dist`` set to True, the command will stores the
items in a sorted set populated with their distance from the
center of the circle or box, as a floating-point number.
For more information check https://redis.io/commands/geosearchstore

Four 、Python Of geohash Coding package

install :

Mode one : Not recommended !!Geohash-1.0
(odc) [[email protected] ~]$ pip install geohash
# Existing problems 
(odc) [[email protected] ~]$ python
Python 3.8.12 packaged by conda-forge (default, Oct 12 2021, 21:59:51)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import geohash
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'geohash'

solve the problem :

(odc) [[email protected] miniconda3]$ find . -name "Geohash"
(odc) [[email protected] miniconda3]$ cd envs/odc/lib/python3.8/site-packages/Geohash
(odc) [[email protected] Geohash]$ ll
total 8
-rw-rw-r--. 1 mca mca 4021 Jan 17 21:14 geohash.py
-rw-rw-r--. 1 mca mca 839 Jan 17 21:14 __init__.py
drwxrwxr-x. 2 mca mca 67 Jan 17 21:14 __pycache__
(odc) [[email protected] Geohash]$ cd ..
(odc) [[email protected] site-packages]$ mv Geohash geohash
(odc) [[email protected] site-packages]$ cd geohash/
(odc) [[email protected] geohash]$ vim __init__.py
# hold from geohash import **** It is amended as follows from .geohash

Python 3.5 install geohash Behind the library import geohash Failure - The pirates Ora - Blog Garden (cnblogs.com)

vinsci/geohash: Python module to decode/encode Geohashes to/from latitude and longitude. See http://en.wikipedia.org/wiki/Geohash (github.com)

Mode two :python-geohash

The existence of a scheme can be avoided bug

(odc) [[email protected] ~]$ pip install python-geohash

Method :

FUNCTIONS
# 1. decode , take geohash Encode and decode into longitude and latitude 
decode(geohash)
Decode geohash, returning two strings with latitude and longitude
containing only relevant digits and with trailing zeroes removed.
# 2. Precise decoding , take geohash Decode to its exact value , Including the error range of the results . Returns four floating-point values : latitude 、 longitude 、 The positive and negative error of latitude ( Positive numbers ) And longitude ( Positive numbers ).
decode_exactly(geohash)
Decode the geohash to its exact values, including the error
margins of the result. Returns four float values: latitude,
longitude, the plus/minus error for latitude (as a positive
number) and the plus/minus error for longitude (as a positive
number).
# 3. code , Encode the latitude and longitude into geohash code , The number of coding digits can be specified ( It's about precision )
encode(latitude, longitude, precision=12)
Encode a position given in float arguments latitude, longitude to
a geohash which will have the character count precision.
# return x The to 10 Log base .
log10(x, /)
Return the base 10 logarithm of x.
Mode three : install mzgeohash
(odc) [[email protected] ~]$ pip install mz2geohash

The solutions to the problems encountered are as follows :

(41 Bar message ) Python install mzgeohash Package failed , Package name conflict _Nougats The blog of -CSDN Blog

Mode 4 : install mz2geohash
(odc) [[email protected] ~]$ pip install mz2geohash

Method :

FUNCTIONS
# 1. Returns the adjacent... In a given direction geohash
adjacent(geohash, direction)
Return the adjacent geohash for a given direction.
# 2. decode geohash. return (lon,lat) Yes .
decode(value)
Decode a geohash. Returns a (lon,lat) pair.
# 3. take (lon,lat) The pair is encoded as GeoHash.
encode(lonlat, length=12)
Encode a (lon,lat) pair to a GeoHash.
# 4. Return all neighbors geohash code 
neighbors(geohash)
Return all neighboring geohashes.
# 
neighborsfit(centroid, points)

example :

>>> import mz2geohash
>>> mz2geohash.decode('xn76urwe1g9y')
(139.76608408614993, 35.681382017210126)
>>> mz2geohash.encode((139.76608408614993, 35.681382017210126))
'xn76urwe1g9y'
>>> mz2geohash.neighbors('xn76urwe1g9y')
{
'c': 'xn76urwe1g9y',
'e': 'xn76urwe1gdn',
'n': 'xn76urwe1g9z',
'ne': 'xn76urwe1gdp',
'nw': 'xn76urwe1g9x',
's': 'xn76urwe1g9v',
'se': 'xn76urwe1gdj',
'sw': 'xn76urwe1g9t',
'w': 'xn76urwe1g9w'}

https://github.com/jason-h-35/mapzen-geohash


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved