Graph Databases: Neo4j and Graph Traversal Patterns

Learn Neo4j graph database modeling with Cypher. Covers nodes, edges, social networks, recommendation engines, fraud detection, and when graphs are not the right fit.

published: reading time: 20 min read author: Geek Workbench updated: November 17, 2026
Quick Summary

Graph databases make connected data easier to traverse, but query cost depends on the start set, fan-out, depth, matching paths, and query plan. This guide covers Neo4j's labeled property graph model, Cypher, bounded traversals, and cases where relational design remains simpler.

Graph Databases: Neo4j and Graph Traversal Patterns

Graph databases store relationships as data a query can follow. That can help when a question depends on chains of connections, but traversal cost does not depend on hop count alone.

A walk from a node with a few neighbors may be small; the same number of hops from a high-degree node can expand many candidates. The starting match, relationship filters, degree, depth, matching path count, and query plan all affect the work. Relational joins can also perform well when the schema and indexes fit the workload.


The Graph Model

A graph database has three core elements:

Nodes represent entities. They have properties (key-value pairs) and labels (type markers).

Edges (or relationships) connect nodes. They have direction, type, and properties. In Neo4j, edges are always directed but you can query in either direction.

Properties store data on both nodes and edges.

// A simple social graph
CREATE (alice:Person {name: 'Alice', age: 30})
CREATE (bob:Person {name: 'Bob', age: 28})
CREATE (carol:Person {name: 'Carol', age: 32})
CREATE (dave:Person {name: 'Dave', age: 27})

CREATE (alice)-[:FRIEND {since: 2020}]->(bob)
CREATE (alice)-[:FRIEND {since: 2019}]->(carol)
CREATE (bob)-[:FRIEND {since: 2021}]->(dave)
CREATE (carol)-[:FRIEND {since: 2018}]->(dave)

Visually:

    [Alice] --FRIEND--> [Bob]
      |                |
   FRIEND            FRIEND
      |                |
      v                v
    [Carol] <--FRIEND-- [Dave]
flowchart LR
    App["Application<br/>(Cypher Query)"]
    Traversal["Traversal<br/>Engine"]
    Store["Property<br/>Store"]
    RelStore["Relationship<br/>Store"]
    Index["Index"]
    Result["Result<br/>Set"]

    App --> Traversal
    Traversal --> Store
    Traversal --> RelStore
    Traversal --> Index
    RelStore --> Result
    Index --> Result

Neo4j traversals follow relationships from the matched starting nodes. Count expanded relationships and matched paths, not only hops or total stored nodes. A selective indexed start can keep the initial match small; high fan-out or many matching paths can still make a bounded walk expensive.


Cypher: Neo4j’s Query Language

Cypher uses ASCII-art-like syntax to represent patterns. Nodes are in parentheses, relationships are arrows.

// Find all of Alice's friends
MATCH (alice:Person {name: 'Alice'})-[:FRIEND]->(friend)
RETURN friend.name

// Find mutual friends of Alice and Bob
MATCH (alice:Person {name: 'Alice'})-[:FRIEND]->(mutual)
MATCH (bob:Person {name: 'Bob'})-[:FRIEND]->(mutual)
RETURN mutual.name

// Find friends of friends (2nd degree connections)
MATCH (alice:Person {name: 'Alice'})-[:FRIEND]->()-[:FRIEND]->(fof)
RETURN fof.name

// Exclude already-friends
MATCH (alice:Person {name: 'Alice'})-[:FRIEND*2]->(potential_friend)
WHERE NOT (alice)-[:FRIEND]->(potential_friend)
RETURN potential_friend.name

Pattern Matching

Cypher’s ASCII-art syntax makes multi-hop traversal paths readable at a glance. The query planner then decides how to execute them efficiently, without you directing the execution order.

Variable-length relationships use a range such as *1..3 to limit the number of hops. Keep the relationship type and starting match selective, and bound the number of returned rows. Neo4j’s planner chooses an execution plan from the query, indexes, and available statistics; hop count alone does not predict its cost.

// Find users who bought products in the same category as their friends
MATCH (person:Person)-[:PURCHASED]->(product:Product)-[:IN_CATEGORY]->(category:Category)<-[:IN_CATEGORY]-(friend:Person)-[:PURCHASED]->(rec:Product)
WHERE NOT (person)-[:PURCHASED]->(rec)
RETURN rec.name AS recommendation, count(*) AS frequency
ORDER BY frequency DESC
LIMIT 10

// Find the shortest path between two people
MATCH path = shortestPath(
  (alice:Person {name: 'Alice'})-[*..6]-(dave:Person {name: 'Dave'})
)
RETURN path

// Find all relationships in a network path
MATCH path = (a:Person)-[:FRIEND|PURCHASED|REVIEWED*1..3]-(b:Person)
WHERE a.name = 'Alice' AND b.name = 'Dave'
RETURN path

Aggregation and Analysis

Cypher aggregation functions (count(), sum(), avg(), min(), max()) work inline as you traverse, not in a separate grouping phase. You count relationships on the walk itself, aggregate across variable-length patterns, and sort in one pass.

size((p)--()) counts all relationships incident to a node regardless of direction or type, which gives you a rough degree centrality check. Pair it with collect() to gather values into lists, and you can assemble community members from a label propagation result.

// Count friends by person
MATCH (p:Person)-[:FRIEND]->(friend)
RETURN p.name, count(friend) AS friend_count
ORDER BY friend_count DESC

// Find influential users (most connections)
MATCH (p:Person)
RETURN p.name, size((p)--()) AS connections
ORDER BY connections DESC
LIMIT 10

// Collaborative filtering: "users who liked X also liked Y"
MATCH (user:Person)-[:LIKED]->(product:Product)<-[:LIKED]-()-[:LIKED]->(rec)
WHERE (user)-[:LIKED]->(product) AND not(user)-[:LIKED]->(rec)
RETURN product.name AS liked, rec.name AS recommended, count(*) AS strength
ORDER BY strength DESC

Where Graphs Actually Shine

Social Networks

Social graphs differ from generic traversals because edges carry social meaning. A FRIEND edge means something different from a FOLLOWS edge, and that distinction shapes your recommendation logic.

The two queries below show common operations. The first recommends friends of friends who are not yet connected to you. The second uses label propagation to discover communities without predefined boundaries, useful for targeted marketing or spotting coordinated groups. The label propagation syntax varies between Neo4j versions; the syntax shown works with the Graph Algorithms library.

// Find friend recommendations (friends of friends who aren't friends yet)
MATCH (me:Person {name: 'Alice'})
MATCH (me)-[:FRIEND]->(friend)-[:FRIEND]->(suggestion)
WHERE NOT (me)-[:FRIEND]->(suggestion) AND suggestion <> me
RETURN suggestion.name, count(*) AS mutual_friend_count
ORDER BY mutual_friend_count DESC
LIMIT 5

// Find communities using weakly connected components
CALL algo.labelPropagation.stream('Person', 'FRIEND', {})
YIELD nodeId, label
RETURN label AS community, collect(members.name) AS members

// Note: above is pseudocode - actual implementation varies by Neo4j version

Recommendation Engines

Recommendation quality improves when you look at the relationship structure around a user’s purchases and views, not just the items themselves. A graph naturally encodes co-purchase patterns, collaborative signals, and network effects in one traversable structure.

The three patterns below go from simple to more sophisticated. The first is item-to-item collaborative filtering: find products that share an audience. The second is content-based: recommend items sharing attributes with what the user already owns. The third uses social proximity: recommend items popular among a user’s direct and second-degree connections. Each trades compute cost against personalization quality.

// "Users who viewed X also viewed Y"
MATCH (p:Person)-[:VIEWED]->(product:Product)<-[:VIEWED]-(other)-[:VIEWED]->(rec)
WHERE p.id = $current_user AND rec <> product
RETURN rec.name, count(*) AS views_together
ORDER BY views_together DESC

// Content-based recommendations
MATCH (user:Person {id: $user_id})-[:PURCHASED]->(owned:Product)-[:IN_CATEGORY|hasTag|TAGGED_WITH]->(attr)
WHERE NOT (user)-[:PURCHASED]->(rec:Product)-[:IN_CATEGORY|hasTag|TAGGED_WITH]->(attr)
AND NOT (user)-[:PURCHASED]->(rec)
RETURN rec, count(attr) AS matching_attributes
ORDER BY matching_attributes DESC

// "Popular in your network"
MATCH (user:Person {id: $user_id})-[:FRIEND*1..2]->(friend)-[:PURCHASED]->(product)
WHERE NOT (user)-[:PURCHASED]->(product)
RETURN product.name, count(DISTINCT friend) AS friend_count
ORDER BY friend_count DESC

Fraud Detection

Fraud rings become visible only when you model the relationships between accounts. A fraudster controlling ten accounts can make each one look normal in isolation. The ring does not show up in individual records.

The three queries target different patterns. The first catches shared identity signals: many accounts sharing the same email, phone, or IP is a strong synthetic identity indicator. The second finds circular transactions, money looping back to the originator, a classic money laundering signature. The third flags velocity anomalies: hundreds of small transactions in a day is unusual for a legitimate user. In production, each query runs on a schedule and feeds a risk scoring layer.

// Detect accounts sharing the same identifying info
MATCH (a:Account)-[:HAS_EMAIL|HAS_PHONE|HAS_IP]->(info)<-[:HAS_EMAIL|HAS_PHONE|HAS_IP]-(b:Account)
WHERE a <> b
WITH info, collect(a.id) AS accounts, collect(b.id) AS others
WHERE size(accounts) + size(others) > 5  // many accounts sharing info
RETURN info, accounts + others AS suspicious_accounts

// Find circular transactions (potential money laundering)
MATCH path = (a:Account)-[:SENT_TO*5..10]->(a)
WHERE a <> head(nodes(path))
RETURN path

// Detect velocity patterns (many small transactions)
MATCH (a:Account)-[t:TRANSACTION]->()
WHERE t.timestamp > datetime() - duration('P1D')
WITH a, count(t) AS tx_count, sum(t.amount) AS total_amount
WHERE tx_count > 100 AND total_amount < tx_count * 10  // many small amounts
RETURN a.id AS account, tx_count, total_amount

Network and IT Operations

IT infrastructure is a graph: services depend on other services, incidents affect services, and root cause analysis means traversing that dependency topology.

The three queries cover the common cases. The first enumerates direct service dependencies. The second finds service pairs with no alternate path, critical single points of failure. The third traces an incident’s blast radius using a variable-length traversal (AFFECTS*0..3), ordered by hop distance so the on-call engineer sees the closest affected services first.

// Find dependencies between services
MATCH (a:Service)-[:DEPENDS_ON]->(b:Service)
RETURN a.name AS service, collect(b.name) AS dependencies

// Find critical paths (no redundancy)
MATCH path = (a:Service)-[:DEPENDS_ON*]->(b:Service)
WHERE NOT exists(()-[:DEPENDS_ON]->(a))  // no incoming dependencies
AND NOT exists((b)-[:DEPENDS_ON]->())   // no outgoing dependencies
RETURN a.name AS source, b.name AS sink

// Root cause analysis
MATCH path = (failure:Incident)-[:AFFECTS*0..3]-(service:Service)
WHERE failure.severity = 'critical'
RETURN service.name, length(path) AS distance_from_incident
ORDER BY distance_from_incident

Modeling: Nodes vs Edges

The choice of what becomes a node vs an edge shapes query capabilities.

Things that work well as nodes:

  • Entities with independent existence (Person, Product, Company)
  • Abstract concepts that participate in multiple relationships
  • Records you need to query directly

Things that work well as edges:

  • Relationships between entities
  • Events that have no identity beyond the connection
  • Attributes that describe a relationship (date, weight, role)
// Good: Purchase as an edge (an event, not an entity)
MATCH (customer)-[p:PURCHASED]->(product)
WHERE p.date > '2024-01-01'
RETURN product.name, sum(p.amount) AS revenue

// Consider: Purchase as a node when you need to query purchases independently
// e.g., "find all purchases with these exact items"
CREATE (p:Purchase {id: 'pur-123', date: date('2024-03-15')})
CREATE (customer)-[:MADE_PURCHASE]->(p)
CREATE (p)-[:INCLUDED_ITEM]->(product)

Practical Neo4j Operations

Python Driver

The Neo4j Python driver’s session-based API over the Bolt protocol is straightforward to wrap. The pattern below opens a session per query, runs Cypher with parameters, and converts results to plain Python dictionaries.

Two things to watch. Pass parameters separately instead of interpolating them into the Cypher string. The driver sends them to the server where they are handled safely, which also avoids formatting edge cases. Also, session.run() returns a reactive stream. Buffering it as a list with [dict(record) for record in result] works for small and medium result sets, but use an iterator instead if you are dealing with large traversals.

from neo4j import GraphDatabase

class Neo4jConnection:
    def __init__(self, uri, user, password):
        self.driver = GraphDatabase.driver(uri, auth=(user, password))

    def query(self, cypher, parameters=None):
        with self.driver.session() as session:
            result = session.run(cypher, parameters)
            return [dict(record) for record in result]

    def close(self):
        self.driver.close()

# Usage
conn = Neo4jConnection('bolt://localhost:7687', 'neo4j', 'password')

# Create nodes
conn.query('''
CREATE (p:Person {name: $name, email: $email})
''', {'name': 'Alice', 'email': 'alice@example.com'})

# Query with parameters
friends = conn.query('''
MATCH (me:Person {name: $name})-[:FRIEND]->(friend)
RETURN friend.name, friend.email
''', {'name': 'Alice'})

# Find recommendations
recommendations = conn.query('''
MATCH (me:Person {name: $name})-[:PURCHASED]->(product)-[:IN_CATEGORY]->(cat)<-[:IN_CATEGORY]-(rec)
WHERE NOT (me)-[:PURCHASED]->(rec)
RETURN rec.name, count(*) AS score
ORDER BY score DESC
LIMIT 5
''', {'name': 'Alice'})

Importing Data

Neo4j’s LOAD CSV clause handles bulk import directly in Cypher, which works well up to a few million rows. For larger datasets, neo4j-admin import or the Apache Spark connector are better since they bypass transaction logging and its memory overhead.

The PERIODIC COMMIT 1000 directive checkpoints the transaction every 1000 rows, preventing heap exhaustion on large imports. Without it, a multi-million row import can run out of memory before finishing. If the import fails partway, the first N thousand rows are already committed and cannot be rolled back. Build idempotency into your import or plan for cleanup on retry.

// Import from CSV
LOAD CSV FROM 'file:///users.csv' AS row
CREATE (u:User {
    id: toInteger(row.id),
    name: row.name,
    email: row.email,
    created_at: datetime(row.created_at)
});

// Import relationships
LOAD CSV FROM 'file:///friendships.csv' AS row
MATCH (a:User {id: toInteger(row.user_a)})
MATCH (b:User {id: toInteger(row.user_b)})
CREATE (a)-[:FRIEND {since: toInteger(row.year)}]->(b);

// Batch import with periodic commits
:auto USING PERIODIC COMMIT 1000
LOAD CSV FROM 'file:///events.csv' AS row
CREATE (:Event {
    id: row.event_id,
    type: row.type,
    timestamp: datetime(row.timestamp)
});

When to Use / When Not to Use Graph Databases

Graph databases shine when relationships are first-class data, not afterthoughts.

Use graph databases when:

  • You need multi-hop traversals (friends-of-friends, recommendation chains, dependency graphs)
  • Relationship patterns drive your core business logic (fraud rings, supply chains, social graphs)
  • Your queries depend on the topology of connections, not just attribute values
  • You need real-time path finding or shortest-path queries
  • You are modeling domains where context and connection history directly inform outcomes

Do not use graph databases when:

  • Your data is mostly independent records with few meaningful relationships
  • Your primary access pattern is full-text search — use Elasticsearch instead
  • You need heavy OLAP aggregation (sums, group-bys across millions of rows) — columnar databases win here
  • Your schema is stable and relational with straightforward joins — the graph model adds complexity you will not use
  • Writes heavily outnumber reads and the writes are not relationship-driven — a write-optimized store like Cassandra handles that better

Hybrid Approaches

Many systems combine graph with other databases.

Application Layer
        |
        +---> Graph DB (Neo4j) for social, recommendations
        |
        +---> Relational DB (PostgreSQL) for transactional
        |
        +---> Search (Elasticsearch) for full-text
        |
        +---> Cache (Redis) for hot data
# Example: hybrid architecture for e-commerce
def get_product_recommendations(user_id):
    # Fast filter with search
    candidates = elasticsearch.search(
        query='laptop',
        filters={'category': 'electronics', 'price_range': '500-2000'}
    )

    # Use graph for collaborative filtering
    graph_result = neo4j.query('''
    MATCH (u:User {id: $user_id})-[:PURCHASED]->()-[:IN_CATEGORY]->(cat)
    WHERE u.id IN $candidates
    WITH cat, count(*) AS score
    MATCH (cat)<-[:IN_CATEGORY]-(rec)
    WHERE NOT (u)-[:PURCHASED]->(rec)
    RETURN rec.id, score
    ORDER BY score DESC
    LIMIT 10
    ''', {'user_id': user_id, 'candidates': [c['id'] for c in candidates]})

    return merge_search_and_graph(candidates, graph_result)

Graph Database Comparison

The table compares Neo4j, Amazon Neptune, and TigerGraph. Neo4j is the oldest and most mature with the largest ecosystem and the most intuitive query language. Neptune is a managed service that makes sense if you are already using AWS. TigerGraph handles high-scale analytics better because of its parallel processing, but GSQL has a steeper learning curve.

A few things the table does not make obvious. For graph algorithms at scale — PageRank, connected components, community detection — TigerGraph’s built-in analytics beat Neo4j’s Spark connector. If you need SPARQL for RDF data, Neptune is your only option. On licensing, Neo4j’s GPL means you need a commercial license if you distribute a product that includes it as a component.

Feature Neo4j Amazon Neptune TigerGraph
Query language Cypher (openCypher) SPARQL, Gremlin, OpenCypher GSQL
License GPL Community, commercial AWS managed service Open source, commercial
Native traversal Yes — purpose-built Yes Yes
Scalability Single-machine to cluster Fully managed, multi-AZ Horizontally scalable
OLAP / Analytics Limited (via Apache Spark connector) Analytics via Gremlin Built-in parallel analytics
Cloud offering Aura (managed), self-hosted Neptune Serverless, provisioned TigerGraph Cloud
Best for General-purpose graphs, operational AWS integration, SPARQL workloads Large-scale analytics, real-time deep link analysis
Learning curve Moderate (Cypher is intuitive) Moderate (multiple query APIs) Steeper (GSQL is powerful but verbose)

Capacity Estimation: Node and Edge Storage in Neo4j

Neo4j stores each node, relationship, and property as separate records on disk. Node records are 15 bytes each plus property references. Relationship records are 34 bytes each plus property references. Property records vary by type: 1 byte for a small integer, n+1 bytes for a string (n bytes plus length byte), 8 bytes for a floating-point number.

For a social graph with 10 million users and 100 million friendships, the base storage is straightforward: 10 million nodes at roughly 15 bytes each is 150MB, and 100 million relationships at 34 bytes each is 3.4GB. Properties add more: if each user has 5 properties averaging 50 bytes each, that is 2.5GB. The total working set for this graph is roughly 6GB before indexes.

Indexes in Neo4j are separate from the graph store. The default index type is a B-tree, and it consumes roughly 30% of the node/relationship data size for highly selective indexes. Property existence constraints and range indexes add more overhead. For the 10 million user graph above, adding indexes on Person(name) and Person(email) adds roughly 1-2GB of index storage.

The practical implication: Neo4j on a single machine handles graphs in the hundreds of millions of edges comfortably if your working set fits in RAM. Beyond that, you need clustering. Neo4j Enterprise clusters data across machines using causal clustering, which splits the graph into distinct cores. Each core is a raft group of 3 or more replicas, and reads get distributed across replicas.

For memory sizing, Neo4j recommends your page cache (which caches the graph store on disk) be large enough to hold your hot data. With 6GB of graph data and 30% hot, aim for 2GB page cache minimum. Add heap for query execution: simple traversals need 512MB to 1GB heap, complex aggregations need 2GB+.

Observability Hooks: Neo4j DBMS Metrics and Query Profiling

Neo4j exposes DBMS metrics via the dbms.metrics namespace. The JMX endpoint (dbms.metrics.prometheus) or the Neo4j HTTP endpoint (/db/neo4j/metrics) provides access to key operational metrics.

Page cache hit ratio is the most important metric: page_cache_hits divided by page_cache_hits + page_cache_misses. Above 95% and Neo4j barely touches the disk. Below 80% and you are latency-bound on page faults. If page cache hit ratio drops, increase dbms.memory.pagecache.size or reduce the graph working set.

Transaction latency: transaction_started, transaction_committed, and transaction_rollbacks counters tell you throughput. transaction_time histograms give you p50/p95/p99 latency. If p99 latency spikes while throughput stays flat, you have slow queries holding connections. db.checking.time tracks constraint checking time separately from transaction execution.

Use a bounded query to inspect the plan:

EXPLAIN MATCH (alice:Person {name: $name})-[:FRIEND*1..3]-(candidate:Person)
RETURN DISTINCT candidate.name
LIMIT 20

EXPLAIN shows the planned operators and estimates without running the query. PROFILE runs it and reports actual rows and database hits; the profile adds overhead, and a mutating query can change data, so use it on a safe read query when diagnosing performance. For example:

PROFILE MATCH (alice:Person {name: $name})-[:FRIEND*1..3]-(candidate:Person)
RETURN DISTINCT candidate.name
LIMIT 20

A simplified plan output might look like this:

PROFILE (schematic; operators and values vary by plan and data)
Operator                Estimated Rows    Rows    DB Hits
[start lookup]          [estimate]        [actual] [hits]
[relationship expand]   [estimate]        [actual] [hits]
ProduceResults          [estimate]        [actual] [hits]

EXPLAIN reports estimated rows; PROFILE adds actual rows and database hits. Compare them at the start lookup and each expansion. A large gap can point to skewed data or weak estimates, but it does not by itself prove that statistics are stale. Operator names and available columns depend on the plan and Neo4j version. See Neo4j’s execution plan documentation for the output format.

For Cypher query monitoring, Neo4j Enterprise tracks query runtime via dbms.query_tracking.enabled. The slow query log (dbms.logs.query.enabled) logs queries exceeding dbms.logs.query.threshold (default 0, set to something like 100ms). Monitor dbms.transaction.timeout — if set, queries exceeding this limit are killed automatically.

Performance Depends on the Data

Two queries with the same hop bound can do very different amounts of work. A selective starting index, relationship type filters, fan-out, duplicate paths, and result cardinality all affect the plan. High fan-out can cause path explosion as combinations of relationships grow with each hop. Measure with data that resembles the production graph, and inspect the plan before attributing performance to database type alone. For adjacency lists, matrices, BFS, and DFS, see the graph representations guide.

Interview Questions

1. You need to find all pairs of people in your database who share the same email address but have different phone numbers — for fraud detection. How do you model and query this in Neo4j?

Model email and phone as separate nodes or as properties on Account nodes. The query matches accounts sharing an email via HAS_EMAIL but diverging on phone via HAS_PHONE. The Cypher pattern finds accounts that share info (email) but have different phone nodes. The WHERE size(phones) > 0 filters out accounts without a recorded phone, and size(shared_phones) < size(phones) confirms at least one phone is not shared — meaning the same email is used by multiple accounts with different phone contact info.

2. Your Neo4j query for "friends of friends of friends" is timing out after 30 seconds. What do you check?

Bound the relationship depth and type first, then inspect the plan for the start lookup and expansion operators. An AllNodesScan may be costly when a selective indexed start is available; a label scan can be reasonable when it matches many rows. Compare estimated and actual rows in PROFILE, and check whether the starting node has unusually high degree. A three-hop query can still expand many paths when fan-out is high.

3. When would you choose a graph database over a relational database for a social network feature?

A graph database can fit queries that repeatedly follow relationships to find neighbors or paths. It does not make those queries automatically cheap: fan-out, starting-node cardinality, indexes, path count, and the execution plan matter. A relational database may still fit when the workload is mostly indexed lookups or aggregations. Compare both with representative queries and data before choosing.

4. What is the difference between Neo4j causal clustering and a single-server deployment, and what are the operational tradeoffs?

A single-server Neo4j deployment is straightforward — one machine, ACID transactions, no network overhead. It handles graphs up to whatever fits on that machine. Causal clustering splits the graph into replica cores using Raft consensus, providing fault tolerance and read scaling. Writes go through the leader replica, reads can be distributed to followers. The tradeoff is operational complexity: you now manage multiple servers, the consensus protocol adds latency to writes, and replica lag means you can read stale data on followers if you are not careful. Causal consistency in Neo4j guarantees you read your own writes on followers, but it does not guarantee all followers are up-to-date at any given moment.

5. What is the difference between Neo4j's traversal query and a Cypher MATCH query? When would you use each?

Cypher MATCH queries are declarative — you specify the pattern, not the traversal method. The Cypher planner chooses the execution strategy. Traversal queries (using the Traversal API in Java or similar) are imperative — you explicitly define the traversal description (where to start, which relationships to follow, how deep, what to prune). Use Cypher MATCH for most queries — it is expressive and the planner is efficient. Use the Traversal API when you need fine-grained control over expansion order (e.g., breadth-first with depth cutoff), custom pruning logic (stop after finding N results), or when you are writing custom procedures in Java. Traversal API queries bypass the Cypher planner entirely, giving you explicit control at the cost of portability.

6. How do you handle high-degree nodes (celebrity nodes) in Neo4j, and what impact do they have on query performance?

A high-degree node can expand many relationships even in a shallow query. Start from a selective indexed match, constrain relationship types and depth, and use PROFILE to inspect rows and database hits at each expansion. A label filter on the destination can reduce returned rows, but it does not necessarily avoid expanding the relationships first. Pagination or streaming can limit client memory; it does not always reduce traversal work.

Category

Related Posts

Document Databases: MongoDB and CouchDB Data Modeling

Compare MongoDB and CouchDB data modeling, transactions, consistency settings, and replication behavior with relational databases.

#database #nosql #document-database

Column-Family Databases: Cassandra and HBase Architecture

Cassandra and HBase data storage explained. Learn partition key design, column families, time-series modeling, and consistency tradeoffs.

#database #nosql #column-family

Denormalization

When to intentionally duplicate data for read performance. Tradeoffs with normalization, update anomalies, and application-level denormalization strategies.

#database #denormalization #performance