Finding associations using Cypher

Asked by At

I have associated IDs in a csv format.

For example :

ID, Associated_ID
1,2
3,4
8,1
2,100
100,100
8,101
200,200

I want to get all associated IDs.

In this case, the expected result is:

[1,2,8,100,101]

[3,4]

[200]

load csv from 'file:///test/test.data'  AS line 
CREATE (:ids { mc: line[0], associated_mc:line[1]})
MERGE (m1:id {name: line[0]}) 
MERGE (m2:id {name: line[1]}) 
MERGE (m1)-[:SAME]->(m2);
MATCH p=(a)-[r:SAME*]-(b) RETURN p;

2 Answers

0
Raj On

You are creating a database and retrieving it in a single query. You should run separate queries these two.

You don't need to write CREATE when creating nodes MERGE will do same avoiding duplicates. So you can load data with the following query:

LOAD CSV FROM 'file:///test/test.data'  AS line 
MERGE (m1:id {name: toInt(line[0])}) 
MERGE (m2:id {name: toInt(line[1])}) 
MERGE (m1)-[:SAME]->(m2);

And get the required result with the following query:

MATCH p=(start:id)-[:SAME*]->(end:id)
WHERE 
    NOT EXISTS ((end)-[:SAME]->()) 
    AND 
    NOT EXISTS ((start)<-[:SAME]-()) 
return EXTRACT(node IN nodes(p) | node.name)

If you don't put where condition you will get too many paths of which are part of other longer paths. You can verify results by removing WHERE condition

0
Reshmi S On

This worked for me -

MATCH (m:id)
CALL apoc.path.subgraphAll(m, {relationshipFilter:'SAME'}) YIELD nodes
with EXTRACT(node IN nodes | node.name) as ex_nodes
return  distinct apoc.coll.sort(ex_nodes);