Neo4j, get all the relationships between a set of nodes

I have a query that retrieves nodes based on a property

MATCH (c { type: 'sometype' }) WITH c LIMIT 100 RETURN c 

all I want is to also get all the relationships between the nodes in the result set, in IRC someone told me to use:

 MATCH (c { type: 'sometype']) WITH c LIMIT 100 OPTIONAL MATCH (c)-[r]-() RETURN c, r 

but this will include relationships from node c to nodes outside the result set, which in my case (several hundred thousand relationships) can create very large useless results or performance problems)

Is there any way to achieve this?

+6
source share
6 answers

Alex

Another way to approach this is with this query:

 MATCH (c {type : 'sometype'})-[r:*0..1]-(d {type : 'sometype'}) WITH c, collect(r) as rs RETURN c, rs 

This allows you to use the case when there is no such relationship.

Grace and peace

Jim

+1
source

I think there are several ways to do this. One approach is to find all the nodes for a given type and build a collection ( cs ) from them. Then map this group again, this time with the outgoing relationship with any node and filter it to make sure endnode is in cs :

 MATCH (c {type:'sometype'}) WITH collect(c) as cs MATCH (x {type:'sometype'})-[r]->(y) WHERE y in cs RETURN startNode(r).name, endNode(r).name 

I don’t know your graph model, but I think it would be nice to reorganize the type='sometype' property to type='sometype' label. In this case, the request will look like this:

 MATCH (c:Group1) WITH collect(c) as cs MATCH (x:Group1)-[r]->(y) WHERE y in cs RETURN startNode(r).name, endNode(r).name 
+3
source

This is straight.

 MATCH (a)-[r]-(b) WHERE a.type = 'foo' AND b.type = 'foo' RETURN DISTINCT r 

You can also use the new syntax:

 MATCH (a { type : 'foo' }) -[r] - (b {type : 'foo'}) RETURN DISTINCT r 

If you prefer it.

+3
source

It is better if you used labels instead of properties for the type. This will make your queries very fast using schema indices.

 MATCH (a:SOMETYPE) -[r] - (b :SOMETYPE) RETURN DISTINCT r 
+1
source

The fastest way I've found is:

  MATCH (n:NodeName {param:"7"}) with n skip 0 limit 5 MATCH n-[r]->(k) with n,k,r 

You can also reduce the execution time if instead of n, k, r n.data, r.data, k.data will be used strong>

This has been tested on Neo4j 2.3

0
source

To minimize the necessary matches, you can try the following:

 MATCH (c { type: 'sometype'}) WITH c LIMIT 100 WITH COLLECT(c) as cNodes UNWIND cNodes as c1 MATCH (c1)-[r]->(c2) WHERE c2 in cNodes RETURN c1, TYPE(r) as rel, c2 

As already mentioned, matching without labels is not recommended, since all nodes should be scanned, as the size of db grows, the query will be slower and slower. Use the shortcut in the original match, if possible, and if there is an index on the shortcut and its type property, this can be a very quick query.

0
source

Source: https://habr.com/ru/post/973541/


All Articles