Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Neo4j Cypher recursive query

Tags:

neo4j

cypher

I have a Cypher query that returns a TagSynonym node between two Tag nodes:

MATCH (t:Tag)<-[:FOR]-(ts:TagSynonym)-[:HAS]->(s:Tag) 
WHERE t.id = {tagId} AND s.id = {synonymId} 
RETURN ts

Additionally, the s:Tag node itself can have its own TagSynonym nodes like:

(s)<-[:FOR]-(ts:TagSynonym)-[:HAS]->(ss:Tag) 

and ss can have its own TagSynonym and so on and so forth.

The depth of this structure can be pretty big.

Please help me to extend this query in order to return all TagSynonym established on t:Tag and all of its synonym successors(tags for s:Tag and deeper up to the end of this recursive structure.)

like image 433
alexanoid Avatar asked Nov 18 '25 01:11

alexanoid


1 Answers

Does something like this look like it is going in the right direction?

Basically use apoc.path.expandConfig to start at s and start grabbing new TagSynonym and Tag nodes.

MATCH (t:Tag)<-[:FOR]-(ts:TagSynonym)-[:HAS]->(s:Tag) 
WHERE t.id = {tagId} AND s.id = {synonymId} 
WITH t, ts, s
CALL apoc.path.expandConfig(s
{
  uniqueness:"NODE_GLOBAL",
  labelFilter:"TagSynonym|Tag",
  relationshipFilter: '<FOR|HAS>'
}) YIELD path
RETURN t, ts, s, path

Optionally, to achieve something similar without using the APOC library you could consider something along the lines of this query...

MATCH (t:Tag)<-[:FOR]-(ts:TagSynonym)-[:HAS]->(s:Tag) 
WHERE t.id = {tagId} AND s.id = {synonymId} 
WITH t,ts,s
OPTIONAL MATCH p=(s)-[:FOR|HAS*]-(end:Tag)
WHERE NOT (end)<-[:FOR]-()
RETURN p
like image 109
Dave Bennett Avatar answered Nov 20 '25 22:11

Dave Bennett



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!