Mowi
Mowi

Reputation: 21

Neo4j query for getting first few nodes with highest degree

I am a total beginner with Neo4j and need help. Is there a query for getting the first few nodes with highest degree?

I have nodes called P and nodes called A. There are only links between P and A nodes. I want to have the first 10 nodes P which have the most links to nodes A.

My idea was the following query, but it took so much time!

MATCH (P1:P)-[r]->(A1:A)
RETURN P1.name AS P_name, COUNT(A1) AS A_no
ORDER BY no DESC
LIMIT 10

Is there something wrong with my query?

Best,

Mowi

Upvotes: 2

Views: 2904

Answers (1)

Michael Hunger
Michael Hunger

Reputation: 41706

How many nodes do you have in your db?

I'd probably not use cypher for that, the Java API actually has a node.getDegree() method which is much much faster.

Your query could be sped up a bit by

MATCH (P1:P)-->() 
RETURN id(P1),count(*) as degree 
ORDER BY degree DESC LIMIT 10

you could also try:

MATCH (P1:P)
RETURN id(P1),size((P1)-->()) as degree 
ORDER BY degree DESC LIMIT 10

for limiting the nodes:

MATCH (P1:P)
WHERE P1.foo = "bar"
WITH P1 limit 10000
MATCH (P1)-->() 
RETURN id(P1),count(*) as degree 
ORDER BY degree DESC LIMIT 10

Upvotes: 3

Related Questions