Neo4j图数据库(四):在Python中使用neo4j【neo4j-driver、py2neo:对Neo4j数据库进行增删改查的python第三方库】

一、neo4j-driver的安装:

neo4j-driver简介: neo4j-driver是一个python中的package, 作为python中neo4j的驱动, 帮助我们在python程序中更好的使用图数据库.

pip install neo4j-driver

1、neo4j-driver使用演示:

from neo4j import GraphDatabase

# 关于neo4j数据库的用户名,密码信息已经配置在同目录下的config.py文件中
from config import NEO4J_CONFIG

driver = GraphDatabase.driver( **NEO4J_CONFIG)

# 直接用python代码形式访问节点Company, 并返回所有节点信息
with driver.session() as session:
    cypher = "CREATE(c:Company) SET c.name='黑马程序员' RETURN c.name"
    record = session.run(cypher)
    result = list(map(lambda x: x[0], record))
    print("result:", result)

输出效果:

result: 黑马程序员

2、事务的概念

如果一组数据库操作要么全部发生要么一步也不执行,我们称该组处理步骤为一个事务, 它是数据库一致性的保证.

使用事务的演示:

def _some_operations(tx, cat_name, mouse_name):
    tx.run("MERGE (a:Cat{name: $cat_name})"
           "MERGE (b:Mouse{name: $mouse_name})"
           "MERGE (a)-[r:And]-(b)",
           cat_name=cat_name, mouse_name=mouse_name)


with driver.session() as session:
    session.write_transaction(_some_operations, "Tom", "Jerry")

输出效果:

Neo4j图数据库(四):在Python中使用neo4j【neo4j-driver、py2neo:对Neo4j数据库进行增删改查的python第三方库】_第1张图片

二、Python连接Neo4j工具:py2neo

# -*- coding: utf-8 -*-
from py2neo import Node, Graph, Relationship,NodeMatcher

# 将excel中数据存入neo4j
class DataToNeo4j(object):
    def __init__(self):
        link = Graph("http://localhost:7474", username="neo4j", password="123456")  # 建立连接
        self.graph = link
        self.buy = 'buy'    # 定义label
        self.sell = 'sell'  # 定义label
        self.graph.delete_all() # 清空数据库
        self.matcher = NodeMatcher(link)    # 匹配关系的方法

        """ 示例
        node3 = Node('animal' , name = 'cat')
        node4 = Node('animal' , name = 'dog')  
        node2 = Node('Person' , name = 'Alice')
        node1 = Node('Person' , name = 'Bob')  
        r1 = Relationship(node2 , 'know' , node1)    
        r2 = Relationship(node1 , 'know' , node3) 
        r3 = Relationship(node2 , 'has' , node3) 
        r4 = Relationship(node4 , 'has' , node2)    
        self.graph.create(node1)
        self.graph.create(node2)
        self.graph.create(node3)
        self.graph.create(node4)
        self.graph.create(r1)
        self.graph.create(r2)
        self.graph.create(r3)
        self.graph.create(r4)
        """
    # 建立节点
    def create_node(self, node_buy_key,node_sell_key):
        for name in node_buy_key:
            buy_node = Node(self.buy, name=name)
            self.graph.create(buy_node)
        for name in node_sell_key:
            sell_node = Node(self.sell, name=name)
            self.graph.create(sell_node)
            
    # 建立关系
    def create_relation(self, df_data):
        m = 0
        for m in range(0, len(df_data)):
            try:    
                print(list(self.matcher.match(self.buy).where("_.name=" + "'" + df_data['buy'][m] + "'")), list(self.matcher.match(self.sell).where("_.name=" + "'" + df_data['sell'][m] + "'")))
                relation = Relationship(self.matcher.match(self.buy).where("_.name=" + "'" + df_data['buy'][m] + "'").first(),
                                        df_data['money'][m],
                                        self.matcher.match(self.sell).where("_.name=" + "'" + df_data['sell'][m] + "'").first()
                                       )
                self.graph.create(relation)
            except AttributeError as e:
                print(e, m)
            
# -*- coding: utf-8 -*-
from dataToNeo4jClass.DataToNeo4jClass import DataToNeo4j
import os
import pandas as pd
#pip install py2neo==5.0b1 注意版本,要不对应不了【可以先阅读下文档:https://py2neo.org/v4/index.html】

invoice_data = pd.read_excel('./Invoice_data_Demo.xls', header=0)
print("invoice_data = {}".format(invoice_data))

# 从excel文件中抽取“节点”数据
def data_extraction():
    node_buy_key, node_sell_key = [], []
    for i in range(0, len(invoice_data)):   # 取出购买方名称到list
        node_buy_key.append(invoice_data['购买方名称'][i])
    for i in range(0, len(invoice_data)):   # 取出销售方名称到list
        node_sell_key.append(invoice_data['销售方名称'][i])
    node_buy_key, node_sell_key = list(set(node_buy_key)), list(set(node_sell_key))   # 去重
    return node_buy_key, node_sell_key

# 从excel文件中抽取“关系”数据
def relation_extraction():
    links_dict, sell_list, money_list, buy_list = {}, [], [], []
    for i in range(0, len(invoice_data)):
        money_list.append(invoice_data[invoice_data.columns[19]][i])#金额
        sell_list.append(invoice_data[invoice_data.columns[10]][i])#销售方方名称
        buy_list.append(invoice_data[invoice_data.columns[6]][i])#购买方名称
    sell_list, buy_list, money_list = [str(i) for i in sell_list], [str(i) for i in buy_list], [str(i) for i in money_list] # 将数据中int类型全部转成string
    links_dict['buy'], links_dict['money'], links_dict['sell']= buy_list, money_list, sell_list # 整合数据,将三个list整合成一个dict
    df_data = pd.DataFrame(links_dict)  # 将数据转成DataFrame
    print("df_data= {}".format(df_data))
    return df_data

relation_extraction()
create_data = DataToNeo4j()
create_data.create_node(data_extraction()[0], data_extraction()[1])
create_data.create_relation(relation_extraction())

输出结果:

在这里插入代码片

你可能感兴趣的:(Neo4J,Neo4j,neo4j-driver,py2neo)