import neo4j
import pandas as pd
from data2neo.relational_modules.pandas import PandasDataFrameIterator
from data2neo import IteratorIterator, Converter, Attribute, register_attribute_postprocessor
from data2neo.utils import load_file
import csv
import os
import time
import multiprocessing as mp
from typing import List, Tuple, Dict
# Setup the neo4j uri and credentials
uri = "bolt:localhost:7687"
auth = neo4j.basic_auth("neo4j", "password")
# Placeholder for dataframes
people = pd.DataFrame({"ID":[1,2], "FirstName": ["[Redacted Person]", "[Redacted Person]"], "LastName":["[Redacted Person]", "[Redacted Person]"], "FavoriteFlower":["virginica","setosa"]})
iris = pd.DataFrame({"sepal_length": [1,2], "sepal_width":[3,4], "petal_length":[5,6], "petal_width":[7,8], "species":["versicolor", "virginica"]})
people_iterator = PandasDataFrameIterator(people, "Person")
iris_iterator = PandasDataFrameIterator(iris, "Flower")
# register a custom data processing function
@register_attribute_postprocessor
def append(attribute, append_string):
new_attribute = Attribute(attribute.key, str(attribute.value) + append_string)
return new_attribute
# Create IteratorIterator
iterator = IteratorIterator([people_iterator, iris_iterator])
# Load the schema file (example)
schema_file = "./tests/integration/resources/schema_end_to_end.yaml" # Replace with path to schema file
schema = load_file(schema_file)
class CSVConverter(Converter):
def __init__(self, schema: str, iterator, output_dir: str, neo4j_uri: str, neo4j_auth: Auth, num_workers: int = None, serialize: bool = False, batch_size: int = 5000):
super().__init__(schema, iterator, neo4j_uri, neo4j_auth, num_workers, serialize, batch_size)
self.output_dir = output_dir
# Initialize directory
os.makedirs(self.output_dir, exist_ok=True)
self.node_files = {}
self.relationship_files = {}
def __call__(self, progress_bar: "tdqm.tqdm" = None, skip_nodes = False, skip_relationships = False) -> None:
"""Runs the convertion and exports the produced nodes and relationships to CSV files.
Args:
progress_bar: An optional tqdm like instance for a progress bar.
skip_nodes: (default: False) If true creation of nodes will be skiped. ATTENTION: this might lead to problems if you use identifiers.
skip_relationships: If true creation of relationships will be skiped (default: False)
"""
# Check if a progress bar was passed
pb = None
if progress_bar is not None:
pb = progress_bar(total=2*len(self._iterator))
if skip_nodes:
pb.update(len(self._iterator))
start = time.time()
config = self._create_worker_config()
conversion_objects = (self._factories, self._node_mask, self._relationship_mask)
if not self._serialize:
with mp.Pool(processes=self._num_workers, initializer=self._init_process_state,
initargs=(config, conversion_objects, self._get_global_shared_state()),
maxtasksperchild=50) as pool:
if not skip_nodes:
config.set_work_type(0)
processed_batches = self._process_iteration(pool, self._create_batcher(self._iterator), config)
self._write_csv_files(processed_batches, WorkType.NODE)
else:
print("Skipping creation of nodes.")
if not skip_relationships:
config.set_work_type(1)
self._process_iteration(pool, processed_batches, config)
self._write_csv_files(processed_batches, WorkType.RELATIONSHIP)
else:
print("Skipping creation of relationships.")
else:
try:
self._init_process_state(config, conversion_objects, self._get_global_shared_state())
if not skip_nodes:
config.set_work_type(0)
processed_batches = []
for batch in map(self._process_batch, self._create_batcher(self._iterator)):
processed_batches.append(batch)
self._write_csv_files(processed_batches, WorkType.NODE)
else:
print("Skipping creation of nodes.")
if not skip_relationships:
config.set_work_type(1)
for batch in map(self._process_batch, processed_batches):
processed_batches.append(batch)
self._write_csv_files(processed_batches, WorkType.RELATIONSHIP)
else:
print("Skipping creation of relationships.")
finally:
self._cleanup_process_state()
# make sure that the progress bar is updated one last time
if pb is not None:
pb.n = len(self._iterator)
pb.refresh()
time.sleep(0.1)
pb.close()
print(f"Conversion finished. CSV files are in '{self.output_dir}'. This run took {int(time.time()-start)}s")
def _write_csv_files(self, processed_batches: List[List[List]], work_type: int) -> None:
if work_type == WorkType.NODE:
print("Writing nodes to CSV file.")
for resource_batch in processed_batches:
for resource in resource_batch:
self._write_resource_to_csv(resource, WorkType.NODE)
else:
print("Writing relationships to CSV file.")
for resource_batch in processed_batches:
for resource in resource_batch:
self._write_resource_to_csv(resource, WorkType.RELATIONSHIP)
def _write_resource_to_csv(self, resource, work_type: int):
"""
This function intercepts the output of the converter and writes the nodes and relationships to CSV files.
"""
mask = self._node_mask if work_type == WorkType.NODE else self._relationship_mask
if resource.type in mask:
# If the resource is not in the mask (meaning we don't need to convert it), we skip it
# This is mainly done for performance reasons, as the conversion is not needed
factory = self._factories[resource.type][int(work_type)]
try:
subgraph = factory.construct(resource)
except Exception as err:
err.args += (f"Encountered error when processing {'nodes' if work_type == WorkType.NODE else 'relationships'} of {resource}.",)
raise err
if work_type == WorkType.NODE:
for node in subgraph.nodes:
self._write_node_to_csv(node)
else:
for rel in subgraph.relationships:
self._write_relationship_to_csv(rel)
return
def _write_node_to_csv(self, node):
"""Writes a single node to the corresponding CSV file."""
label = node.labels[0] # Assuming one label per node
file_path = os.path.join(self.output_dir, f"{label}_nodes.csv")
if label not in self.node_files:
file = open(file_path, 'w', newline='', encoding='utf-8')
writer = csv.writer(file)
header = [":ID"]
header.extend(list(node.properties.keys()))
header.append(":LABEL")
writer.writerow(header)
self.node_files[label] = (file, writer)
file, writer = self.node_files[label]
row = [node.__primarykey__]
row.extend(list(node.properties.values()))
row.append(label)
writer.writerow(row)
def _write_relationship_to_csv(self, relationship):
"""Writes a single relationship to the corresponding CSV file."""
rel_type = relationship.type
file_path = os.path.join(self.output_dir, f"{rel_type}_relationships.csv")
if rel_type not in self.relationship_files:
file = open(file_path, 'w', newline='', encoding='utf-8')
writer = csv.writer(file)
header = [":START_ID", ":END_ID"]
header.extend(list(relationship.properties.keys()))
header.append(":TYPE")
writer.writerow(header)
self.relationship_files[rel_type] = (file, writer)
file, writer = self.relationship_files[rel_type]
row = [relationship.start_node_id, relationship.end_node_id]
row.extend(list(relationship.properties.values()))
row.append(rel_type)
writer.writerow(row)
def _create_worker_config(self):
"""Creates the worker config for this instance.
"""
config = super()._create_worker_config()
config.graph_lock = mp.Lock()
config.processed_lock = mp.Lock()
return config
def _create_batcher(self, iterator):
"""Creates a batcher based on the iterator.
"""
return super()._create_batcher(iterator, binarize=False)
def _process_batch(self, batch) -> None:
"""
Main conversion processing. While the worker is not notified to stop (with the exit flag),
it repeatedly askes the iterator for a next resource to process. If the iterator reports that the
data is traversed fully, the method returns.
"""
try:
work_type = 0 if self._process_config.nodes_flag.is_set() else 1
mask = self._process_config.node_mask if work_type == 0 else self._process_config.relationship_mask
processed_resources = []
for i, resource in enumerate(batch) :
if self._process_config.exit_flag.is_set():
# If the exit flag is set, we stop processing
return []
if resource.type in mask:
# If the resource is not in the mask (meaning we don't need to convert it), we skip it
# This is mainly done for performance reasons, as the conversion is not needed
processed_resources.append(resource)
return processed_resources
except Exception as err:
raise err
output_dir = "./csv_output" # Define where CSV files will be saved
csv_converter = CSVConverter(schema, iterator, output_dir, uri, auth, serialize=True)
csv_converter()