Skip to content

Instantly share code, notes, and snippets.

@decagondev
Created January 13, 2026 17:09
Show Gist options
  • Select an option

  • Save decagondev/b9032a4c1eadf60cf13759bb84cca1b2 to your computer and use it in GitHub Desktop.

Select an option

Save decagondev/b9032a4c1eadf60cf13759bb84cca1b2 to your computer and use it in GitHub Desktop.

Neo4j Primer: Basics for Complete Beginners

This primer serves as an absolute beginner's introduction to Neo4j, assuming no prior knowledge of databases, graphs, or programming beyond basic computer literacy. It breaks down the foundational concepts into digestible steps, explaining "why" before "how," and using simple analogies. The focus is on pure Neo4j groundwork, with practical, code-driven examples using Python and Cypher. No advanced topics like RAG (Retrieval-Augmented Generation) are covered here—this is just the essentials to get you started.

Structure: One sprint with 4 modules for quick pacing (1-2 hours total). Code uses Python (basic level) and Cypher. If you don't have Python installed, download it from https://www.python.org/downloads/ and follow the installation instructions for your operating system.

Sprint 0: Core Neo4j Concepts and First Steps

Estimated time: 30-45 minutes per module.

Module 1: What is Neo4j and Why Graphs?

Learning Objectives

  • Understand databases in simple terms.
  • Learn what a graph database is (compared to traditional ones).
  • See why Neo4j is useful, with everyday analogies.

Key Concepts

A database is like a digital filing cabinet for storing, organizing, and retrieving information efficiently. It helps manage large amounts of data without chaos, much like how a library catalog helps you find books quickly.

Traditional databases (e.g., spreadsheets like Excel or relational databases like SQL) use tables—imagine a phone book with rows for each person and columns for details like name, phone number, and address. They're great for simple lists but struggle with complex connections.

A graph database models data as a network: "things" (nodes) connected by "how they relate" (relationships). Neo4j is a popular graph database that excels at this. It stores data in a way that mimics real-world connections, making it easier to explore patterns.

Analogy: Think of social media friends—people are nodes, and "friends with" is a relationship. In a graph, it's straightforward to ask questions like "Who are my friends' friends?" or "What's the shortest path between two people?" In a table database, you'd need multiple joins and complex queries, which can be slow and cumbersome.

Why use Neo4j?

  • It handles connections naturally, ideal for applications like recommendations (e.g., "People who bought this also bought..."), fraud detection (spotting unusual patterns in transactions), or network analysis (e.g., mapping disease spread).
  • It's fast for complex, relationship-heavy queries.
  • The core is open-source, with free community editions and cloud options for scalability.

Here's a comparison table to highlight the differences:

Aspect Graph Database (Neo4j) Table Database (e.g., SQL)
Structure Nodes (entities) + Relationships (connections) Rows (records) + Columns (fields)
Strength Exploring relationships and patterns Simple lists, aggregations, and sums
Example Use Social networks, family trees, road maps Inventory lists, financial ledgers
Query Example "Find all friends of friends" "Sum sales by region"

Hands-On (No Code Yet)

To build intuition, grab a pen and paper:

  1. Draw circles for "nodes" representing people in your family (e.g., one circle for "You," one for "Parent," one for "Sibling").
  2. Draw lines between them for "relationships" (e.g., an arrow from "Parent" to "You" labeled "PARENT_OF").
  3. Add notes next to nodes or lines for "properties" (e.g., next to "You": "age: 30"; next to the line: "since: birth").

This simple sketch shows how graphs represent interconnected data.

