Andreas Kuczera
Andreas Kuczera

Reputation: 363

neo4j cypher compare chain of nodes

Given a text in a graph-db with the words as nodes:

... (:word {text:'Die'})-[:NEXT]->(:word {text:'Natur'})-[:NEXT]->(:word {text:'selbst'})-[:NEXT]->(:word {text:'ist'})-[:NEXT]->(:word {text:'Einheit'})-[:NEXT]->(:word {text:'in'})-[:NEXT]->(:word {text:'der'})-[:NEXT]->(:word {text:'Vielheit'}) ... 

Now i want to find parts of the chain where the words:

(Natur), (Einheit) and (Vielheit)

occur within a range of max. 10 word-nodes.

Upvotes: 1

Views: 163

Answers (1)

Dave Bennett
Dave Bennett

Reputation: 11216

Something like this...

// look for paths from two to nine relationships in length 
MATCH p=(n:Node)-[:NEXT*2..9]->(:Node) 

// find paths that have all of the words
WHERE ALL(label in ['Natur','Einheit','Vielheit'] where label in 
extract(node in nodes(p) | node.name ))

// return the nodes of the matching paths
RETURN nodes(p)

This is a superior approach. Be sure and and an index on :Word(test).

// list of words
WITH ['Natur','Einheit','Vielheit'] AS texts

// find paths that include three words
MATCH path=(word1:Word )-[:NEXT*1..8]->(word2:Node)-[:NEXT*1..8]->(word3:Node)

// where each word is in your list
WHERE word1.text in texts
AND word2.text in texts
AND word3.text in texts

// and none of the words are the same
AND word1.text <> word2.text
AND word2.text <> word3.text
RETURN path

Upvotes: 1

Related Questions