从 Python 使用 Neo4j

本指南概述了如何从 Python 连接到 Neo4j。

您应该熟悉 图数据库概念 和属性图模型。您应该已 创建 Neo4j AuraDB 云实例,或 在本地安装 Neo4j

Neo4j 和 Python

Neo4j 提供驱动程序,使您可以连接到数据库并开发创建、读取、更新和删除图中信息的应用程序。

在 GraphAcademy 学习

badge

使用 Python 构建 Neo4j 应用程序

在本免费课程中,我们将引导您完成将 Neo4j 集成到 Python 项目中的步骤。您将了解 Neo4j Python 驱动程序、会话和事务的工作原理,以及如何从现有应用程序查询 Neo4j。

Neo4j Python 驱动程序

Neo4j Python 驱动程序由 Neo4j **官方支持**,并使用二进制协议连接到数据库。它旨在保持简洁,同时符合 Python 的习惯用法。

在驱动程序的 2.0 版本中,已删除对 Python 2 的支持。
pip install neo4j
from neo4j import GraphDatabase

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.execute_write(self._create_and_return_greeting, message)
            print(greeting)

    @staticmethod
    def _create_and_return_greeting(tx, message):
        result = tx.run("CREATE (a:Greeting) "
                        "SET a.message = $message "
                        "RETURN a.message + ', from node ' + id(a)", message=message)
        return result.single()[0]


if __name__ == "__main__":
    greeter = HelloWorldExample("bolt://localhost:7687", "neo4j", "password")
    greeter.print_greeting("hello, world")
    greeter.close()

驱动程序配置

从 Neo4j 版本 **4.0** 开始,默认加密设置默认情况下为 **关闭**,Neo4j 将不再生成自签名证书。这适用于默认安装、通过 Neo4j 桌面和 Docker 映像进行的安装。您可以 通过检查neo4j.conf 中的dbms.connector.bolt.enabled 键来验证服务器的加密级别

表 1. 表格方案使用
证书类型 Neo4j 集群 Neo4j 独立服务器 直接连接到集群成员

未加密

neo4j

neo4j

bolt

使用完整证书加密

neo4j+s

neo4j+s

bolt+s

使用自签名证书加密

neo4j+ssc

neo4j+ssc

bolt+ssc

Neo4j AuraDB

neo4j+s

N/A

N/A

在进入生产环境时,请查看您的 SSL 框架设置。如有必要,您还可以 使用 Letsencrypt 为 Neo4j 生成证书

名称

版本

作者

neo4j-driver

5.22.0

Neo4j 团队

Neo4j 在线社区

文档

API

源代码

示例项目

Neo4j 示例项目是一个小型单页面 Web 应用程序,用于构建到 Neo4j 教程中的电影数据库。前端页面对所有驱动程序都相同:电影搜索、电影详细信息以及演员和电影的图可视化。每个后端实现都向您展示了如何从不同的语言和驱动程序连接到 Neo4j。

您可以 在这里了解更多关于我们跨多种不同语言驱动程序的小型一致示例项目的信息。您将找到所有驱动程序的实现,作为 独立的 GitHub 存储库,您可以直接克隆和部署这些存储库。