安装py2neo
为了让python与Neo4j相连,需要安装python中的py2neo库:
1 pip3 install py2neo
开始实验测试
本次实验测试主要建立一个有关(购买方,价格,销售方)3元关系的数据库,数据库存储在表格之中。
如图所示:

提取数据
首先我们需要将表格中的数据提取出来:
1
2
3
4
5
6
7
8
9
10
11 class Datas():
def __init__(self):
self.path = 'Invoice_data_Demo.xls'
self.datas = pd.read_excel(self.path,header=0,encoding = 'utf-8')
def pd_data(self):
buy_key = [str(data) for data in self.datas['购买方名称']]
sell_key = [str(data) for data in self.datas['销售方名称']]
money_key = [str(data) for data in self.datas['金额']]
return {'sell_key':sell_key,'buy_key':buy_key,'money_key':money_key}

如图所示我们将表格数据以字典的形式提取出来。
链接数据库:
1 Link = Graph('http://localhost:7474',username = 'neo4j',password = 'xxxx')
在py2neo中只需要一行便与数据库有了联系。
创捷节点和关系:
在创建节点和关系时,需要注意的时节点的不重复性,因为购买方可以对应多个销售方,同时销售方也可以对应多个购买方。所以节点与关系需要分开创建:
首先创建全部节点,通过set集合的方法去重;然后使用查询语句找出关系对应的两个节点;最后创建关系:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 class Neo4j():
def __init__(self,datas):
self.link = Graph('http://localhost:7474',username = 'neo4j',password = 'csh826926')
self.link.delete_all()
self.datas = datas
self.Matcher = NodeMatcher(self.link)
def create_node(self):
for buy_name in list(set(self.datas['buy_key'])):
node = Node('购买方',name=buy_name)
self.link.create(node)
for sell_name in list(set(self.datas['sell_key'])):
node = Node('销售方',name=sell_name)
self.link.create(node)
def match_node(self,i):
buy_node = self.Matcher.match('购买方').where(f"_.name='{self.datas['buy_key'][i]}'").first()
sell_node = self.Matcher.match('销售方').where(f"_.name='{self.datas['sell_key'][i]}'").first()
print([buy_node,sell_node])
return [buy_node,sell_node]
def create_relationship(self):
for i in range(len(self.datas['buy_key'])):
relationship = Relationship(self.match_node(i)[0],self.datas['money_key'][i],self.match_node(i)[1])
self.link.create(relationship)
验证
回到数据库页面,如下图即为成功:
