Which Elements From Networkx Graph Might Become Labels At Neo4j Graph?
Solution 1:
I made some reserch and finally I have got a process to be able to export a networkx graph into a neo4j graph managing the labels. Some details have to be considered:
1.- When creating the nodes: the property to become a label at neo4j must be named as labels (notice that it is in plural, do not ask why, it works). Its value must be a string starting with ':'
G.add_nodes_from([(1,{'labels':':NUMBER', 'color':'blue'}), ('A',{'labels':':LETTER', 'state':'done'})])
2.- When creating the edges: the property to become a label at neo4j must be named as label (now it is in singular!!). Its value must be a string starting with ':'
G.add_edges_from([(1,'A','dir',{'label':'IMPACTS', 'when':'old'})])
3.- For MultiDiGraph the k value is not going to be imported. My workarround is to duplicate k as an edge property called, for exampel id.
for u,v,k in G.edges(keys=True):
G[u][v][k]['id']=k
4.- Export networkx graph to graphml using named_key_ids=True
nx.write_graphml(G, 'test.graphml', named_key_ids=True)
5.- Import to neo4j with parameteres readLabels: true and storeNodeIds:true. At neo4j browser you might have:
CALL apoc.import.graphml("test.graphml", {readLabels: true, storeNodeIds:true})
Here I include a graph created in networkx that can be imported to neo4j as described:
import networkx as nx
G=nx.MultiDiGraph()
#creation of nodes with property called 'labels'
G.add_nodes_from([
(1,{'labels':':NUMBER', 'color':'blue'}),
(2,{'labels':':NUMBER', 'color':'yellow'}),
('A',{'labels':':LETTER', 'state':'done'}),
('B',{'labels':':LETTER', 'state':'pending'})
])
#creation of edges with property called 'label'
G.add_edges_from([
(1,'A','dir',{'label':'IMPACTS', 'when':'old'}),
(1,'A','n_dir',{'label':'IMPACTS', 'when':'new'}),
(1,'B','n_dir',{'label':'ALTS', 'when':'future'}),
(2,'B','dir',{'label':'IMPACTS', 'when':'new'}),
(2,'B','n_dir',{'label':'IMPACTS', 'when':'old'}),
(2,'A','n_dir',{'label':'ALTS', 'when':'new'}),
])
#k is duplicated at every node as a propertyfor u,v,k in G.edges(keys=True):
G[u][v][k]['id']=k
nx.write_graphml(G, 'test.graphml', named_key_ids=True)
What is pending? To figure out how to assing to a node or an edge more than one label. Any help will be welcome
Post a Comment for "Which Elements From Networkx Graph Might Become Labels At Neo4j Graph?"