Dragos
Dragos

Reputation: 776

Neo4J Cypher combine 2 queries into one

I got 2 node types, let's say A and B, and a relationship with a property, let's call it 'a_has_b' with the property 'value'

First I want to count the number of relationships a specific node of type A has.

MATCH (a:A)-[r:a_has_b]->(b:B) 
WHERE a.id='123'
RETURN COUNT(r) as count

I also want to get the top n B's ordered by the property from the relationship

MATCH (a:A)-[r:a_has_b]->(b:B)
WHERE a.id='123'
RETURN r, b
ORDER BY r.value
LIMIT 3

Now, it's clearly I am doing the same thing twice, changing the return value.

How can I combine them together to get both needed results?

Upvotes: 0

Views: 1074

Answers (1)

stdob--
stdob--

Reputation: 29172

You can combine collect and range:

MATCH  (a:A)-[r:a_has_b]->(b:B) 
       WHERE a.id='123'
WITH   a, 
       r, 
       b 
       ORDER BY r.value
RETURN a, 
       COUNT(r) AS count, 
       COLLECT([r,b])[0..3] AS rels

Upvotes: 5

Related Questions