wab
wab

Reputation: 857

NEO4J Cypher find nodes with multiple relationship counts

Graph

I've got a Neo4J database with broadly three types of graphs that look something like this:

  1. A single cat, fed by one human, who lives in one building. Graph 1

  2. A single cat, fed by two humans, who live in the same building Same cat, different humans, same building

  3. A single cat, who is being fed by multiple humans who all live in different buildings Same cat, different humans, and different buildings

Query

The data has lots of small graphs of this kind. I want to select the graphs where the Cat is fed by more humans than the humans have buildings. count(cat fed by human) > count(human lives in building) for each graph.

To select cats with multiple humans I can run:

MATCH (cat:CAT)-[fed_by:FED_BY]-(:Human)
WITH cat, count(fed_by) as n_feeders
WHERE n_feeders > 1
MATCH g=(cat)-[:FED_BY]-(:Person)-[:LIVES_AT]-(:Building)
RETURN g
LIMIT 10

But how can I add the condition that the number of (:Cat)-[:FED_BY]-(:Human) relationships must be greater than the number of (:Human)-[:LIVES_IN]-(:Building) relationships?

Upvotes: 0

Views: 1265

Answers (1)

Rajendra Kadam
Rajendra Kadam

Reputation: 4052

You can find the Cats you are looking for with the following query.

You can return the graph for these cats at the end.

MATCH (cat:CAT)-[:FED_BY]-(person:Person)-[:LIVES_AT]-(building:Building)
WITH cat, COUNT(DISTINCT person) as n_feeders, COUNT(DISTINCT building) as n_buildings
WHERE n_feeders > n_buildings
RETURN cat

Upvotes: 1

Related Questions