如何解决networkx 图中的哪些元素可能会成为 neo4j 图中的标签?
我在 networkx 中有一个 MultiDiGraph,我正在考虑将它导出到 neo4j。我已经有一个名为 ntype 的节点属性和一个名为 dtype 的边属性,它符合 neo4j 图的节点和边的标签概念。
networkx 中的哪些元素可能会成为 neo4j 的标签?如何管理?
我在 python 中添加了一个图形示例,以及导出到 neo4j 时我想得到的图形。
这是python的代码
import networkx as nx
G=nx.MultiDiGraph()
G.add_nodes_from([
(1,{'ntype':'NUMBER','color':'blue'}),(2,'color':'yellow'}),('A',{'ntype':'LETTER','state':'done'}),('B','state':'pending'})
])
G.add_edges_from([
(1,'A','dir',{'etype':'IMPACTS','when':'old'}),(1,'n_dir','when':'new'}),'B',{'etype':'ALTS','when':'future'}),])
这是从 networkx 导入时我想要的图的 Neo4j 代码
CREATE (one:NUMBER {name:1,color:'blue'})
CREATE (two:NUMBER {name:2,color:'yellow'})
CREATE (A:LETTER {name:'A',state:'done'})
CREATE (B:LETTER {name:'B',state:'pending'})
CREATE (one)-[:IMPACTS {k:'dir',when:'old'}]->(A)
CREATE (one)-[:IMPACTS {k:'n_dir',when:'new'}]->(A)
CREATE (one)-[:IMPACTS {k:'n_dir',when:'future'}]->(B)
CREATE (two)-[:ALTS {k:'dir',when:'new'}]->(B)
CREATE (two)-[:IMPACTS {k:'n_dir',when:'old'}]->(B)
CREATE (two)-[:ALTS {k:'n_dir',when:'new'}]->(A)
我已经尝试在 networkx 中导出到 graphml 并在 neo4j 中导入,如此处 enter link description here 所述。我还添加了参数 readLabels 和 storeNodeIds。从浏览器:
CALL apoc.import.graphml("test.graphml",{readLabels: true,storeNodeIds:true})
现在我得到了边的标签,但我没有得到节点的标签。这就是我得到的:
解决方法
我做了一些研究,最后我有了一个能够将 networkx 图导出到管理标签的 neo4j 图的过程。 必须考虑一些细节:
1.- 创建节点时:在neo4j中成为标签的属性必须命名为标签(注意是复数,不要问为什么,它有效)。它的值必须是一个以':'开头的字符串
G.add_nodes_from([(1,{'labels':':NUMBER','color':'blue'}),('A',{'labels':':LETTER','state':'done'})])
2.- 创建边时:在neo4j中成为标签的属性必须命名为label(现在是单数!!)。它的值必须是一个以':'开头的字符串
G.add_edges_from([(1,'A','dir',{'label':'IMPACTS','when':'old'})])
3.- 对于 MultiDiGraph 不会导入 k 值。我的解决方法是复制k作为边缘属性,例如id。
for u,v,k in G.edges(keys=True):
G[u][v][k]['id']=k
4.- 使用 named_key_ids=True
将 networkx 图导出到 graphmlnx.write_graphml(G,'test.graphml',named_key_ids=True)
5.- 使用参数 readLabels: true 和 storeNodeIds:true 导入到 neo4j。在 Neo4j 浏览器中,您可能有:
CALL apoc.import.graphml("test.graphml",{readLabels: true,storeNodeIds:true})
这里我包含了一个在 networkx 中创建的图,可以按照描述导入到 neo4j:
import networkx as nx
G=nx.MultiDiGraph()
#creation of nodes with property called 'labels'
G.add_nodes_from([
(1,(2,'color':'yellow'}),'state':'done'}),('B','state':'pending'})
])
#creation of edges with property called 'label'
G.add_edges_from([
(1,'when':'old'}),(1,'n_dir','when':'new'}),'B',{'label':'ALTS','when':'future'}),])
#k is duplicated at every node as a property
for u,k in G.edges(keys=True):
G[u][v][k]['id']=k
nx.write_graphml(G,named_key_ids=True)
待定的是什么?弄清楚如何为节点或边分配多个标签。欢迎任何帮助
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。