Python中py2neo库的基本使用方法

因为需要将处理好的csv文件用neo4j存储,因此想到使用python将数据导入neo4j,就需要用到py2neo库。

安装py2neo库:

pip install py2neo

首先是建立连接:

from py2neo import Node, Relationship, Graph, NodeMatcher, RelationshipMatcher
# 打开数据库
graph = Graph("http://localhost:7474/", auth=("neo4j", "123456"))

注意:这里传入用户名和密码使用的auth元组形式

建立简单的关系图

a = Node("Person", name="Alice", sex="female", ID="222")
b = Node("Person", name="Bob", sex="male", ID="123")
ab = Relationship(a, "KNOWS", b)
graph.create(ab)

Node和Relationship可以定义对应的实例,Node第一个参数是label, 再利用graph.create()创建。打开neo4j可以看到如下图:
Python中py2neo库的基本使用方法_第1张图片

可以看到已经建立成功。

查询

查询的类型通常就是查询节点和关系,对应的就是NodeMatcher, RelationshipMatcher两个类:

macher1 = NodeMatcher(graph)
macher2 = RelationshipMatcher(graph)
node1 = macher1.match("Person", ID="123")  # 匹配ID为123的节点
node2 = macher2.match(r_type="KNOWS").limit(25)  # 找出关系类型为KNOWS的前25个关系

result1 = list(node1)
print(result1)
result2 = list(node2)
print(result2)

运行结果如下:
在这里插入图片描述
下面就用一个实例来演示用python建立neo4j:

实例

创建节点

创建节点的函数:

# 建立一个节点
def create_node(graph, label, attrs):
    n = "_.name=" + "\"" + attrs["name"] + "\""
    matcher = NodeMatcher(graph)
    # 查询是否已经存在,若存在则返回节点,否则返回None
    value = matcher.match(label).where(n).first()
    # 如果要创建的节点不存在则创建
    if value is None:
        node = Node(label, **attrs)
        n = graph.create(node)
        return n
    return None

然后创建两个节点:

label1 = "Stock"
attrs1 = {"name": "招商银行", "code": "600036"}
label2 = "SecuritiesExchange"
attrs2 = {"name": "上海证券交易所"}
create_node(graph, label1, attrs1)
create_node(graph, label2, attrs2)

结果如下:
Python中py2neo库的基本使用方法_第2张图片

创建关系

这里需要用到两个函数:

# 建立两个节点之间的关系
def create_relationship(graph, label1, attrs1, label2, attrs2, r_name):
    value1 = match_node(graph, label1, attrs1)
    value2 = match_node(graph, label2, attrs2)
    if value1 is None or value2 is None:
        return False
    r = Relationship(value1, r_name, value2)
    graph.create(r)


# 查询节点
def match_node(graph, label, attrs):
    n = "_.name=" + "\"" + attrs["name"] + "\""
    matcher = NodeMatcher(graph)
    return matcher.match(label).where(n).first()

然后在主函数中添加如下语句:

r = "证券交易所"
create_relationship(graph, label1, attrs1, label2, attrs2, r)

即创建成功:
Python中py2neo库的基本使用方法_第3张图片

修改结点属性值

有时候我们需要更新结点的属性值,或者添加新的属性,可以使用如下方法。

首先对于名为上海证券交易所的结点,其属性值只有name这一个属性:
Python中py2neo库的基本使用方法_第4张图片
然后我们尝试修改其属性值并添加一个名为addr的属性:

label2 = "SecuritiesExchange"
attrs2 = {"name": "上海证券交易所"}
node = match_node(graph, label2, attrs2)  # 找到对应的结点
node.update({"name": "北交所", "addr": "北京"})  # 修改结点的属性
graph.push(node)  # 更新结点,注意:如果没有这一步,则结点不会被更新

运行之后,我们再来查看可以得到如下截图:
Python中py2neo库的基本使用方法_第5张图片

你可能感兴趣的:(Python,人工智能,数据库,python,知识图谱,开发语言)