使用 Neo4j 和 Python 构建应用程序

Neo4j Python 驱动程序是通过 Python 应用程序与 Neo4j 实例进行交互的官方库。

Neo4j 的核心是 Cypher,它是与 Neo4j 数据库进行交互的查询语言。虽然本指南不要求您是经验丰富的 Cypher 查询员,但如果您已经了解一些 Cypher,那么专注于 Python 特定的部分会更容易。出于这个原因,虽然本指南也会在过程中提供 Cypher 的入门介绍,但如果您是第一次接触,请查看 入门 → Cypher 以获取有关图数据库建模和查询的更详细的介绍。然后,您可以在遵循本指南开发 Python 应用程序时应用这些知识。

安装

使用 pip 安装 Neo4j Python 驱动程序

pip install neo4j

连接到数据库

通过创建 Driver 对象并提供 URL 和身份验证令牌来连接到数据库。一旦您拥有 Driver 实例,请使用 .verify_connectivity() 方法确保可以建立工作连接。

from neo4j import GraphDatabase

# URI examples: "neo4j://localhost", "neo4j+s://xxx.databases.neo4j.io"
URI = "<URI for Neo4j database>"
AUTH = ("<Username>", "<Password>")

with GraphDatabase.driver(URI, auth=AUTH) as driver:
    driver.verify_connectivity()

查询数据库

使用 Driver.execute_query() 方法执行 Cypher 语句。不要硬编码或连接参数:使用占位符并将参数指定为关键字参数。

# Get the name of all 42 year-olds
records, summary, keys = driver.execute_query(
    "MATCH (p:Person {age: $age}) RETURN p.name AS name",
    age=42,
    database_="neo4j",
)

# Loop through results and do something with them
for person in records:
    print(person)

# Summary information
print("The query `{query}` returned {records_count} records in {time} ms.".format(
    query=summary.query, records_count=len(records),
    time=summary.result_available_after,
))

运行自己的事务

对于更高级的用例,您可以运行 事务。使用 Session.execute_read()Session.execute_write() 方法运行托管事务。

包含多个查询、客户端逻辑和潜在回滚的事务
from neo4j import GraphDatabase


URI = "<URI for Neo4j database>"
AUTH = ("<Username>", "<Password>")
employee_threshold=10


def main():
    with GraphDatabase.driver(URI, auth=AUTH) as driver:
        with driver.session(database="neo4j") as session:
            for i in range(100):
                name = f"Thor{i}"
                org_id = session.execute_write(employ_person_tx, name)
                print(f"User {name} added to organization {org_id}")


def employ_person_tx(tx, name):
    # Create new Person node with given name, if not exists already
    result = tx.run("""
        MERGE (p:Person {name: $name})
        RETURN p.name AS name
        """, name=name
    )

    # Obtain most recent organization ID and the number of people linked to it
    result = tx.run("""
        MATCH (o:Organization)
        RETURN o.id AS id, COUNT{(p:Person)-[r:WORKS_FOR]->(o)} AS employees_n
        ORDER BY o.created_date DESC
        LIMIT 1
    """)
    org = result.single()

    if org is not None and org["employees_n"] == 0:
        raise Exception("Most recent organization is empty.")
        # Transaction will roll back -> not even Person is created!

    # If org does not have too many employees, add this Person to that
    if org is not None and org.get("employees_n") < employee_threshold:
        result = tx.run("""
            MATCH (o:Organization {id: $org_id})
            MATCH (p:Person {name: $name})
            MERGE (p)-[r:WORKS_FOR]->(o)
            RETURN $org_id AS id
            """, org_id=org["id"], name=name
        )

    # Otherwise, create a new Organization and link Person to it
    else:
        result = tx.run("""
            MATCH (p:Person {name: $name})
            CREATE (o:Organization {id: randomuuid(), created_date: datetime()})
            MERGE (p)-[r:WORKS_FOR]->(o)
            RETURN o.id AS id
            """, name=name
        )

    # Return the Organization ID to which the new Person ends up in
    return result.single()["id"]


if __name__ == "__main__":
    main()

关闭连接和会话

除非您使用 with 语句创建它们,否则请对所有 DriverSession 实例调用 .close() 方法以释放它们持有的任何资源。

from neo4j import GraphDatabase


driver = GraphDatabase.driver(URI, auth=AUTH)
session = driver.session(database="neo4j")

# session/driver usage

session.close()
driver.close()

API 文档

有关驱动程序功能的深入信息,请查看 API 文档

词汇表

LTS

长期支持 (LTS) 版本是保证支持数年时间的版本。Neo4j 4.4 是 LTS 版本,Neo4j 5 也将有 LTS 版本。

Aura

Aura 是 Neo4j 的完全托管云服务。它提供免费和付费计划。

Cypher

Cypher 是 Neo4j 的图查询语言,它允许您从数据库中检索数据。它类似于 SQL,但适用于图。

APOC

Cypher 上的超赞过程 (APOC) 是一个包含许多函数的库,这些函数无法轻松地在 Cypher 本身中表达。

Bolt

Bolt 是 Neo4j 实例和驱动程序之间交互使用的协议。默认情况下,它在端口 7687 上监听。

ACID

原子性、一致性、隔离性、持久性 (ACID) 是保证数据库事务可靠处理的属性。符合 ACID 标准的 DBMS 确保数据库中的数据即使在发生故障的情况下也能保持准确性和一致性。

最终一致性

如果数据库保证所有集群成员将在某个时间点存储数据的最新版本,那么它就是最终一致的。

因果一致性

如果每个集群成员以相同的顺序看到读写查询,则数据库就是因果一致的。这比最终一致性更强大。

NULL

空标记不是类型,而是值不存在的占位符。有关更多信息,请参见 Cypher → 使用 null

事务

事务是工作单元,它要么完全提交,要么在发生故障时回滚。例如银行转账:它涉及多个步骤,但它们必须全部成功或被还原,以避免从一个帐户中扣除资金但没有添加到另一个帐户中。

背压

背压是抵制数据流动的力量。它确保客户端不会被超出其处理能力的数据淹没。

事务函数

事务函数是 execute_readexecute_write 调用执行的回调。如果服务器发生故障,驱动程序会自动重新执行回调。

Driver

Driver 对象保存与 Neo4j 数据库建立连接所需的详细信息。