Exercise

  1. List 3 real-life examples where connections matter more than lists (e.g., road networks for navigation apps, supply chains for logistics, or movie recommendations based on viewer preferences).
  2. Visit the Neo4j homepage (https://neo4j.com/) and read the introductory section to see real-world case studies.
  3. Reflect: How might a graph database improve one of your examples compared to a table?

Tips & Gotchas

  • Graphs shine when relationships are central—don't force them for simple flat data like a basic to-do list.
  • Neo4j is flexible but requires thinking in "networks" rather than "tables."
  • If you're curious, explore free resources like Neo4j's blog for more analogies.

Module 2: Basic Building Blocks of Graphs in Neo4j

Learning Objectives

  • Define nodes, relationships, properties, and labels.
  • Visualize and build simple graphs conceptually.
  • Understand how graph data tells "stories."

Key Concepts

Graphs in Neo4j are made of a few core elements:

  • Node: Represents a "thing" or entity (e.g., a person, book, or city). Think of it as a dot on a map.
  • Relationship: A directed or undirected connection between nodes (e.g., "LIKES" or "LIVES_IN"). It's like a road linking dots, often with a direction (arrow) to show flow, such as "FOLLOWS" (one-way) vs. "FRIENDS_WITH" (two-way).
  • Property: Key-value details attached to nodes or relationships (e.g., on a node: {name: "Alice", age: 30}; on a relationship: {since: 2023}). These add context, like labels on a map.
  • Label: A category or type for nodes (e.g., :Person, :Book). Labels help group and query similar items efficiently, like tags in a photo album.

Together, these form "stories": For example, (:Person {name: "Alice"})-[:LIKES {since: 2023}]->(:Movie {title: "Inception"}) means "Alice likes the movie Inception since 2023." This structure makes querying intuitive.

Hands-On (Conceptual)

Use pen and paper or a free online tool like draw.io (https://app.diagrams.net/):

  1. Create two nodes: One labeled :Person with property {name: "Alice"}, another :Person with {name: "Bob"}.
  2. Connect them with a relationship: -[:FRIENDS_WITH {since: 2020}]-> (make it bidirectional by ignoring direction for now).
  3. Add more: Create a :Movie node {title: "Inception"} and connect Alice to it with -[:LIKES]->.

Step-by-step elaboration:

  • Start with blank canvas.
  • Draw circles for nodes, write labels inside (e.g., :Person).
  • Add curly braces {} for properties inside or next to the circle.
  • Draw arrows for relationships, labeling them (e.g., :FRIENDS_WITH) and adding properties if needed.
  • This visualization helps before coding—graphs are visual by nature!

Exercise

  1. Expand your sketch: Add properties to all nodes and relationships (e.g., add {age: 28} to Bob).
  2. Add labels if missing (ensure every node has at least one).
  3. Reflect: Why do properties help in searches? (Answer: They allow filtering, e.g., "Find friends who connected since 2020 and are over 25.")
  4. Challenge: Sketch a graph for a simple recipe (ingredients as nodes, "USED_IN" relationships to a :Recipe node).

Tips & Gotchas

  • Relationships are directed by default in Neo4j, but you can query them bidirectionally (e.g., ignore arrow direction).
  • Keep it simple at first—too many labels or properties can overcomplicate your model.
  • Properties must be simple types like strings, numbers, or booleans; no nested structures without planning.

Module 3: Setting Up Neo4j for the First Time

Learning Objectives

  • Install Neo4j safely and securely.
  • Launch the database and explore the interface.
  • Run your first diagnostic command.

Key Concepts

Neo4j can run locally on your computer or in the cloud. For beginners, start with the free Desktop version. It requires Java (bundled in the installer). The main interface is Neo4j Browser, a web-based tool for running commands and visualizing graphs.

Options:

  • Neo4j Desktop: User-friendly app for local development (Windows, Mac, Linux).
  • Neo4j Aura Free: Cloud-hosted, no installation needed—sign up at https://neo4j.com/cloud/aura/.
  • Ports: Browser uses 7474 (HTTP), data connections use 7687 (Bolt protocol).

Hands-On Example

Step-by-step installation and first run:

  1. Download Neo4j Desktop from https://neo4j.com/download/. Choose the version for your OS.
  2. Run the installer. Follow prompts—it will install Java if needed.
  3. Open Neo4j Desktop: Create a new project (e.g., name it "MyFirstGraph").
  4. Add a DBMS (Database Management System): Click "Add" > "Local DBMS," name it (e.g., "neo4j-db"), set a password (strong one!), and create.
  5. Start the DBMS: Click "Start" and wait for it to turn green.
  6. Open Neo4j Browser: Click "Open" — it launches in your web browser at http://localhost:7474.
  7. Login: Use username "neo4j" and the password you set. (Change it immediately if prompted.)
  8. Run your first command in the Browser's query bar:
    CALL dbms.components()
    
    This queries the database components and returns info like version and edition—your "Hello World" to confirm it's working.

For Python setup (to connect later):

  1. Open a terminal or command prompt.
  2. Install the Neo4j driver:
    pip install neo4j
    
  3. Test import in a Python script (create a file like test.py):
    from neo4j import GraphDatabase
    print("Neo4j driver imported successfully!")
    Run it: python test.py.

Exercise

  1. Run the CALL dbms.components() command and take a screenshot of the output.
  2. Explore the Browser: Click the "Help" tab for built-in guides, or the database icon to see system info.
  3. If using Aura: Sign up, create an instance, download credentials, and connect via Browser (URL provided in Aura dashboard).
  4. Troubleshoot: If ports are blocked, check your firewall settings.

Tips & Gotchas

  • Always change the default password to avoid security risks.
  • If starting fails, ensure no other apps use ports 7474/7687.
  • Desktop is great for learning; switch to Aura for no-maintenance cloud use.
  • No data is stored yet—this is just setup.

Module 4: Your First Cypher Query and Simple Data

Learning Objectives

  • Learn basic Cypher syntax for creating and querying data.
  • Create and query a tiny graph.
  • Visualize results and connect from Python.

Key Concepts

Cypher is Neo4j's query language—readable like English sentences for graphs.

  • CREATE: Adds nodes, relationships, or properties.
  • MATCH: Finds patterns in the graph.
  • WHERE: Filters results.
  • RETURN: Outputs what you found.
  • Parameters (using $): Safe way to pass values, preventing injection issues.

Syntax basics: Nodes in (), relationships in -[]-, directions with > or <.

Hands-On Example

In Neo4j Browser:

  1. Clear any existing data (optional, for clean start):
    MATCH (n) DETACH DELETE n
    
  2. Create a node:
    CREATE (p:Person {name: "Bob", age: 25})
    RETURN p
    
    This adds a :Person node with properties and shows it (visualizes as a graph).
  3. Create another node and connect:
    CREATE (m:Movie {title: "Inception", year: 2010})
    CREATE (p:Person {name: "Alice", age: 30})-[:LIKES {since: 2023}]->(m)
    RETURN p, m
    
    Elaboration: First line creates the movie; second creates Alice, the relationship, and links to the movie. RETURN shows the graph.
  4. Query with filter:
    MATCH (p:Person)-[r:LIKES]->(m:Movie)
    WHERE p.age > 20 AND r.since > 2020
    RETURN p.name AS Person, m.title AS Movie
    
    This finds people over 20 who like movies since after 2020.

Python integration (using the driver from Module 3): Create a file like first_graph.py:

from neo4j import GraphDatabase

# Connect to your local Neo4j (replace with your password and URI if using Aura)
driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "your_password"))

