简体   繁体   中英

Find largest path featuring pattern in Neo4j with Cypher

I have the following node types, and a pattern to find:

Node Labels

Questions Outcomes

Relationship

Answers (with a 'title' field)

I want to "find all questions that are connected to each other by "no" answers and all have a "yes" answer to the same outcome" - i suspect there are hundreds of these groups in my database, some are just two nodes in size, some are up to 5 or 6 nodes. None bigger than six.

So I can match all answers joined by nos in a 2-group:

(outcome)<-[yes]-(question)->[no]->(question)->[yes]->(outcome)

But i can't figure out how to apply that to 3 or 4-groups. I thought i could perhaps do a straight:

(question)<-[no][0..*]-(question) - and find all the questions joined by nos, then in a WHERE clause add something like WHERE all matched questions point to -> outcome - but i have no idea how to express that in cypher

Can anyone help?

[RE-RE-EDITED]

This might work for you.

MATCH p=(oc:Outcome)<-[:Answer {title: 'yes'}]-(q1:Question)-[:Answer* {title: 'no'}]->(q2:Question)-[:Answer {title: 'yes'}]->(oc)
WHERE
  NOT (
    (oc)<-[:Answer {title: 'yes'}]-(:Question)-[:Answer {title: 'no'}]->(q1) OR
    (q2)-[:Answer {title: 'no'}]->(:Question)-[:Answer {title: 'yes'}]->(oc)
  ) AND
  ALL(q IN NODES(p)[1..-1] WHERE (q)-[:Answer {title: 'yes'}]->(oc))
RETURN oc, NODES(p)[1..-1] AS questions;

The NOT (...) term in the WHERE clause is there to make sure we only use the longest valid sequences of Questions .

Each result row contains a shared outcome and an ordered collection of Question nodes.

This query can take a long time to finish, as it does not specify an upper bound for the variable length pattern. You may want to specify an appropriate upper bound if this is a problem (eg, Answer*..5 ).

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