安装前提
python3.5以上
版本对照
Nebula Graph版本 | Nebula Python版本 |
---|---|
2.6.1 | 2.6.0 |
2.0.1 | 2.0.0 |
2.0.0 | 2.0.0 |
2.0.0-rc1 | 2.0.0rc1 |
pip安装
不同版本的自行替换版本号
pip install nebula2-python==2.6.0
连接到nebula graph服务
# 定义配置
config = Config()
config.max_connection_pool_size = 10
# 初始化连接池
connection_pool = ConnectionPool()
# 连接到graph服务地址端口
connection_pool.init([('127.0.0.1', 9669)], config)
# 从连接池中获取会话
client = connection_pool.get_session('root', 'nebula')
'''
中间可以进行一些查询等操作
'''
# 释放会话
client.release()
执行指令操作
使用execute方法执行指令,可用于nGQL、cypher等各种语句操作,如果按照属性进行查询,则需要建立并重建索引,在下面有自己写的一些脚本可以参考
# 使用图空间
client.execute('use basketballplayer;')
# 用cypher语句查询(查询之前要先建立相应TAG或属性的索引 )
res = client.execute('match (x:player) - [r] -(y) where x.name == "Yao Ming" return x, r, y;')
自己写的一些脚本
- 对所有tag及其所哟普属性创建并重建索引
make_all_indexes(client, 'basketballplayers')
def make_all_indexes(client, space, index_lenth=30):
'''
创建所有tag和edge的索引
'''
for aim in ['tags', 'edges']:
make_all_indexes(client, space, aim, index_lenth)
def make_indexes(client, space, aim='tags', index_lenth=30):
'''
次函数用于生成所有TAG或EDGE及其所有属性的索引
输入:
client: 连接到nebula的会话
space: 需要创建索引的图空间
aim: 需要创建的索引是tag还是edge
index_lenth: string类型的索引长度,默认30
返回值为一个字典(顺便获得的所有属性),键为每个TAG或EDGE名,值为每个TAG或EDGE中所有的属性名
'''
client.execute('use %s;'%space)
tags = client.execute('show %s;'%aim)
tags = [tags.row_values(i)[0] for i in range(tags.row_size())]
tags = [str(i).replace('"', '') for i in tags]
props_dic = {}
for tag in tags:
index_name = 'i_' + tag
client.execute('create %s index if not exists %s on %s();'%(aim[:-1], index_name, tag, aim[:-1], index_name))
client.execute('rebuild %s index %s;'%(aim[:-1], index_name))
properties = client.execute('show create %s %s;;'%(aim[:-1], tag))
if aim == 'tags':
properties = properties.column_values('Create Tag;')
elif aim == 'edges':
properties = properties.column_values('Create Edge;')
props_type = re.findall(r'[(]([^"]+)[)]', str(properties))[0]
props_type = props_type.split(',')
props_type = [i.replace('\n', '').replace('`', '')[1:] for i in props_type]
props_type = [i.split(' ') for i in props_type] # [['name', 'string', 'NULL'], ['age', 'int64', 'NULL']]
props_dic[tag] = [i[0] for i in props_type]
for prop in props_type:
index_name_prop = index_name + '_%s'%prop[0]
if 'string' in prop[1]:
client.execute('create %s index if not exists %s on %s(%s(%s));'%(aim[:-1], index_name_prop, prop[0], index_lenth))
else:
client.execute('create %s index if not exists %s on %s(%s);'%(aim[:-1], index_name_prop, prop[0]))
client.execute('rebuild %s index %s;'%(aim[:-1], index_name_prop))
return props_dic
- 处理从nebula中查询到的答案
client.execute('use basketballplayers;')
res = client.execute('match (x:player) - [r] - (y) where x.name == "Yao Ming" return x, r, y;')
handle_result(res)
def handle_result(res):
result = []
for lines in result:
result1 = []
for line in lines:
line = extract_info(line)
result1.append(line)
result.append(result1)
return result
def extract_info(line):
'''
用于将nebula查询到的结果(nebula独有的格式)中某行某列转换为字典,例:
1.vertex类型:
输入:("player133": player{age: 38, name: "Yao Ming"})
输出:{'type': 'vertex',
'player133':{'tag': 'player',
'properties':{'age': 38,
'name': 'Yao Ming'}}}
2.edge类型:
输入:("player133")-[:serve@0{end_year: 2011, start_year: 2002}]->("team202")
输出:{'type': 'edge',
'start': 'player133',
'end': 'team202',
'edge': {'edge_type': 'serve',
'properties': {'end_year': 2011,
'start_year: 2002'}}}
3.path类型:
输入:("player100" )-[:follow@0{}]->("player101" )-[:follow@0{}]->("player125" )-[:serve@0{}]->("team204" )
输出:{'type': 'path',
'vertex': {1: 'player100',
2: 'player101',
3: 'player125',
4:'team204'},
'edge': {1: {'edge_type': 'follow',
'properties': {}},
2: {'edge_type': 'follow',
'properties': {}},
3: {'edge_type': 'serve',
'properties': {}}}}
'''
dic = {}
# 判断数据类型是vertex还是edge
line = str(line)
if '->' in line:
line_type = 'edge' if line.count('->') == 1 else 'path'
else:
line_type = 'vertex'
dic['type'] = line_type
if line_type == 'vertex':
dic = extract_vertex(line, line_type)
if line_type == 'edge':
dic = extract_edge(line, line_type)
if line_type == 'path':
dic = extract_path(line, line_type)
return dic
def extract_edge(line, line_type):
'''
在extract_info中line类型是edge的情况下被调用处理line
'''
dic = {'type': line_type}
line = line.split('-')
line = [i.strip('>') for i in line]
dic['start'] = line[0][2: -2]
dic['end'] = line[2][2: -2]
edge_type = line[1][1:line[1].find('@')]
properties = line[1][line[1],find('{')+1: line[1].find('}')]
properties = handle_properties(properties)
dic['edge'] = {'edge_type': edge_type, 'properties': properties}
return dic
def extract_vertex(line, line_type):
dic = {'type': line_type}
vid = line[2: line.find(':') - 2]
tag = line[line.find(':') + 1: line.find('{')]
properties = line[line.find('{') + 1: line.find('}')]
properties = handle_properties(properties)
dic[vid] = {'tag': tag, 'properties': properties}
return dic
def extract_path(line, line_type):
dic = {'type': line_type}
line = line.split('-')
line = [i.strip('>') for i in line]
vertex = [i for i in line if '@' not in i]
edges = [i for i in line if '@' in i]
vertex = [re.findall(r'"(\w+)"', i)[0] for i in vertex]
dic['vertex'] = {i + 1: vertex[i] for i in range(len(vertex))}
edge_type = [i[i.find(':') + 1: i.find('@')] for i in edges]
properties = [i[i.find('{') + 1: i.find('}')] for i in edges]
properties = [handle_properties(properties) for i in properties]
dic['edge'] = {i + 1: {'edge_type': edge_type[i], 'properties': properties[i]} for i in range(len(properties))}
return dic
def handle_properties(properties):
'''
在extract_path/vertex/edge 中被调用,处理edge或vertex的属性
'''
properties = properties.split(',')
properties = [i.strip() for i in properties]
properties = ['"' + i[: i.find(':')] + '"' + i[i.find(':')] for i in properties]
properties = '{' + ','.join(properties) + '}'
properties = eval(properties)
return properties