NebulaGraph v3的Python客户端
项目描述
NebulaGraph Python客户端
入门指南
注意:请确保您使用的是正确的版本,有关Python客户端版本如何对应于NebulaGraph数据库版本的详细信息,请参阅兼容性矩阵。
访问NebulaGraph
-
入门笔记本 - 一个Jupyter笔记本,用于入门NebulaGraph Python客户端,包含最新功能和示例。
-
如果您是首次尝试使用Python客户端,请参阅快速示例:使用Graph客户端连接到GraphD。
-
如果您构建的是针对一个图空间的图应用程序(Web服务),请使用会话池的单例,请参阅使用会话池:指南。
-
如果您正在构建图分析工具(扫描而非查询),您可能希望使用存储客户端来扫描顶点和边,请参阅快速示例:使用存储客户端扫描顶点和边。
-
有关参数化查询,请参阅示例:服务器端评估参数。
处理查询结果
-
如何将查询结果形成 Pandas DataFrame,请参阅示例:将查询结果提取到 Pandas DataFrame 中。
-
关于如何渲染/可视化查询结果,请参阅示例:从查询结果中提取边和顶点列表,它演示了如何通过利用
ResultSet.dict_for_vis()
方法从任何查询结果中提取边和顶点列表。 -
如何获取具有原始类型的 dict/JSON 结构的行,请参阅示例:检索原始类型的结果。
Jupyter Notebook 集成
如果您准备在 Jupyter Notebook 中访问 NebulaGraph,您可能希望使用 NebulaGraph Jupyter 扩展,它提供了一种更互动的方式来访问 NebulaGraph。有关 Google Colab 的信息,请参阅NebulaGraph on Google Colab。
获取 nebula3-python
方法 1:通过 pip 安装
# for v3.x
pip install nebula3-python==$version
# for v2.x
pip install nebula2-python==$version
方法 2:通过源码安装
点击展开
- 从 GitHub 克隆
git clone https://github.com/vesoft-inc/nebula-python.git
cd nebula-python
- 从源码安装
对于 python 版本 >= 3.7.0
pip install .
对于 python 版本 >= 3.6.2,< 3.7.0
python3 setup.py install
快速示例:使用 Graph Client 连接到 GraphD
from nebula3.gclient.net import ConnectionPool
from nebula3.Config import Config
# define a config
config = Config()
config.max_connection_pool_size = 10
# init connection pool
connection_pool = ConnectionPool()
# if the given servers are ok, return true, else return false
ok = connection_pool.init([('127.0.0.1', 9669)], config)
# option 1 control the connection release yourself
# get session from the pool
session = connection_pool.get_session('root', 'nebula')
# select space
session.execute('USE basketballplayer')
# show tags
result = session.execute('SHOW TAGS')
print(result)
# release session
session.release()
# option 2 with session_context, session will be released automatically
with connection_pool.session_context('root', 'nebula') as session:
session.execute('USE basketballplayer')
result = session.execute('SHOW TAGS')
print(result)
# close the pool
connection_pool.close()
使用会话池:指南
会话池是由池管理的会话集合。它旨在提高会话管理效率,并减少会话创建和销毁的开销。
会话池有以下假设
- 在会话池初始化之前,数据库中必须已经存在一个空间。
- 每个会话池都与一个用户和一个空间相关联,以确保用户访问控制的一致性。例如,一个用户可能在不同的空间中拥有不同的访问权限。要执行多个空间的查询,请考虑使用多个会话池。
- 每次调用
sessionPool.execute()
时,会话都会在会话池配置中指定的空间内执行查询。 - 必须避免通过会话池执行会更改密码或删除用户的命令。
有关更多详细信息,请参阅SessionPoolExample.py。
示例:服务器端评估参数
要启用查询的参数化,请参阅以下示例
注意:并非所有查询的标记都可以参数化。您可以通过 iPython 或 Nebula-Console 的交互方式快速验证它。
params = {
"p1": 3,
"p2": True,
"p3": "Bob",
"ids": ["player100", "player101"], # second query
}
resp = client.execute_py(
"RETURN abs($p1)+3 AS col1, (toBoolean($p2) and false) AS col2, toLower($p3)+1 AS col3",
params,
)
resp = client.execute_py(
"MATCH (v) WHERE id(v) in $ids RETURN id(v) AS vertex_id",
params,
)
有关更多信息,请参阅Params.py。
示例:从查询结果中提取边和顶点列表
为了图形可视化的目的,以下代码片段演示了如何通过利用 ResultSet.dict_for_vis()
方法轻松地从任何查询结果中提取边和顶点列表。
result = session.execute(
'GET SUBGRAPH WITH PROP 2 STEPS FROM "player101" YIELD VERTICES AS nodes, EDGES AS relationships;')
data_for_vis = result.dict_for_vis()
然后,我们可以将 data_for_vis
传递给一个前端可视化库,如 vis.js
、d3.js
或 Apache ECharts。有关 Apache ECharts 的示例,请参阅exapmple/apache_echarts.html。
带有 dict_for_vis()
的 dict/JSON 结构如下
点击展开
{
'nodes': [
{
'id': 'player100',
'labels': ['player'],
'props': {
'name': 'Tim Duncan',
'age': '42',
'id': 'player100'
}
},
{
'id': 'player101',
'labels': ['player'],
'props': {
'age': '36',
'name': 'Tony Parker',
'id': 'player101'
}
}
],
'edges': [
{
'src': 'player100',
'dst': 'player101',
'name': 'follow',
'props': {
'degree': '95'
}
}
],
'nodes_dict': {
'player100': {
'id': 'player100',
'labels': ['player'],
'props': {
'name': 'Tim Duncan',
'age': '42',
'id': 'player100'
}
},
'player101': {
'id': 'player101',
'labels': ['player'],
'props': {
'age': '36',
'name': 'Tony Parker',
'id': 'player101'
}
}
},
'edges_dict': {
('player100', 'player101', 0, 'follow'): {
'src': 'player100',
'dst': 'player101',
'name': 'follow',
'props': {
'degree': '95'
}
}
},
'nodes_count': 2,
'edges_count': 1
}
示例:检索原始类型的结果
执行的结果被类型化为 ResultSet
,您可以使用 dir()
来检查其结构。
对于 ResultSet
中的每个数据单元格,您可以使用 .cast()
来检索原始包装数据(带糖)如 Vertex(节点)、Edge(关系)、Path、Value(Int、Float 等)。或者,您可以使用 .cast_primitive()
来根据您的需要获得原始类型(如 dict、int 或 float)的值。
有关更多详细信息,请参阅FromResp.py。
此外,ResultSet.as_primitive()
提供了一个方便的方法,将结果集转换为包含每行原始值的字典列表(类似于JSONL格式)。
result = session.execute('<your query>')
result_dict = result.as_primitive()
print(result_dict)
示例:将查询结果提取到Pandas DataFrame中
对于
nebula3-python>=3.6.0
假设您已安装pandas,可以使用以下代码将查询结果提取到pandas DataFrame中
pip3 install pandas
result = session.execute('<your query>')
df = result.as_data_frame()
对于`nebula3-python<3.6.0`
from nebula3.gclient.net import ConnectionPool
from nebula3.Config import Config
import pandas as pd
from typing import Dict
from nebula3.data.ResultSet import ResultSet
def result_to_df(result: ResultSet) -> pd.DataFrame:
"""
build list for each column, and transform to dataframe
"""
assert result.is_succeeded()
columns = result.keys()
d: Dict[str, list] = {}
for col_num in range(result.col_size()):
col_name = columns[col_num]
col_list = result.column_values(col_name)
d[col_name] = [x.cast() for x in col_list]
return pd.DataFrame(d)
# define a config
config = Config()
# init connection pool
connection_pool = ConnectionPool()
# if the given servers are ok, return true, else return false
ok = connection_pool.init([('127.0.0.1', 9669)], config)
# option 2 with session_context, session will be released automatically
with connection_pool.session_context('root', 'nebula') as session:
session.execute('USE <your graph space>')
result = session.execute('<your query>')
df = result_to_df(result)
print(df)
# close the pool
connection_pool.close()
快速示例:使用存储客户端扫描顶点和边
存储客户端允许您从存储服务而不是图服务(使用nGQL/Cypher)扫描顶点和边。当您需要扫描大量数据时,这非常有用。
点击展开
您应该确保扫描客户端可以连接到从SHOW HOSTS
中看到的存储地址
from nebula3.mclient import MetaCache, HostAddr
from nebula3.sclient.GraphStorageClient import GraphStorageClient
# the metad servers's address
meta_cache = MetaCache([('172.28.1.1', 9559),
('172.28.1.2', 9559),
('172.28.1.3', 9559)],
50000)
# option 1 metad usually discover the storage address automatically
graph_storage_client = GraphStorageClient(meta_cache)
# option 2 manually specify the storage address
storage_addrs = [HostAddr(host='172.28.1.4', port=9779),
HostAddr(host='172.28.1.5', port=9779),
HostAddr(host='172.28.1.6', port=9779)]
graph_storage_client = GraphStorageClient(meta_cache, storage_addrs)
resp = graph_storage_client.scan_vertex(
space_name='ScanSpace',
tag_name='person')
while resp.has_next():
result = resp.next()
for vertex_data in result:
print(vertex_data)
resp = graph_storage_client.scan_edge(
space_name='ScanSpace',
edge_name='friend')
while resp.has_next():
result = resp.next()
for edge_data in result:
print(edge_data)
有关更多详细信息,请参阅ScanVertexEdgeExample.py
兼容性矩阵
Nebula-Python版本 | 兼容的NebulaGraph版本 | 备注 |
---|---|---|
3.8.2 | 3.x | 强烈推荐。NebulaGraph 3.x系列的最新版本。 |
master | master | 包含最近的变化。尚未发布。 |
3.0.0 ~ 3.5.1 | 3.x | 与NebulaGraph 3.x系列中的任何已发布版本兼容。 |
2.6.0 | 2.6.0, 2.6.1 | |
2.5.0 | 2.5.0 | |
2.0.0 | 2.0.0, 2.0.1 | |
1.0 | 1.x |
目录结构概述
.
└──nebula-python
│
├── nebula3 // client source code
│ ├── fbthrift // the RPC code generated from thrift protocol
│ ├── common
│ ├── data
│ ├── graph
│ ├── meta
│ ├── net // the net code for graph client
│ ├── storage // the storage client code
│ ├── Config.py // the pool config
│ └── Exception.py // the exceptions
│
├── examples
│ ├── FormatResp.py // the format response example
│ ├── SessionPoolExample.py // the session pool example
│ ├── GraphClientMultiThreadExample.py // the multi thread example
│ ├── GraphClientSimpleExample.py // the simple example
│ └── ScanVertexEdgeExample.py // the scan vertex and edge example(storage client)
│
├── tests // the test code
│
├── setup.py // used to install or package
│
└── README.md // the introduction of nebula3-python
为Nebula-Python做出贡献
点击展开
要做出贡献,首先从仓库中分叉。接下来,将您的分叉仓库克隆到本地机器。请记住,在以下URL中用您的实际GitHub用户名替换{username}
git clone https://github.com/{username}/nebula-python.git
cd nebula-python
对于包管理,我们使用PDM。请先安装它
pipx install pdm
有关替代安装方法,请访问PDM文档
安装包及其所有开发依赖项
pdm install
确保Nebula服务器正在运行,然后使用pytest运行测试
pdm test
使用默认格式化器black
请在提交之前运行pdm fmt
来格式化Python代码。
有关向Nebula项目贡献的一般过程,请参阅如何贡献
项目详情
下载文件
为您的平台下载文件。如果您不确定选择哪个,请了解更多关于安装包的信息。