Incorrect graph visualization

Hi,
I'm new to Neo4j so I'm wondering if I'm doing something wrong with the following example:
In a new database I created 2 nodes and 2 relations between these nodes:
create (:Message {id:1})
create (:Message {id:2})
create (:Message {id:1})-[:implies {model:'a'}]-(:Message {id:2})
create (:Message {id:1})-[:implies {model:'b'}]-(:Message {id:2})

When I executed the following query:
match (m1:Message {id:1})-[r:implies {model:'a'}]->(m2:Message {id:2})
return m1, r, m2

In Table mode, I correctly get only one row.
in Graph mode, the visualization is still displaying both relationships (model:'a' and model:'b')

Am I doing something wrong?
Best regards,
Arta

There's a few things you'll need to consider.

  1. There's a setting the Browser to show all relationships, which ignores the query result.
    • In the browser, bottom left, click Settings (gear icon). Near the bottom is checkbox labled, "Connect result nodes." Uncheck it.
  2. Your create statements will create additional nodes.

Neo uses an internal id, and unless you specify an index, and unique constraints, the following will create a total of 4 nodes:

create (:Message {id:1})
create (:Message {id:2})
create (:Message {id:1})<-[:implies {model:'a'}]-(:Message {id:2})

image

You can avoid this by using MERGE instead of create, and using variables.

MERGE (a:Message {id:1})
MERGE (b:Message {id:2})
MERGE (a)<-[:implies {model:'a'}]-(b)
MERGE (a)-[:implies {model:'b'}]->(b)

However, be very careful with MERGE, as it will create the entire path if it doesn't find a match. The advantage is that it will find an existing match first, and create it if it doesn't exist. The above command can be run many times, and will always result in the same graph, while the CREATE equivalent will continue adding nodes and edges.

After clearing the database, and running the MERGE commands as many times as I like:
image

2 Likes

Thank you very much Tony.
The "Connect result nodes" fixed my problem.
Thanks also for the rest of the tips. They are very helpful!
Best,
Arta

Glad to help!

One last thing I forgot to mention.

All Neo4j relationships are directional. But...

  • MATCH clauses may be unidirectional: MATCH (a)-[]-(b)
  • CREATE clauses must specify a direction: CREATE (a)-[]->(b)
  • MERGE commands may omit the direction, but the result will randomly chose the direction, if it is not specified: MERGE (a)-[]-(b) results in: (a)<-[]-(b) or (a)-[]->(b)

Relationship direction is the first, and most effective means of optimizing queries, so it is best to carefully define them before creating them, where possible.