user20833054
user20833054

Reputation:

I'm having problems undestanding some cypher concepts - naming nodes

I'm following one tutorial and I'm having a hard time understating the very basic things and I need your help. The code is:

CREATE (u:User {name: "Alice"})-[:Likes]->(m:Software {name: "Memgraph"});

The explanation for this code is: The query above will create 2 nodes in the database, one labeled "User" with name "Alice" and the other labeled "Software" with name "Memgraph". It will also create a relationship that "Alice" likes "Memgraph".

This part I get.

What I don't get is this: To find created nodes and relationships, execute the following query:

MATCH (u:User)-[r]->(x) RETURN u, r, x;

If I've created a node that has a variable (or how is u called), why is the relation related to as r, and software as x? When a relation was created, it was just defined as :Likes, and software was m.

From where do r and x come from? Is there any connection between CREATE and MATCH or is the order the only an important thing and names are not important at all?

Upvotes: 0

Views: 44

Answers (1)

KateLatte
KateLatte

Reputation: 728

When you were creating nodes and a relationship between them, you used variables, but you could have done it like this:

CREATE (:User {name: "Alice"})-[:Likes]->(:Software {name: "Memgraph"});

The above query would also create nodes and a relationship. We use variables when we want to use certain objects in the other parts of one query. For example, if you wanted to also return the created nodes, you would execute the following query:

CREATE (u:User {name: "Alice"})-[:Likes]->(m:Software {name: "Memgraph"})
RETURN u, m;

You can notice that you needed variables u and m, in order to return them. Also, you can't return the relationship object, since you did not assign variable to it.

Now to answer the other part of your question - variables are used in one query and they are not memorized in any way to be used in other query. So if you ran:

CREATE (u:User {name: "Alice"})-[:Likes]->(m:Software {name: "Memgraph"});

and then you want to get u and m in some other query, those won't be Alice and Memgraph nodes anymore. Hence, when you execute:

MATCH (u:User)-[r]->(x) RETURN u, r, x;

you get every node labeled with User, regardless of Alice from the query before (but Alice will be included too, since they are a person), and all other nodes that the User nodes are related to, along with those relationships. You choose your variable names, so it does not matter whether they are u, r and x or m, n and l.

Upvotes: 1

Related Questions