How to import a graph from neo4j into dgl

Hi everyone,

I am currently trying to import my neo4j graph in the dgl library but I don’t know how to do it.
If any of you have an idea, I will be happy to take it !

Thank you all !

Hi @aure_bnp , I am not familiar with neo4j. But if the graph in neo4j can be converted in scipy, networkx or pytorch tensor, then it can be converted to DGL graph.

1 Like

The GDS library may be helpful: GitHub - neo4j/graph-data-science-client: A Python client for the Neo4j Graph Data Science (GDS) library

1 Like

As mentioned above, one way is to first create a networkx graph and then convert it. Here’s a simple example (more details in the docs 1.4 Creating Graphs from External Sources — DGL 1.1 documentation):

import networkx as nx
from neo4j import GraphDatabase

uri = "bolt://localhost:7687"  # Update with your Neo4j connection details
username = "your_username"
password = "your_password"

driver = GraphDatabase.driver(uri, auth=(username, password))

query = "MATCH (n)-[r]->(m) RETURN n, r, m"  # Replace with your actual query

with driver.session() as session:
    result = session.run(query)
    data = result.data()

nx_graph = nx.Graph()

for row in data:
    # Extract the nodes and relationships from the query result
    node1 = row['n']
    rel = row['r']
    node2 = row['m']
    
    # Add nodes to the graph
    nx_graph.add_node(node1['name'], label=node1['label'])
    nx_graph.add_node(node2['name'], label=node2['label'])
    
    # Add edges to the graph
    nx_graph.add_edge(node1['name'], node2['name'], relationship=rel['type'])

my_dgl_graph = dgl.from_networkx(nx_graph)

# Use my_dgl_graph ...
3 Likes

Thank you all. That fixed my problem

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.