Martin
Martin

Reputation: 116

How do I get the list of a node relationships which is ordered by the properties of the relationship?

I want to get a list of nodes's relationships which is ordered by relationship's properties. For example, I have two labels for my nodes which are Org and Company, there is only one relationship type between them which is INVEST_IN. The INVEST_IN relationship has a property "Series" which could be "Series A","Series B","Series C" So the graph is like as followed:

merge (o:Org{name:'Google'})
merge (o2:Org{name:'Facebook'})
merge (c:Company{name:'Company1'})
merge (c2:Company{name:'Company2'})
merge (o)-[:INVEST_IN{series:'A'}]-(c)
merge (o)-[:INVEST_IN{series:'B'}]-(c)
merge (o)-[:INVEST_IN{series:'C'}]-(c)
merge (o)-[:INVEST_IN{series:'A'}]-(c2)
merge (o)-[:INVEST_IN{series:'B'}]-(c2)
merge (o2)-[:INVEST_IN{series:'C'}]-(c)
merge (o2)-[:INVEST_IN{series:'B'}]-(c2)
merge (o2)-[:INVEST_IN{series:'C'}]-(c2)

enter image description here

So I need the result like:

Org ordered_series

Google [A,B,C]
Facebook [C,B]

The result is ordered by the number of series of each Org's relationship. Google has 2 A series, 2 B series, 1 C series, so the result is [A,B,C] Facebook has 1 B series and 2 C series so the result is [C,B]

match (o:Org)-[r:INVEST_IN]->(c:Company)
return o.name, r.series, count(r.series)

return the enter image description here

and I do not understand the difference between

match (o:Org)-[r:INVEST_IN]->(c:Company)
return o.name, r.series, count(r.series)

and

match (o:Org)-[r:INVEST_IN]->(c:Company)
with o, r, count(r.series) as cr
return o.name, r.series, cr

They are so different. I could not order the relationship and collect them. Can anyone show me how do I do it?

Upvotes: 0

Views: 142

Answers (1)

cybersam
cybersam

Reputation: 66989

Your 2 queries are logically the same, as long as Org nodes have unique name values.

This query:

MATCH (o:Org)-[r:INVEST_IN]->(c:Company)
RETURN o.name AS name, r.series AS series, COUNT(r.series) AS cnt
ORDER BY name ASC, cnt DESC

produces this result:

╒══════════╤════════╤═════╕
│"name"    │"series"│"cnt"│
╞══════════╪════════╪═════╡
│"Facebook"│"C"     │2    │
├──────────┼────────┼─────┤
│"Facebook"│"B"     │1    │
├──────────┼────────┼─────┤
│"Google"  │"A"     │2    │
├──────────┼────────┼─────┤
│"Google"  │"B"     │2    │
├──────────┼────────┼─────┤
│"Google"  │"C"     │1    │
└──────────┴────────┴─────┘

[UPDATE]

To get the series for each Org in a list:

MATCH (o:Org)-[r:INVEST_IN]->(c:Company)
WITH o.name AS name, r.series AS series, COUNT(r.series) AS cnt
ORDER BY name ASC, cnt DESC
RETURN name, COLLECT(series) AS seriesList

which produces this result:

╒══════════╤═════════════╕
│"name"    │"seriesList" │
╞══════════╪═════════════╡
│"Facebook"│["C","B"]    │
├──────────┼─────────────┤
│"Google"  │["A","B","C"]│
└──────────┴─────────────┘

Upvotes: 1

Related Questions