Loading

使用Python中py2neo库操作Neo4j


返回 我的技术栈(Technology Stack)



安装py2neo

下面三个你选一个吧!
pip install py2neo
pip install -i http://mirrors.aliyun.com/pypi/simple py2neo
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple py2neo
如果报以下错误:ValueError: check_hostname requires server_hostname
通常一个可能是,由网络代理导致的问题,即你开着VPN下呢,关了就好了;
另一个可能是,因为版本冲突等原因,你在下载的时候指定下版本py2neo==2.0啥的。
image


开启Neo4j服务

如果你还没有安装,可以看看这篇博客:Neo4j安装

安装好后,使用管理员身份运行CMD,执行 neo4j.bat console
image

如果密码忘记了,可以看这个章节的官方文档:Password and user recovery或者neo4j重置密码


连接使用Neo4j

创建节点

# from py2neo import *     # *中常用的是Node,Relationship,Graph
from py2neo import Node, Graph, Relationship

if __name__ == '__main__':
    neo_graph = Graph("http://localhost:7474", password="neo4j4j")
    test_node_1 = Node("Testing", name="test_node_1")  # 注意:这里不要加“label=”,否则label会以属性的形式展示,而非标签
    test_node_2 = Node("Testing", name="test_node_2")
    neo_graph.create(test_node_1)
    neo_graph.create(test_node_2)

上面的代码相当于CQL语句: CREATE (:Testing {name:'test_node_1'}), (:Testing {name:'test_node_2'})
image

建立节点间关系

if __name__ == '__main__':
    neo_graph = Graph("http://localhost:7474", password="neo4j4j")
    test_node_1 = Node("Testing", name="test_node_1")  # 注意:这里不要加“label=”,否则label会以属性的形式展示,而非标签
    test_node_2 = Node("Testing", name="test_node_2")

    node_1_call_node_2 = Relationship(test_node_1, 'CALL', test_node_2)
    node_1_call_node_2['count'] = 1
    node_1_call_node_1 = Relationship(test_node_1, 'CALL', test_node_1)
    node_1_call_node_1['count'] = 2
    neo_graph.create(node_1_call_node_2)
    neo_graph.create(node_1_call_node_1)

上面代码建立了两条关系,关系的类型为"CALL",两条关系都有属性count,且值为1。
image

直接执行Cypher语句(run)

if __name__ == '__main__':
    neo_graph = Graph("http://localhost:7474", password="neo4j4j")
    neo_graph.run("CREATE (:pig{name:'猪爸爸',age:12})-[:夫妻]->(:pig{name:'猪妈妈',age:10})")

image


参考:
[1]https://blog.csdn.net/u010037715/article/details/118277228
[2]https://neo4j.com/docs/
[3]https://www.pianshen.com/article/32141059454/
[4]https://blog.csdn.net/qq_38486203/article/details/79826028


posted @ 2021-07-31 15:19  言非  阅读(1264)  评论(0编辑  收藏  举报