Search code examples
cassandracql3

Find points within a distance using CQL3


I have a cassandra table with user name, latitude and longitude. I would like to get a list of users who are inside the circle with a given latitude, longitude and distance.

For example: my input Lat= 78.3232 and Long = 65.3234 and distance = 30 miles.

I would like to get a list of users who are within 30 miles distance from the point 78.3232 and 65.3234. Is it possible to solve this with single CQL3 query? Or can anyone give me a hint start solving this query?


Solution

  • There was no geospatial support for cassandra so I found a way to Implement it mathematically to generate box coordinates around the point (That was good enough for my work) and use query to get coordinates within boundary. I'll post the code for others reference.

    public class GeoOperations {
    
    public static final int UPPER_LATITUDE = 0;
    public static final int LOWER_LATITUDE = 1;
    public static final int UPPER_LONGITUDE = 2;
    public static final int LOWER_LONGITUDE = 3;
    private static final double KM_TO_MILES = 0.621371;
    private final double Latitude;
    private final double Longitude;
    
    double Boundary[];
    
    public GeoOperations(double init_latitude, double init_longitude) {
        Latitude = init_latitude;
        Longitude = init_longitude;
        Boundary = new double[4];
    }
    
    public void GenerateBoxCoordinates(double Distance) {
        Distance = Distance * KM_TO_MILES;
        double Lat_Factor = (Distance) / 69;
        Boundary[UPPER_LATITUDE] = Latitude + Lat_Factor;
        Boundary[LOWER_LATITUDE] = Latitude - Lat_Factor;
    
    
        double Long_Factor = (Distance) / (3960 * 2 * Math.PI / 360 * Math.cos(Latitude));
        Boundary[UPPER_LONGITUDE] = Longitude + Long_Factor;
        Boundary[LOWER_LONGITUDE] = Longitude - Long_Factor;
    
        for (double x : Boundary) {
            System.out.println(x);
        }
    
    }
    }
    

    And then Used Simple CQL to find coordinates within ranges

    if values are like this

        UPPER_LATITUDE = 60
        LOWER_LATITUDE = 40
        UPPER_LONGITUDE = 10
        LOWER_LONGITUDE = 5
    

    Query will be something like this (actually I used kundera with Hibernate and used a JPA query. So I havent tested it but it should work)

    SELECT * FROM Points_Tablle
        WHERE  LATITUDE > 40 
        AND LATITUDE < 60 
        AND LONGITUDE > 5
        AND LONGITUDE < 10;