0
votes

I would like to query for the following subgraph in my Neo4J database:

(a)-->(b)-->(c)-->(d)
       |
       | -->(e)

Note: a, b, c, d, e are attribute values (non-unique values) for each of the nodes. There are thousands for these nodes with similar attribute values (a to e) but they are randomly connected to one another.

How can I write the Cyper query to specifically find the particular subgraph (akin to subgraph isomorphism problem) I seek and return (a)? I've tried the following Cyper query but other subgraphs pop up:

START n1=node:SomeIndex(AttrVal="a")
MATCH n1-[]->n2-[]->n3-[]->n4
WHERE n2.AttrVal="b" AND n3.AttrVal="c" and n4.AttrVal="d"
WITH  n1, n2
MATCH n2-[]->n5
WHERE n5.AttrVal="e"
RETURN n1

Am I using the WITH and 2nd MATCH clause wrongly?

Thanks!

1
Could you describe in natural language what your query should really do? Your cypher statement does not fit the ascii art graph since you match for n1-->n5 in Cypher but b is connected to e in ascii.Stefan Armbruster
Stefan - Updated the code example to match the ASCII graph correctly. I'm essentially trying to do subgraph matching here, in a database full of all these node with various attribute values.Victor Neo

1 Answers

1
votes

You can use the comma to combine multiple paths in a single match clause:

START n1=node:SomeIndex(AttrVal="a")
MATCH n1-[]->n2-[]->n3-[]->n4, n2-[]->n5
WHERE n2.AttrVal="b" AND n3.AttrVal="c" and n4.AttrVal="d" and n5.attrVal='e'
RETURN n1

Side note 1: you can also refactor the statement like this:

START n1=node:SomeIndex(AttrVal="a"), n2=node:SomeIndex(AttrVal="b")
n3=node:SomeIndex(AttrVal="c"), n4=node:SomeIndex(AttrVal="d"),
n5=node:SomeIndex(AttrVal="e")
MATCH n1-[]->n2-[]->n3-[]->n4, n2-[]->n5
RETURN n1

Depending on the structure of your graph the second might be faster.

Side note 2: When matching an arbitrary relationship type as you did in n1-[]->n2 you can use a shorter and more readable notation: n1-->n2