SoFunction
Updated on 2025-04-14

Redis GEO implements nearby search function

The company recently came to a new project to recruit mini programs. One of the requirements is to achieve recommendations for nearby positions. Due to the small number of users, I decided to use redis to achieve it. Haven't been in contact before. Now it is used to record. (Redis must use version 3.2 and above)

  • Let’s talk about the general process first. Save the position ID and latitude and longitude into redis. Add a message whenever a position is added. When the user clicks nearby, the corresponding position id is checked through the user's latitude and longitude, so that the position information can be correlated and queryed to return to the user for display.
  • The spring cloud Alibaba family bucket used by the project does not write its maven dependencies, only write redis related

Introducing redis dependencies

<dependency>
            <groupId></groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>2.3.</version>
        </dependency>

Bo

package .vo_bo;
import ;
import ;
import ;
/**
  * @Author: zhangxiongwei
  * @Date: 2021-10-26 16:11
  * @Description: Location information
  */
@Data
@ApiModel("Location Information")
public class LocationBo {
    @ApiModelProperty("longitude")
    private Double longitude;
    @ApiModelProperty("latitude")
    private Double latitude;
    @ApiModelProperty("radius")
    private Double radius;
    @ApiModelProperty("Number of digits")
    private Long limit;
}

Redis configuration class

package ;
import ;
import ;
import ;
import ;
/**
  * @Author: zhangxiongwei
  * @Date: 2021-10-26 16:38
  * @Description: redi configuration
  */
@Configuration
public class RedisConfig {
    /**
     * The constant GEO_STAGE.
     */
    public static final String GEO_STAGE = "cities";
    /**
     * Geo ops bound geo operations.
     *
     * @param redisTemplate the redis template
     * @return the bound geo operations
     */
    @Bean
    public BoundGeoOperations&lt;String, String&gt; citiesGeoOps(RedisTemplate&lt;String, String&gt; redisTemplate) {
        // Clean up the cache        (GEO_STAGE);
        return (GEO_STAGE);
    }
}

Test Controller

package ;
import ;
import .vo_bo.LocationBo;
import ;
import ;
import ;
import ;
import .slf4j.Slf4j;
import .*;
import ;
import ;
import ;
import .*;
import ;
import ;
/**
  * @Author: zhangxiongwei
  * @Date: 2021-10-26 15:41
  * @Description: Recommended nearby
  */
@Slf4j
@RestController
@Api(tags = "redis", description = "redis control")
@RequestMapping("/geo")
@AllArgsConstructor
public class RedisGeoController {
    private static final String GEO_STAGE = "cities";
    private final RedisTemplate&lt;String, String&gt; redisTemplate;
    private final BoundGeoOperations&lt;String, String&gt; citiesGeoOps;
    /**
      * Initialize the data and the position id and latitude and longitude can be stored in redis.
      * Add position data when adding occupations
      * When the user clicks near is, the latitude and longitude are transmitted.  Return to id to get job information and push it to the user
      */
    @GetMapping("/init")
    @ApiOperation("initialization")
    public void init() {
        // Clean up the cache        (GEO_STAGE);
        Map&lt;String, Point&gt; points = new HashMap&lt;&gt;();
        ("shijiazhuang", new Point(114.48, 38.03));
        ("xingtang", new Point(114.54, 38.42));
        ("guangcheng", new Point(114.84, 38.03));
        ("gaoyi", new Point(114.58, 37.62));
        ("zhaoxian", new Point(114.78, 37.76));
        ("jinxing", new Point(114.13, 38.03));
        ("luquan", new Point(114.03, 38.08));
        ("xinle", new Point(114.67, 38.33));
        ("zhengding", new Point(114.56, 38.13));
        // Add geographic information        (GEO_STAGE).add(points);
    }
    @PostMapping("/city")
    @ApiOperation("Get the City")
    public CommonResult&lt;GeoResults&lt;&lt;String&gt;&gt;&gt; dis(@RequestBody LocationBo locationBo) {
        //Set the current location        Point point = new Point((), ());
        //Set the radius range        Metric metric = ;
        Distance distance = new Distance((), metric);
        Circle circle = new Circle(point, distance);
        //Set parameters including distance, coordinates, and number of digits         args = RedisGeoCommands
                .GeoRadiusCommandArgs
                .newGeoRadiusArgs()
                .includeDistance()
                .includeCoordinates()
                .sortAscending()
                .limit(());
        GeoResults&lt;&lt;String&gt;&gt; radius = (circle, args);
        return (radius);
    }
}

