Nebula Python 简单使用

官方文档

安装前提

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;')

自己写的一些脚本

  1. 对所有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
  1. 处理从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
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,386评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,142评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,704评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,702评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,716评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,573评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,314评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,230评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,680评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,873评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,991评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,706评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,329评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,910评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,038评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,158评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,941评论 2 355

推荐阅读更多精彩内容