I've a query that fetches nodes based on a property
MATCH (c { type: 'sometype' })
WITH c LIMIT 100
RETURN c
all I want is to also fetch all the relations between nodes in the resultset, on IRC someone told me to use:
MATCH (c { type: 'sometype'])
WITH c LIMIT 100
OPTIONAL MATCH (c)-[r]-()
RETURN c, r
but that will include relationships from node c to nodes outside the resultset which in my case (some hundred thousand relationships) could create very big useless resultset or performance issues)
Is there any way to achieve that?
Return all elements When you want to return all nodes, relationships and paths found in a query, you can use the * symbol.
This will work in all versions of Neo4j that support the MATCH clause, namely 2.0. 0 and later. This is a minimum length of 3, and a maximum of 5. It describes a graph of either 4 nodes and 3 relationships, 5 nodes and 4 relationships or 6 nodes and 5 relationships, all connected together in a single path.
You can show everything with simple MATCH (n) RETURN n , as offical documentation suggests. START n=node(*) RETURN n from Neo4j 2.0 is deprecated: The START clause should only be used when accessing legacy indexes (see Chapter 34, Legacy Indexing). In all other cases, use MATCH instead (see Section 10.1, “Match”).
With UNWIND , you can transform any list back into individual rows. These lists can be parameters that were passed in, previously collect -ed result or other list expressions. One common usage of unwind is to create distinct lists. Another is to create data from parameter lists that are provided to the query.
I guess there are multiple ways to do that. One approach is to find all nodes for the given type and build a collection out of them (cs
). Then match again that group, this time with outgoing relationships to any node and filter that to make sure the 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
Don't know your graph model, but I think it could be a good idea to refactor the property type='sometype'
into a label sometype
. In this case the query would 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
This is straight forward.
MATCH (a)-[r]-(b)
WHERE a.type = 'foo' AND b.type = 'foo'
RETURN DISTINCT r
You could equally use the new syntax:
MATCH (a { type : 'foo' }) -[r] - (b {type : 'foo'})
RETURN DISTINCT r
If you prefer it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With