neo4jcypherspatialcypher-dsl

Query neo4j with Cypher DSL using point.withinBBox()


I want to find locations in my neo4j database that are within a bounding box. There is a function called point.withinBBox() that I want to use. I build my queries dynamically using Cypher DSL. This is the kind of query I want to run:

MATCH (loc:Location)
WHERE point.withinBBox(loc.coordinates, point({longitude: 2.592773, latitude: 46.346928}), point({longitude: 18.654785, latitude: 55.714735}))
RETURN loc

In my Java code I dynamically chain conditions like this:

conditions = Conditions.noCondition();
conditions = conditions.and(new_condition);

So I want to get a Condition that encapsulates the point.withinBBox() part.


Solution

  • There is no built-in Functions call to do this yet, but you can easily create a custom one via Cypher.call. The function returned can be turned into a condition via .asCondition() like this:

    @Test
    void bbBox() {
    
        Node location = Cypher.node("Location").named("loc");
        Expression sw = Functions.point(Cypher.mapOf("latitude", Cypher.literalOf(46.346928), "longitude", Cypher.literalOf(2.592773)));
        Expression ne = Functions.point(Cypher.mapOf("latitude", Cypher.literalOf(55.714735), "longitude", Cypher.literalOf(18.654785)));
        Expression withinBBox = Cypher.call("point.withinBBox")
            .withArgs(location.property("coordinates"), sw, ne).asFunction();
    
        Condition conditions = Conditions.noCondition();
        conditions = conditions.and(withinBBox.asCondition());
    
        String stmt = Cypher.match(location).where(conditions).returning(location).build().getCypher();
        assertThat(stmt).isEqualTo("MATCH (loc:`Location`) WHERE point.withinBBox(loc.coordinates, point({latitude: 46.346928, longitude: 2.592773}), point({latitude: 55.714735, longitude: 18.654785})) RETURN loc");
    }