Why use apoc instead of cypher for simple queries?

Viewed 116

I have written (and optimized, using "PROFILE") a Cypher query that answers neighbors of a node given the node. Now I find an apoc procedure (apoc.neighbors.athop) that seems to do the same thing.

Is the APOC version better? Faster? More robust?

I understand the value of APOC when there is no counterpart in regular Cypher for the given behavior. In the case of collecting neighbors, the Cypher seems easy:

MATCH (target:SomeLabel)
WITH target

MATCH (target)-[:ADJOINS]-(neighbor:SomeLabel)
WITH target, neighbor

As I understand it, the APOC counterpart is:

MATCH (target:SomeLabel)
WITH target

CALL apoc.neighbors.athop(target, "ADJOINS", 1)
YIELD node
RETURN node

Why would I choose the latter over the former?

1 Answers

The OPTIONAL MATCH clause should achieve the same result:

MATCH (target:SomeLabel)
OPTIONAL MATCH (target)-[:ADJOINS]-(neighbor:SomeLabel)
RETURN target, neighbor

According to the documentation, OPTIONAL MATCH was introduced in Neo4j 3.5, so maybe it didn't exist when this question was asked.

On the other hand, the APOC procedures apoc.neighbours.athop/byhop/tohop allow you to pass the relationship pattern, i.e. type and direction (incoming, outgoing, bidirectional), and the distance, i.e. the number of hops between two nodes, as dynamic parameters. This means that you can determine the relationship pattern and length in your application and pass them as parameters to the Neo4j driver.

Example for apoc.neighbors.tohop:

MATCH (p:Person {name: "Emil"})
CALL apoc.neighbors.byhop(p, "KNOWS", 2)
YIELD nodes
RETURN nodes

This query would traverse these relationships:

  • (praveena)-[:FOLLOWS]-(joe)
  • (praveena)-[:FOLLOWS]-(joe)-[:FOLLOWS]→(mark)
Related