def create_person_and_like(tx, name, age, movie_title, year, since):
    query = """
    CREATE (p:Person {name: $name, age: $age})
    CREATE (m:Movie {title: $movie_title, year: $year})
    CREATE (p)-[:LIKES {since: $since}]->(m)
    RETURN p, m
    """
    result = tx.run(query, name=name, age=age, movie_title=movie_title, year=year, since=since)
    return result.single()

with driver.session() as session:
    result = session.execute_write(create_person_and_like, "Charlie", 35, "Matrix", 1999, 2022)
    print(result["p"]["name"], "likes", result["m"]["title"])

driver.close()

Step-by-step:

  1. Import the driver.
  2. Connect using URI and auth.
  3. Define a function with a Cypher query using parameters ($).
  4. Use a session to execute write (for creating data).
  5. Print results. Run: python first_graph.py — then check in Browser.

Query from Python (add to the script):

def query_likes(tx):
    query = """
    MATCH (p:Person)-[:LIKES]->(m:Movie)
    RETURN p.name AS Person, m.title AS Movie
    """
    result = tx.run(query)
    for record in result:
        print(f"{record['Person']} likes {record['Movie']}")

with driver.session() as session:
    session.execute_read(query_likes)

Exercise

  1. In Browser: Create 2 more nodes (e.g., another :Person and :Movie), connect with :WATCHED {date: "2024-01-01"}.
  2. Query: "Find all people over 25 who like or watched something after 2020."
    MATCH (p:Person)-[r]->(m:Movie)
    WHERE p.age > 25 AND (r.since > 2020 OR r.date > "2020-01-01")
    RETURN p, r, m
    
  3. Visualize: After running, click the graph view in Browser to expand and see connections.
  4. In Python: Modify the script to add your own data and query it.
  5. Challenge: Add a bidirectional relationship (query both ways).

Tips & Gotchas

  • Cypher is case-sensitive for labels and relationship types (e.g., :Person ≠ :person).
  • Use parameters ($) for dynamic values to avoid errors and security issues.
  • Always close the driver in Python to free resources.
  • If queries fail, check syntax—missing commas in properties are common.
  • Visualize often: Browser's graph view helps debug.

Primer Capstone: Build a tiny graph for your hobbies (e.g., (:Person {name: "You"})-[:LIKES]->(:Hobby {name: "Reading"})). Use both Browser and Python to create/query it. Visualize and reflect on a simple question like "What hobbies do I like?"

You're now equipped with Neo4j basics!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment