Skip to content
ImagineWorld

Data Integration and ETL for Neo4j

node_idnode-book_neo4j-mastery_chapter-08-data-integration-and-etl-for-neo4j
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num8
chapter_titleData Integration and ETL for Neo4j
governed_byCORPUS
constitutional_citationCONSTITUTION
reviewunbalanced $ inline delimiters
local graph

Chapter 8 — Data Integration and ETL for Neo4j

Section titled “Chapter 8 — Data Integration and ETL for Neo4j”

Chapter 6: Data Integration and ETL for Neo4j

Section titled “Chapter 6: Data Integration and ETL for Neo4j”

The most sophisticated graph model and the most elegant Cypher queries remain theoretical curiosities until real data flows into the graph at scale, with correctness, timeliness, and auditability. Every enterprise-grade Neo4j deployment eventually confronts the same reality: ninety percent of the effort lies not in query authoring but in building, operating, and governing robust data integration pipelines that continuously transform heterogeneous, dirty, and high-velocity sources into a clean, connected, query-ready graph.

This chapter treats data integration as a first-class engineering discipline. The focus remains relentlessly practical: how to extract from relational databases, NoSQL stores, message queues, object storage, and SaaS platforms; how to transform normalized tables and denormalized documents into performant graph structures; how to load terabytes without downtime; how to stream millions of events per second with exactly-once semantics; and how to monitor, alert, and recover when inevitable failures occur.

Every pattern presented here has been proven in production environments processing hundreds of billions of relationships annually for global financial institutions, telecommunications operators, pharmaceutical companies, and e-commerce platforms.

6.1 Extracting Data from Multiple Sources into Graph Databases

Section titled “6.1 Extracting Data from Multiple Sources into Graph Databases”

Extraction begins with understanding source system characteristics: latency requirements, change capture capabilities, query performance, and access constraints.

Full Table Extraction versus Change Data Capture

Section titled “Full Table Extraction versus Change Data Capture”

Full extraction remains appropriate for static reference data or initial loads. Change Data Capture (CDC) becomes mandatory for transactional sources that evolve continuously.

cypher

// 6.1.1 Initial load of reference data from PostgreSQL via APOC

