3

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?

Tom Stambaugh
  • 1,019
  • 13
  • 18

1 Answers1

0

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)
zirkelc
  • 1,451
  • 1
  • 23
  • 49
  • I understand this, and it seems unresponsive to my question. The `MATCH` query that I offered in my topic-starter works as desired. My question whether there is any advantage to using an apparently synonymous `apoc` call. In what circumstances do I choose an `apoc` call over a "plain" cypher query with the same behavior? – Tom Stambaugh Sep 08 '22 at 21:37
  • For the query provided in your question, there is **zero** advantage of using APOC over plain Cypher. It just causes an overhead of calling a custom procedure and interrupts the query planner to calculate the optimal traversing path. However, in my answer I wanted to provide an explanation for using these APOC procedures. Namely, they are a flexible alternative to [variable length relationships with multiple relationship types](https://neo4j.com/docs/cypher-manual/current/clauses/match/#varlength-rels-multiple-types). – zirkelc Sep 09 '22 at 06:21
  • Got it, I appreciate your attention. – Tom Stambaugh Sep 10 '22 at 14:40