入门
Python 客户端的设计理念是模拟 GDS Cypher API 在 Python 代码中的表现。Python 客户端会将用户编写的 Python 代码转换为相应的 Cypher 查询,然后使用 Neo4j Python 驱动连接在 Neo4j 服务器上运行该查询。
Python 客户端力求尽可能地“Pythonic”,以最大限度地便利习惯和精通 Python 环境的用户。因此,尽可能使用标准的 Python 和 Pandas 类型。然而,为了与 Cypher 表面保持一致,调用对应于 Cypher 过程的方法的通用返回值将是表格形式(在 Python 中是 Pandas DataFrame
)。更多信息请参阅Cypher 与 Python 之间的映射。
Python 客户端的根组件是 GraphDataScience
对象。一旦实例化,它就成为与 GDS 库交互的入口点。这包括在 GDS 中投影图、运行算法以及定义和使用机器学习管道。按照惯例,我们建议始终将实例化后的 GraphDataScience
对象命名为 gds
,因为这样使用它将最类似于直接使用 Cypher API。
1. 导入和设置
实例化 GraphDataScience
对象的最简单方法是使用 Neo4j 服务器 URI 和相应的凭据
from graphdatascience import GraphDataScience
# Use Neo4j URI and credentials according to your setup
# NEO4J_URI could look similar to "bolt://my-server.neo4j.io:7687"
gds = GraphDataScience(NEO4J_URI, auth=(NEO4J_USER, NEO4J_PASSWORD))
# Check the installed GDS version on the server
print(gds.server_version())
assert gds.server_version()
"2.1.9"
请注意,GraphDataScience
对象在构建时需要与 Neo4j 数据库通信,并且默认使用“neo4j”数据库。如果不存在这样的数据库,您将需要使用 database
关键字参数提供一个有效的数据库。
1.1. Aura 图分析无服务器
GDS Python 客户端对 Aura 图分析无服务器产品提供专门支持。
此示例展示了如何使用 Aura API 密钥对和 AuraDB 连接信息实例化 GraphDataScience
对象。
from graphdatascience.session import DbmsConnectionInfo, GdsSessions, AuraAPICredentials, SessionMemory
sessions = GdsSessions(api_credentials=AuraAPICredentials("<clientId>", "<clientSecret>"))
gds = sessions.get_or_create(
session_name="my-session",
memory=SessionMemory.m_4GB,
db_connection=DbmsConnectionInfo("neo4j+s://mydbid.databases.neo4j.io", "neo4j", "<password>"),
)
1.2. AuraDS
如果您将客户端连接到 AuraDS 实例,则可以自动应用推荐的非默认 Python 驱动程序配置设置。为此,请将构造函数参数 aura_ds
设置为 True
。
from graphdatascience import GraphDataScience
# Configures the driver with AuraDS-recommended settings
gds = GraphDataScience(
"neo4j+s://my-aura-ds.databases.neo4j.io:7687",
auth=("neo4j", "my-password"),
aura_ds=True
)
1.3. 从 Neo4j 驱动程序实例化
对于某些用例,需要直接访问和控制 Neo4j 驱动程序。例如,如果需要以某种方式配置所使用的 Neo4j 驱动程序。在这种情况下,可以使用 GraphDataScience.from_neo4j_driver
方法实例化 GraphDataScience
对象。它接受与常规 GraphDataScience
构造函数相同的参数,但 aura_ds
关键字参数除外,因为该参数仅在内部实例化底层 Neo4j 驱动程序时才相关。
1.5. 指定目标数据库
如果我们不想使用 DBMS 的默认数据库,我们可以为 GraphDataScience
构造函数提供关键字参数 database
。
gds = GraphDataScience(NEO4J_URI, auth=(NEO4J_USER, NEO4J_PASSWORD), database="my-db")
或者我们可以在稍后更改我们正在连接的数据库。
gds.set_database("my-db")
1.6. 配置 Apache Arrow 参数
如果 Apache Arrow 在服务器上可用,我们可以为 GraphDataScience
构造函数提供几个关键字参数来配置连接
-
arrow_disable_server_verification
:一个标志,指示如果 flight 客户端使用 TLS 连接,则跳过服务器验证。如果启用此选项,则所有其他 TLS 设置都将被覆盖。 -
arrow_tls_root_certs
:用于连接到 Apache Arrow Flight 服务器的 PEM 编码证书。
gds = GraphDataScience(
NEO4J_URI,
auth=(NEO4J_USER, NEO4J_PASSWORD),
arrow=True,
arrow_disable_server_verification=False,
arrow_tls_root_certs=CERT
)
2. 最小示例
在下面的示例中,我们演示了 Python 客户端如何运行 Cypher 查询、将图投影到 GDS 中、运行算法并通过客户端图对象检查结果。我们假设我们已经创建了一个存储在变量 gds
中的 GraphDataScience
对象。
# Create a minimal example graph
gds.run_cypher(
"""
CREATE
(m: City {name: "Malmö"}),
(l: City {name: "London"}),
(s: City {name: "San Mateo"}),
(m)-[:FLY_TO]->(l),
(l)-[:FLY_TO]->(m),
(l)-[:FLY_TO]->(s),
(s)-[:FLY_TO]->(l)
"""
)
# Project the graph into the GDS Graph Catalog
# We call the object representing the projected graph `G_office`
G_office, project_result = gds.graph.project("neo4j-offices", "City", "FLY_TO")
# Run the mutate mode of the PageRank algorithm
mutate_result = gds.pageRank.mutate(G_office, tolerance=0.5, mutateProperty="rank")
# We can inspect the node properties of our projected graph directly
# via the graph object and see that indeed the new property exists
assert G_office.node_properties("City") == ["rank"]
您还可以使用库中包含的其中一个数据集来开始。有关此内容的更多信息,请参见数据集一章。 |
客户端库的设计使得大多数方法在您键入时通过字符串构建方案和重载魔术 |
3. 运行 Cypher
正如我们在上面的示例中所看到的,GraphDataScience
对象有一个 run_cypher
方法,用于方便地运行 Cypher 查询。此方法接受查询字符串 query: str
、可选的 Cypher 参数字典 params: Optional[Dict[str, Any]]
以及可选的字符串 database: Optional[str]
作为参数,以覆盖要连接的数据库。它以 Pandas DataFrame
的格式返回查询结果。
4. 关闭开放连接
与 Neo4j Python 驱动程序支持关闭与 DBMS 的所有开放连接类似,您也可以在 GraphDataScience
对象上调用 close
来达到相同的效果。
# Close any open connections in the underlying Neo4j driver's connection pool
gds.close()
当 GraphDataScience
对象被删除时,close
也会自动调用。
5. Cypher 与 Python 之间的映射
Cypher API 如何映射到 Python 客户端 API 存在一些一般原则
-
对应于 Cypher 过程(文档中以
CALL
开头)的方法调用返回:-
一个表,以 Pandas
DataFrame
形式,如果过程返回多行(例如,流模式算法调用)。 -
一行,以 Pandas
Series
形式,如果过程精确返回一行(例如,统计模式算法调用)。
一些值得注意的例外是:
-
-
对应于 Cypher 函数(文档中以
RETURN
开头)的方法调用将简单地返回函数的值。 -
Python 客户端还包含用于检查 GDS 图目录中的图的特定功能,它使用客户端图对象。同样,可以使用客户端模型对象检查 GDS 模型目录中的模型。
-
GDS 的 Cypher 函数和过程通常将图和/或模型的引用作为字符串输入,而在 Python 客户端 API 中则将图对象和/或模型对象作为输入。