|
| 1 | +from typing import Annotated, Any, Literal, Tuple, Union |
| 2 | + |
| 3 | +from pydantic import BeforeValidator, PlainSerializer |
| 4 | +from pydantic_extra_types.coordinate import Coordinate |
| 5 | + |
| 6 | + |
| 7 | +RadiusUnit = Literal["m", "km", "mi", "ft"] |
| 8 | + |
| 9 | + |
| 10 | +class GeoFilter: |
| 11 | + """ |
| 12 | + A geographic filter for searching within a radius of a coordinate point. |
| 13 | +
|
| 14 | + This filter is used with GEO fields to find models within a specified |
| 15 | + distance from a given location. |
| 16 | +
|
| 17 | + Args: |
| 18 | + longitude: The longitude of the center point (-180 to 180) |
| 19 | + latitude: The latitude of the center point (-90 to 90) |
| 20 | + radius: The search radius (must be positive) |
| 21 | + unit: The unit of measurement ('m', 'km', 'mi', or 'ft') |
| 22 | +
|
| 23 | + Example: |
| 24 | + >>> # Find all locations within 10 miles of Portland, OR |
| 25 | + >>> filter = GeoFilter( |
| 26 | + ... longitude=-122.6765, |
| 27 | + ... latitude=45.5231, |
| 28 | + ... radius=10, |
| 29 | + ... unit="mi" |
| 30 | + ... ) |
| 31 | + >>> results = await Location.find( |
| 32 | + ... Location.coordinates == filter |
| 33 | + ... ).all() |
| 34 | + """ |
| 35 | + |
| 36 | + def __init__( |
| 37 | + self, longitude: float, latitude: float, radius: float, unit: RadiusUnit |
| 38 | + ): |
| 39 | + # Validate coordinates |
| 40 | + if not -180 <= longitude <= 180: |
| 41 | + raise ValueError(f"Longitude must be between -180 and 180, got {longitude}") |
| 42 | + if not -90 <= latitude <= 90: |
| 43 | + raise ValueError(f"Latitude must be between -90 and 90, got {latitude}") |
| 44 | + if radius <= 0: |
| 45 | + raise ValueError(f"Radius must be positive, got {radius}") |
| 46 | + |
| 47 | + self.longitude = longitude |
| 48 | + self.latitude = latitude |
| 49 | + self.radius = radius |
| 50 | + self.unit = unit |
| 51 | + |
| 52 | + def __str__(self) -> str: |
| 53 | + return f"{self.longitude} {self.latitude} {self.radius} {self.unit}" |
| 54 | + |
| 55 | + @classmethod |
| 56 | + def from_coordinates( |
| 57 | + cls, coords: Coordinate, radius: float, unit: RadiusUnit |
| 58 | + ) -> "GeoFilter": |
| 59 | + """ |
| 60 | + Create a GeoFilter from a Coordinates object. |
| 61 | +
|
| 62 | + Args: |
| 63 | + coords: A Coordinate object with latitude and longitude |
| 64 | + radius: The search radius |
| 65 | + unit: The unit of measurement |
| 66 | +
|
| 67 | + Returns: |
| 68 | + A new GeoFilter instance |
| 69 | + """ |
| 70 | + return cls(coords.longitude, coords.latitude, radius, unit) |
| 71 | + |
| 72 | + |
| 73 | +CoordinateType = Coordinate |
| 74 | + |
| 75 | + |
| 76 | +def parse_redis(v: Any) -> Union[Tuple[str, str], Any]: |
| 77 | + """ |
| 78 | + Transform Redis coordinate format to Pydantic coordinate format. |
| 79 | +
|
| 80 | + The pydantic coordinate type expects a string in the format 'latitude,longitude'. |
| 81 | + Redis stores coordinates in the format 'longitude,latitude'. |
| 82 | +
|
| 83 | + This validator transforms the input from Redis into the expected format for pydantic. |
| 84 | +
|
| 85 | + Args: |
| 86 | + v: The value from Redis (typically a string like "longitude,latitude") |
| 87 | +
|
| 88 | + Returns: |
| 89 | + A tuple of (latitude, longitude) strings if input is a coordinate string, |
| 90 | + otherwise returns the input unchanged. |
| 91 | +
|
| 92 | + Raises: |
| 93 | + ValueError: If the coordinate string format is invalid |
| 94 | + """ |
| 95 | + if isinstance(v, str): |
| 96 | + parts = v.split(",") |
| 97 | + |
| 98 | + if len(parts) != 2: |
| 99 | + raise ValueError( |
| 100 | + f"Invalid coordinate format. Expected 'longitude,latitude' but got: {v}" |
| 101 | + ) |
| 102 | + |
| 103 | + return (parts[1], parts[0]) # Swap to (latitude, longitude) |
| 104 | + |
| 105 | + return v |
| 106 | + |
| 107 | + |
| 108 | +Coordinates = Annotated[ |
| 109 | + CoordinateType, |
| 110 | + PlainSerializer( |
| 111 | + lambda v: f"{v.longitude},{v.latitude}", |
| 112 | + return_type=str, |
| 113 | + when_used="unless-none", |
| 114 | + ), |
| 115 | + BeforeValidator(parse_redis), |
| 116 | +] |
0 commit comments