יום שישי, 24 במאי 2013

Cypher Optional relationships

The cypher optional relationships is equivalent to the SQL outer join .
It is declared by using the [?] sign and it is used in the case where  if there is no relationship or node found we wants the query to return a null node instead of not returning a result at all .

The sample DB used in this post :
from py2neo import neo4j
from py2neo import node, rel
from py2neo import  cypher

graph_db = neo4j.GraphDatabaseService("http://localhost:7474/db/data/")

die_hard = graph_db.create(
    node(name="Bruce Willis"),
    node(name="John McClane"),
    node(name="Alan Rickman"),
    node(name="Hans Gruber"),
    node(name="Nakatomi Plaza"),
    rel(0, "PLAYS", 1),
    rel(2, "PLAYS", 3),
    rel(1, "VISITS", 4),
    rel(3, "STEALS_FROM", 4),
    rel(1, "KILLS", 3),
)

Running the following example :

theCyperCode = "START Bruce=node(1) MATCH Bruce-->ConnectedNode-[?]->NodeConectedToConnectedNode RETURN ConnectedNode, NodeConectedToConnectedNode"

cypher.execute(graph_db, theCyperCode, row_handler=handle_row)
produce the following results :
cypher query result:
(2 {"name":"John McClane"})
(5 {"name":"Nakatomi Plaza"})
cypher query result:
(2 {"name":"John McClane"})
(4 {"name":"Hans Gruber"})

node 2 has 2  connections
Try a case where there is no results :
theCyperCode = "START Hans=node(4) MATCH Hans-->ConnectedNode-[?]->NodeConectedToConnectedNode RETURN ConnectedNode, NodeConectedToConnectedNode"

cypher.execute(graph_db, theCyperCode, row_handler=handle_row)
produce the following results :
cypher query result:
(5 {"name":"Nakatomi Plaza"})
None


Node 5 has no connection going out from it. therefore the optional relation chip return null as the connected node.
In case where the optional relationship is not used :
theCyperCode = "START Hans=node(4) MATCH Hans-->ConnectedNode-->NodeConectedToConnectedNode RETURN ConnectedNode, NodeConectedToConnectedNode"

cypher.execute(graph_db, theCyperCode, row_handler=handle_row)
No results will return at all.

אין תגובות:

הוסף רשומת תגובה