Neo4j的Python程序操作
- 创建节点
from py2neo import *
import pandas as pd
graph = Graph('http://localhost:7474/', username="neo4j",password="root")
def CreateNode(m_graph,m_label,m_attrs):
m_n="_.name="+"\'"+m_attrs['name']+"\'"
matcher =NodeMatcher(m_graph)
re_value =matcher.match(m_label).where(m_n).first()
if re_value is None:
m_node=Node(m_label,**m_attrs)
n=graph.create(m_node)
return n
return None
label ='Stock'
attrs1={"name":'招商银行',"code":'600036'}
label2='SecuritiesExchange'
attrs2={"name":'上海证券交易所'}
CreateNode(graph,label,attrs1)
CreateNode(graph,label2,attrs2)
- 建立关系
def MatchNode(m_graph,m_label,m_attrs):
m_n="_.name="+"\'"+m_attrs['name']+"\'"
matcher =NodeMatcher(m_graph)
re_value =matcher.match(m_label).where(m_n).first()
return re_value
def CreateRelationship(m_graph,m_label1,m_attrs1,m_label2,m_attrs2,m_r_name):
reValue1=MatchNode(m_graph,m_label1,m_attrs1)
reValue2=MatchNode(m_graph,m_label2,m_attrs2)
if reValue1 is None or reValue1 is None:
return False
m_r =Relationship(reValue1,m_r_name,reValue2)
n=m_graph.create(m_r)
return n
label1 ='Stock'
attrs1={"name":'招商银行',"code":'600036'}
label2='SecuritiesExchange'
attrs2={"name":'上海证券交易所'}
m_r_name="证券交易所"
reValue=CreateRelationship(graph,label1,attrs1,label2,attrs2,m_r_name)
- 查询操作
def MatchNodeByID(m_graph,m_id):
matcher = NodeMatcher(m_graph)
re_value = matcher.get(m_id)
return re_value
def MatchNodeByAttr(m_graph,m_label,m_attrs):
m_n = "_.name=" + "\'" + m_attrs['name'] + "\'"
matcher = NodeMatcher(m_graph)
re_value = matcher.match(m_label).where(m_n).first()
return re_value
def MatchNodeByLabel(m_graph,m_label):
matcher = NodeMatcher(m_graph)
re_value = matcher.match(m_label)
return re_value
print(MatchNodeByID(graph,0))
print(MatchNodeByAttr(graph,'Stock',{"name":'招商银行',"code":'600036'}))
print(MatchNodeByLabel(graph,'Stock'))
- 批量创建节点