How to write dynamic query for neo4j in spring?
-
02-01-2020 - |
Question
I am implementing search on relationships. I would put list of relations types as parameter and I also want to use attributes of nodes to do query.
Example :
In neo4j, assume that I have following nodes and relationships.
node (name:"a") - like - node(name:"b")
node (name:"a") - follow - node(name:"c")
node (name:"a") - follow -node(name:"e")
node(name:"a") - like- node(name:"d")
node (name:"s") - like - node(name:"b")
node (name:"s") - follow - node(name:"g")
node (name:"s") - follow -node(name:"e")
node(name:"s") - like- node(name:"v")
For search I will pass list of relationship type
Example query : find the node who likes node with name "b" AND follows node with name "c" Result should be node with name "a".
But like and follow query would be dynamic. (any number of) How to write such query in spring?
Solution
execute the dynamic Cypher query with a Neo4jTemplate
or
add it as method on a repository for your entity, eg. UserRepository
(then it would be static in structure and dynamic with parameters).
MATCH (u:User {name:{user}})-[:LIKES]->(t:Thing {name:{thing}}),
(u:User {name:{user}})-[:FOLLOWS]->(f:User {name:{friend}})
RETURN u;
You could also extend your repository interface from the CypherDSLRepository to execute dynamic CypherDSL queries.