Home > other >  Spring Boot neo4j query param
Spring Boot neo4j query param

Time:03-14

I'm trying to write Cypher queries for Neo4J with params in a Spring Boot project. There are many tutorials showing showing these things, but none of them work for me. One version goes like this:

@Query("MATCH p=(n:Phone {phoneId:{0}})-[f:calling]-(m) OPTIONAL MATCH (m)-[r]-() where length(p)<{1} return m,r")
...

This will get executed at is it, with the {0} and {1} in it, and obviously it doesn't work.

Some sites use this syntax:

@Query("MATCH (a:City {name:$departure}), (b:City {name:$arrival})\n"
        "MATCH p=(a)-[*]->(b)\n"
        "WITH collect(p) as paths\n"
        "CALL apoc.spatial.sortByDistance(paths) YIELD path, distance\n"
        "RETURN path, distance")
  List<Path> getAllPaths(String departure, String arrival);

This doesn't even compile. It says that the query must be a compile time constant.

If it was JPA with MySQL it would look like this:

    @Query("update blah b set b.foo = :foo, b.bar = :bar where b.id = :id")
    fun update(foo: String, bar: String, id: Int)

With Neo4J the :param part also ends up in the query without any value replacement.

So the main question is: how can I write Cypher queries for Neo4J with parameters in them? Bonus question: what's the story with these different syntax's? I've never heard about the first 2. Is that old stuff?

CodePudding user response:

Ok, I have figured it out. The right syntax is.... drum roll...

    @Query(value = "match (:Dude {dudeId: \$underlingId1})-[*0..]->(x)<-[*0..]-(:Dude {dudeId: \$underlingId2}) return x")
    fun findLCA(underlingId1: Int, underlingId2: Int): Dude

The equivalent Java syntax would be:

    @Query(value = "match (:Dude {dudeId: $underlingId1})-[*0..]->(x)<-[*0..]-(:Dude {dudeId: $underlingId2}) return x")
    Dude findLCA(Integer underlingId1, Integer underlingId12);

So the Neo4J library does the trick with the $ character, that needs to be escaped in Kotlin.

  • Related