简体   繁体   中英

Neo4j Cypher execution time when using DESC vs ASC too slow

In my current nodejs application, I'm using Neo4j as the database and use its REST API. By running my unit tests, I discovered that I have two very slow running tests and tracked it down to the cypher query being the culprit for the bad performance itself. Now while the performance is still quite slow, at least the first case runs in a somewhat acceptable time for the use case on my local dev machine in about 300ms. However, the second query adds a whole second until I get the result (just two rows in my case) back. The only difference is that I'm using DESC instead of ASC ordering of the brand name.

Query 1

MATCH (Distributor {slug: "some-dist"})-[:SELLS]->(product:Product)-[:IS|:BELONGS_TO*0..5]->(Category {slug: "electrical"}),
(product)-[:HAS_BRAND]->(brand:Brand)
RETURN DISTINCT brand ORDER BY brand.name ASC

Query 2

MATCH (Distributor {slug: "some-dist"})-[:SELLS]->(product:Product)-[:IS|:BELONGS_TO*0..5]->(Category {slug: "electrical"}),
(product)-[:HAS_BRAND]->(brand:Brand)
RETURN DISTINCT brand ORDER BY brand.name DESC

Some data about the graph:

  • 4 Distributor nodes
  • ~600 Brand nodes
  • ~1500 Category nodes
  • ~30000 Product nodes

All slug properties have a constraint to be unique. The name property of the Brand name is indexed, too.

Why is it, that the second query is so much slower and how do I fix it?

I made the mistake and did not use the colon on the first node to specify its label. I actually created the internal rule that every node should have exactly one Label.

Matching by label is fast and the sorting of the result does not really have an impact, wether it's ascending or descending order. It still does not explain the noticed behavior, but let this be a reminder to use labels in your cypher queries.

MATCH (:Distributor {slug: "some-dist"})-[:SELLS]->(product:Product)-[:IS|:BELONGS_TO*0..5]->(Category {slug: "electrical"}),
(product)-[:HAS_BRAND]->(brand:Brand)
RETURN DISTINCT brand ORDER BY brand.name DESC

does the trick for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM