neo4j vs python

1.将库中已经存在的两个节点,创建关系。

查询库中只有2个独立的节点。

方式一,python,使用py2neo库

python 复制代码
#coding:utf-8
from py2neo import Graph,Node,Relationship,NodeMatcher
 
##连接neo4j数据库,输入地址、用户名、密码
graph = Graph('bolt://xx.xx.xx.xx:7687',auth=("neo4j","neo4j1234"))

hd = graph.nodes.match("person",name="宋太祖").first()
hh = graph.nodes.match("person",name="皇后").first()

graph.create(Relationship(hd,"夫妻",hh))

执行成功

查看库

方式二:使用neo4j, 原生cypher语句

python 复制代码
#coding:utf-8
from neo4j import GraphDatabase

##获取已经存在的节点,创建关系
driver = GraphDatabase.driver('bolt://xx.xx.xx.xx:7687',auth=("neo4j","neo4j1234"))

with driver.session() as session:
    hd = session.run("MATCH (a:person {name:'宋太祖'}) return a").single().get("a")
    hh = session.run("MATCH (b:person {name:'皇后'}) RETURN b").single().get("b")

    session.run("Match (a:person), (b:person) where a.name='皇后' and b.name='宋太祖' create (a) - [:老婆] -> (b)")
driver.close()

查看库

看着上面的脚本就奇怪,那获取节点干嘛呢,信息存入了变量里,后面又没用到这个变量。

直接用最后面的cypher语句,不就能执行了嘛。执行一次,没报错,查看库

果然不需要那两句,直接match查询就可以。

总结

通过这两个方式也看出来了,还是用封装好的方法操作便捷,出错的概率也小。

相关推荐
明月_清风6 小时前
Python 装饰器前传:如果不懂“闭包”,你只是在复刻代码
后端·python
明月_清风6 小时前
打破“死亡环联”:深挖 Python 分代回收与垃圾回收(GC)机制
后端·python
ZhengEnCi1 天前
08c. 检索算法与策略-混合检索
后端·python·算法
明月_清风1 天前
Python 内存手术刀:sys.getrefcount 与引用计数的生死时速
后端·python
明月_清风1 天前
Python 消失的内存:为什么 list=[] 是新手最容易踩的“毒苹果”?
后端·python
Flittly2 天前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(3)TodoWrite (待办写入)
python·agent
千寻girling2 天前
一份不可多得的 《 Django 》 零基础入门教程
后端·python·面试
databook2 天前
探索视觉的边界:用 Manim 重现有趣的知觉错觉
python·动效
明月_清风2 天前
Python 性能微观世界:列表推导式 vs for 循环
后端·python
明月_清风2 天前
Python 性能翻身仗:从 O(n) 到 O(1) 的工程实践
后端·python