Test data

### Use httpclientPOST http://localhost:6001/geo/city
Content-Type: application/json
{
  "longitude": 114.56,
  "latitude": 38.13,
  "radius": 100000,
  "limit": 10
}

Return result

{
  "code": 200,
"message": "The operation was successful",
  "data": {
    "averageDistance": {
      "value": 31642.19217777778,
      "metric": "METERS",
      "unit": "m",
      "normalizedValue": 0.004961039905191403
    },
    "content": [
      {
        "content": {
          "name": "zhengding",
          "point": {
            "x": 114.55999821424484,
            "y": 38.12999923666221
          }
        },
        "distance": {
          "value": 0.1778,
          "metric": "METERS",
          "unit": "m",
          "normalizedValue": 2.787647866453794E-8
        }
      },
      {
        "content": {
          "name": "shijiazhuang",
          "point": {
            "x": 114.55999821424484,
            "y": 38.02999941748397
          }
        },
        "distance": {
          "value": 13144.3531,
          "metric": "METERS",
          "unit": "m",
          "normalizedValue": 0.0020608452123245394
        }
      },
      {
        "content": {
          "name": "xinle",
          "point": {
            "x": 114.55999821424484,
            "y": 38.329998875018696
          }
        },
        "distance": {
          "value": 24232.5609,
          "metric": "METERS",
          "unit": "m",
          "normalizedValue": 0.0037993164618445796
        }
      },
      {
        "content": {
          "name": "guangcheng",
          "point": {
            "x": 114.55999821424484,
            "y": 38.02999941748397
          }
        },
        "distance": {
          "value": 26919.7324,
          "metric": "METERS",
          "unit": "m",
          "normalizedValue": 0.004220626242427844
        }
      },
      {
        "content": {
          "name": "xingtang",
          "point": {
            "x": 114.55999821424484,
            "y": 38.419999219223335
          }
        },
        "distance": {
          "value": 32302.7819,
          "metric": "METERS",
          "unit": "m",
          "normalizedValue": 0.005064610857371048
        }
      },
      {
        "content": {
          "name": "jinxing",
          "point": {
            "x": 114.55999821424484,
            "y": 38.02999941748397
          }
        },
        "distance": {
          "value": 39255.7243,
          "metric": "METERS",
          "unit": "m",
          "normalizedValue": 0.006154732063610425
        }
      },
      {
        "content": {
          "name": "zhaoxian",
          "point": {
            "x": 114.55999821424484,
            "y": 37.760000919591185
          }
        },
        "distance": {
          "value": 45453.0791,
          "metric": "METERS",
          "unit": "m",
          "normalizedValue": 0.007126388018946599
        }
      },
      {
        "content": {
          "name": "luquan",
          "point": {
            "x": 114.55999821424484,
            "y": 38.07999932707309
          }
        },
        "distance": {
          "value": 46718.8049,
          "metric": "METERS",
          "unit": "m",
          "normalizedValue": 0.00732483559070619
        }
      },
      {
        "content": {
          "name": "gaoyi",
          "point": {
            "x": 114.55999821424484,
            "y": 37.62000066579741
          }
        },
        "distance": {
          "value": 56752.5152,
          "metric": "METERS",
          "unit": "m",
          "normalizedValue": 0.00889797682301274
        }
      }
    ]
  }
}

Response code: 200; Time: 92ms; Content length: 1844 bytes

All uploaded is a practice project, and you only need to change the city name to the occupation id

This is the article about Redis GEO's implementation of nearby search functions. For more relevant search content for Redis GEO, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!