首页 > 编程笔记 > Python笔记 阅读:38

Python操作Neo4j(非常详细)

Python 操作 Neo4j 可以采用官方的 neo4j 库,也可采用 py2neo 库,本文采用的是官方的 neo4j 库。

Python安装Neo4j依赖

打开命令行,通过 pip 命令安装 Neo4j 驱动,代码如下:
pip install neo4j==4.0.3
得到的返回值如下:
Installing collected packages: pytz, neo4j
Successfully installed neo4j-4.0.3 pytz-2021.1
表示 Neo4j 驱动安装成功。

Python操作Neo4j的方法

在 Python 编辑器中创建 Neo4jDemo.py 文件后,我们就可以开始编写代码了。

导入 Python 模块,代码如下:
from neo4j import GraphDatabase

定义 HelloWorldExample 类,其中包含相关函数,代码如下:
class HelloWorldExample:
    def __init__(self, uri, user, password):
        self.driver = GraphDatabase.driver(uri, auth = (user, password))
    def close(self):
        self.driver.close()
    def print_greeting(self, message):
        with self.driver.session() as session:
            greeting = session.write_transaction(self._create_and_return_greeting,
                      message)
            print(greeting)
    @staticmethod
    def _create_and_return_greeting(tx, message):
        result = tx.run("CREATE (a:PythonGreeting) "
                        "SET a.message = $message "
                        "RETURN a.message + ', from node ' + id(a)", message =
                        message)
        return result.single()[0]
上述代码中,各函数的含义如下:
下面代码中选初始化 HelloWorldExample 类,然后调用并执行 print_greeting() 函数,最后调用 close 关闭资源。
if __name__ == "__main__":
    greeter = HelloWorldExample("bolt://localhost:7687", "neo4j", "111111")
    greeter.print_greeting("hello, world")
    greeter.close()
得到的返回值如下:

hello, world, from node 65

可以看到,返回结果中有 hello、world、from node 65,其中,hello 和 world 表示节点属性,65 表示节点 ID。

打开 Neo4j 的 Web 界面,输入以下内容:
MATCH (n:PythonGreeting) RETURN n,id(n) LIMIT 25
可以看到返回值如下:
│"n"                       │"id(n)"│
│{"message":"hello, world"}│65     │

相关文章