Search code examples
javaneo4jspring-data-neo4jneo4j-spatial

neo4j adding spatial wgs84 point to node to calculate distance


i'm trying to add a lon lat point to a node. i was unable to find any doc regarding which java class should be used.

Here is what i have:

@NodeEntity
public class Coordination {

    @Id
    @GeneratedValue
    private Long id;

    @Index
    private Value point;


    private Double lon;
    private Double lat;
    @Relationship(type = "GEO_LOCATION", direction = Relationship.INCOMING)
    private List<GeoLocation> geoLocations;

    public Coordination(Double lon, Double lat) {
        Value point = new PointValue(new InternalPoint2D(4326, lon, lat));
        this.lon = lon;
        this.lat = lat;
    }
}

Value class is not working for me. what do i miss?


Solution

  • Using a CompositeAttributeConverter it is possible to define your own class to store lat and lon coordinates. However, you can also use the built-in Point and corresponding Distance classes defined in Spring Data Commons.

    Here's an example from the test cases in Spring Data Neo4j:

    public class Restaurant implements Comparable<Restaurant> {
    
        @Id @GeneratedValue private Long id;
        private String name;
        @Convert(PointConverter.class) private Point location; //Encapsulates lat/lon 
        private int zip;
        private double score;
        private String description;
        private boolean halal;
    

    You can then define methods such as:

    import org.springframework.data.geo.Point;
    import org.springframework.data.neo4j.conversion.PointConverter;
    
    public interface RestaurantRepository extends Neo4jRepository<Restaurant, Long> {
    
        List<Restaurant> findByNameAndLocationNear(String name, Distance distance, Point point);
    
        List<Restaurant> findByLocationNearAndName(Distance distance, Point point, String name);
    }
    

    The finder method will generate CYPHER that passes the following arguments to a distance function:

    • The lat and lon properties defined on your node
    • The at and lon arguments passed in as an argument to the finder method.

    Is this what you were looking for? If yes great! If not, could you please clarify your question.