Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Neo4j: Labels, Relationships, and Properties

Labels

In Neo4j, labels are used to categorize nodes. A label helps to define the type or class of a node, allowing for efficient querying and organization of data.

Note: A node can have multiple labels.

Creating Nodes with Labels


CREATE (n:Person {name: 'Alice', age: 30})
            

In the example above, a node of type Person is created with properties name and age.

Relationships

Relationships in Neo4j connect nodes and are directional. They can also have properties, just like nodes.

Creating Relationships


MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'})
CREATE (a)-[:FRIENDS_WITH {since: 2020}]->(b)
            

This creates a directed relationship FRIENDS_WITH from Alice to Bob with a property indicating when they became friends.

Properties

Properties are key-value pairs associated with nodes and relationships. They add additional context and detail to the data.

Adding Properties


MATCH (n:Person {name: 'Alice'})
SET n.email = 'alice@example.com'
            

The above command sets the email property for the node labeled Person with the name Alice.

Best Practices

  • Use meaningful labels that reflect the nature of the data.
  • Limit the number of properties on a node for optimal performance.
  • Utilize relationships to indicate connections between entities clearly.
  • Index frequently queried properties for faster lookups.

FAQ

What is the maximum number of labels a node can have?

A node can have up to 64 labels.

Can relationships have properties?

Yes, relationships can have properties just like nodes.

How do I delete a label from a node?

You can use the REMOVE clause to delete a label, for example: REMOVE n:LabelName.

Flowchart: Creating and Managing Nodes and Relationships


graph TD;
    A[Create Node] --> B{Label?};
    B -->|Yes| C[Assign Label];
    B -->|No| D[Skip Label];
    C --> E[Add Properties];
    D --> E;
    E --> F[Create Relationship];
    F --> G[Assign Relationship Type];
    G --> H[Add Relationship Properties];