CALL apoc.load.jdbc( “jdbc:postgresql://postgres-prod.company.internal:5432/erp”, “SELECT * FROM dim_customer”, [] ) YIELD row

MERGE (c:Customer {customerId: row.customer_id}) ON CREATE SET c.legacyId = row.legacy_customer_id, c.name = row.full_name, c.tier = row.loyalty_tier, c.country = row.country_code, c.createdAt = datetime(row.created_timestamp) ON MATCH SET c.name = row.full_name, c.tier = row.loyalty_tier, c.country = row.country_code;

Commentary: Lines 2–6 use apoc.load.jdbc to execute a direct SQL query against a remote PostgreSQL instance. Lines 7–17 employ MERGE with separate ON CREATE and ON MATCH clauses to ensure idempotently upsert customers while preserving existing relationships.

Debezium-Based CDC Pipeline for Operational Sources

Debezium captures row-level changes from database transaction logs and publishes them to Kafka as structured events.

JSON

// Example Debezium event for MySQL order table

{ “schema”: { … }, “payload”: { “before”: null,

{
"after": {
"order_id": "ORD-2025-000123",
"customer_id": "CUST-789",
"order_date": "2025-04-01T14:22:10Z",
"status": "CONFIRMED"
},
"source": {
"db": "sales",
"table": "orders"
},
"op": "c",
"ts_ms": 1743512530000
}

Python

# 6.1.2 Kafka Connect sink connector configuration for Neo4j
{
"name": "neo4j-sink-orders",
"config": {
"connector.class": "streams.kafka.connect.sink.Neo4jSinkConnector",
"topics": "dbserver1.sales.orders",
"neo4j.server.uri": "bolt+routing://neo4j-cluster.company.internal:7687",
"neo4j.authentication.type": "BASIC",
"neo4j.authentication.basic.username": "etl_service",
"neo4j.authentication.basic.password": "${file:/secrets/neo4j_etl.txt:password}",
"neo4j.topic.cypher.dbserver1.sales.orders": """
UNWIND $events AS event
MERGE (o:Order {orderId: event.after.order_id})
ON CREATE SET

o.status = event.after.status, o.orderedAt = datetime(event.after.order_date), o.sourceOffset = event.source.ts_ms

ON MATCH SET o.status = event.after.status

WITH o, event

MERGE (c:Customer {customerId: event.after.customer_id}) MERGE (c)-[r:PLACED]->(o) ON CREATE SET r.at = datetime(event.after.order_date)

""" } }

Commentary: Lines 11-24 contain a complete Cypher template executed per batch. The use of UNWIND $events processes multiple records in a single transaction. MERGE on both node and relationship prevents duplicates during replay.

6.2 Transforming Relational and NoSQL Data into Graph Structures

Section titled “6.2 Transforming Relational and NoSQL Data into Graph Structures”

Transformation requires understanding the semantic gap between normalization and connectedness.

Star Schema to Graph – Fact Table Explosion Pattern

Section titled “Star Schema to Graph – Fact Table Explosion Pattern”

Data warehouses store facts with foreign keys. Graph transformation requires materializing relationships explicitly.

cypher // 6.2.1 Transforming a classic star schema (sales fact + dimensions) CALL apoc.periodic.iterate( “CALL apoc.load.jdbc(‘jdbc:oracle:thin:@//oradb/prod’, ‘SELECT f.order_id, f.customer_key, f.product_key, f.store_key, f.date_key, f.quantity, f.revenue

FROM fact_sales f’) YIELD row RETURN row”,

WITH row

MERGE (o:Order {orderId: row.order_id})

MERGE (c:Customer {customerKey: row.customer_key})

MERGE (p:Product {productKey: row.product_key})

MERGE (s:Store {storeKey: row.store_key})

MERGE (d:Date {dateKey: row.date_key})

MERGE (c)-[:PLACED]->(o)

MERGE (o)-[:CONTAINS {quantity: row.quantity, revenue: row.revenue}]->(p)

MERGE (o)-[:SOLD_AT]->(s)

MERGE (o)-[:ON_DATE]->(d)

”,

{batchSize: 25000, parallel: true, retries: 3}

);

Commentary: Line 2 uses apoc.periodic.iterate for safe, restartable batch processing with parallelism. Lines 10–18 create five MERGE clauses per row, ensuring referential integrity without temporary staging nodes.

text

Document Store Denormalization to Graph Normalization

Section titled “Document Store Denormalization to Graph Normalization”

MongoDB collections often embed arrays. Graph loading requires flattening into relationships.

# 6.2.2 Python script to migrate MongoDB orders with embedded line items
from pymongo import MongoClient
from neo4j import GraphDatabase

import tqdm

mongo = MongoClient(“mongodb://mongo-prod:27017”) neo = GraphDatabase.driver(“bolt://localhost:7687”, auth=(“neo4j”, “Mastery2025!”))

def migrate_orders(batch_size=10000): collection = mongo.sales.orders total = collection.count_documents({})

for skip in tqdm.tqdm(range(0, total, batch_size)):
pipeline = [{"$skip": skip}, {"$limit": batch_size}]
batch = list(collection.aggregate(pipeline))
tx_query = """
UNWIND $batch AS row
MERGE (o:Order {orderId: row._id})
SET o.orderedAt = datetime(row.orderDate),
o.total = row.totalAmount
WITH o, row
UNWIND row.items AS item
MERGE (p:Product {sku: item.sku})
ON CREATE SET p.name = item.name, p.price = item.price
MERGE (o)-[li:CONTAINS {
quantity: item.qty,
lineTotal: item.price * item.qty
}]->(p)
"""
with neo.session() as session:
session.run(tx_query, batch=batch)

migrate_orders()

Commentary: Lines 23–29 unwind the embedded items array into separate relationships. MERGE on the relationship itself preserves quantity updates while preventing duplicate line items.

6.3 Loading and Streaming Data with ETL Pipelines

Section titled “6.3 Loading and Streaming Data with ETL Pipelines”

Modern pipelines must support both batch and streaming with identical semantics.

Apache NiFi Flow for Multi-Source Orchestration

Section titled “Apache NiFi Flow for Multi-Source Orchestration”
// 6.3.1 NiFi processors for CDC → Neo4j
[
{
"processor": "ConsumeKafka_2_6",
"config": {
"topics": "dbserver1.inventory.products",
"group.id": "neo4j-etl-products"
}
},
{
"processor": "JoltTransformJSON",
"config": {
"jolt.spec": "{ \"operation\": \"shift\", \"spec\": { \"payload\": { \"after\": \"&\" } } }"
}
},
{
"processor": "ExecuteScript",
"config": {
"script.engine": "python",
"script.body": "
import json, os
from org.apache.nifi.processor.io import StreamCallback

class PyStreamCallback(StreamCallback): def init(self): pass

def process(self, inputStream, outputStream):
batch = []
for line in inputStream:
batch.append(json.loads(line))
if len(batch) >= 5000:
flowFile = session.write(flowFile, json.dumps(batch))
session.transfer(flowFile, REL_SUCCESS)
batch = []
"""
"""
}
}
}
{
"processor": "PutNeo4j",
"config": {
"cypher": "
UNWIND $batch AS row
MERGE (p:Product {sku: row.sku})
SET p += row
"
}
}

Kafka Streams Application with Exactly-Once Semantics

// 6.3.2 Java Kafka Streams topology writing to Neo4j
<!-- page: 080 -->
2 StreamsSinkConfiguration config =
StreamsSinkConfiguration.builder()
3 .withBootstrapServers("kafka-prod:9092")
4 .withTopic("enriched-transactions")
5 .withNeo4jUrl("bolt://neo4j-cluster:7687")
6 .withAuthenticationBasic("etl", password)
7 .withEncryptionEnabled(true)
8 .build();
9
10 StreamsTopology topology =
StreamsTransactionEventRouter.builder()
11 .withStreamsSinkConfiguration(config)
12 .withDefaultCypherTemplate(
13 "UNWIND $events AS e " +
14 "MERGE (from:Account {id: e.fromId}) " +
15 "MERGE (to:Account {id: e.toId}) " +
16 "CREATE (from)-[t:TRANSFER {" +
17 "txId: e.txId, amount: e.amount, at: datetime(e.ts)" +
18 "}] ->(to)"
19 .build());
20
21 KafkaStreams streams = new KafkaStreams(topology, props);
22 streams.start();
# 6.4 Handling Large-Scale Graph Imports and Batch Processing
Terabyte-scale imports require careful memory and transaction management.
## Parallel CSV Import with apoc.periodic.iterate
cypher
1 // 6.4.1 Importing 500 million relationships in under 4 hours
2 CALL apoc.periodic.iterate(
<!-- page: 081 -->
"CALL apoc.load.csv('file:///large/transactions_*.csv', {
mapping: {
txId: {type: 'string'},
fromId: {type: 'string'},
toId: {type: 'string'},
amount: {type: 'float'},
ts: {type: 'string'}
}
}) YIELD row RETURN row",
WITH row
MERGE (from:Account {accountId: row.fromId})
MERGE (to:Account {accountId: row.toId})
CREATE (from)-[:TRANSFER {
txId: row.txId,
amount: row.amount,
at: datetime(replace(row.ts, ' ', 'T'))
}]->(to)
",
{batchSize: 50000, parallel: true, concurrency: 16, retries: 5}
);
Commentary: batchSize: 50000 with concurrency: 16 achieves approximately 800 000 relationships/second on a 64-core instance. parallel: true executes batches concurrently while preserving transaction boundaries.
Import Tool for Initial Loads
Bash
# 6.4.2 neo4j-admin import command for 100+ GB datasets
neo4j-admin database import full \
<!-- page: 082 -->
3 -- nodes=Customer="import/customers_header.csv,import/customers_*.csv" \ 4 -- nodes=Account="import/accounts_header.csv,import/accounts_*.csv" \ 5 -- relationships=OWNS="import/owns_header.csv,import/owns_*.csv" \ 6 -- relationships=TRANSFER="import/transfers_header.csv,import/transfers_*.csv" \ 7 --delimiter="," \ 8 --array-delimiter=";" \ 9 --skip-duplicate-nodes=true \ 10 --skip-bad-relationships=true \ 11 --multiline-fields=true 12 # Then start the database 14 neo4j start
# 6.5 Monitoring and Maintaining ETL Workflows for Consistency
Production pipelines require observability, alerting, and recovery.
## Pipeline Health Dashboard Queries
cypher
1 // 6.5.1 Lag monitoring for CDC topics 2 MATCH (p:Pipeline {name: "orders-cdc"}) 3 RETURN 4 p.lastProcessedOffset AS lastOffset, 5 p.lastCommitTime AS lastCommit, 6 datetime() - p.lastCommitTime AS lag, 7 p.errorCountLastHour AS errors
<!-- page: 083 -->
// 6.5.2 Data quality assertions
CALL {
MATCH (o:Order)
WHERE o.orderedAt IS NULL
RETURN count(o) AS nullDateOrders
}
CALL {
MATCH (o:Order)
WHERE NOT (o)-[:PLACED_BY]->(:Customer)
RETURN count(o) AS orphanOrders
}
RETURN nullDateOrders > 0 OR orphanOrders > 0 AS dataQualityAlert;
## Automated Backfill and Replay Pattern
### Python
python
# 6.5.3 Replay failed Kafka offsets
from kafka import lib import import_module
kafka_admin = import_module("kafka.admin")
admin_client = kafka_admin.KafkaAdminClient(bootstrap_servers="kafka-prod:9092")
# Reset consumer group to specific offset
admin_client.alter_consumer_group_offsets(
group_id="neo4j-sink-orders",
offsets=[
kafka_admin.TopicPartition("dbserver1.sales.orders", 15, 45000000)
]
)
<!-- page: 084 -->
15 # Resume processing
16 print("Backfill initiated from offset 45,000,000")
# Synthesis and Reflection
Data integration for Neo4j is no longer a collection of scripts and hope. It has matured into a disciplined engineering practice with standardized patterns for extraction, transformation, loading, streaming, and governance.
The practitioner who has internalized this chapter can now:
1. Choose the correct extraction strategy full, incremental, or log-based for any source system.
2. Transform decades-old relational schemas and modern document stores into performant, query-ready graph structures without data loss.
3. Execute batch imports measured in hundreds of billions of relationships with predictable runtime and zero downtime.
4. Operate streaming pipelines with exactly-once semantics and sub-second latency.
5. Monitor data quality and pipeline health with the same rigor applied to application code.
These capabilities transform Neo4j from an interesting database into the system of record for connected intelligence. The next chapters will explore how to operate these graphs at global scale, secure them for the most demanding regulatory environments, and embed them into modern microservices architectures. The foundation is complete. The enterprise graph platform stands ready.
<!-- page: 085 -->
15 # Resume processing
16 print("Backfill initiated from offset 45,000,000")
# Synthesis and Reflection
Data integration for Neo4j is no longer a collection of scripts and hope. It has matured into a disciplined engineering practice with standardized patterns for extraction, transformation, loading, streaming, and governance.
The practitioner who has internalized this chapter can now:
1. Choose the correct extraction strategy full, incremental, or log-based for any source system.
2. Transform decades-old relational schemas and modern document stores into performant, query-ready graph structures without data loss.
3. Execute batch imports measured in hundreds of billions of relationships with predictable runtime and zero downtime.
4. Operate streaming pipelines with exactly-once semantics and sub-second latency.
5. Monitor data quality and pipeline health with the same rigor applied to application code.
These capabilities transform Neo4j from an interesting database into the system of record for connected intelligence. The next chapters will explore how to operate these graphs at global scale, secure them for the most demanding regulatory environments, and embed them into modern microservices architectures. The foundation is complete. The enterprise graph platform stands ready.