zoukankan      html  css  js  c++  java
  • py2neo查询节点和关系

    记录一下使用py2neo进行查询,查询某演员出演的电影,返回三元组,可转为json用于前端显示,如下(以下在jupyter notebook中进行操作):

    一.查询数据

    from py2neo import Graph,Node,Relationship,NodeMatcher,RelationshipMatcher,Path
    
    class Movie():
        '''
        电影
        '''
        def __init__(self, id, name):
            self.id = id
            self.name = name
    
    class Person():
        ''''''
        def __init__(self, id, name):
            self.id = id
            self.name = name
    
    def initNeo4j():
        '''
        初始化neo4j
        :return:
        '''
        graph = Graph(
            "http://127.0.0.1:7474",
            username="neo4j",
            password="123"
        )
        return graph
    
    def get_person_actorof_movie(graph, p_id) -> list:
        '''
        查找演员参演的电影,并返回三元组
        :param graph:
        :param p_id:
        :return:
        '''
        data = graph.run("match path=(m:Movie)-[:ACTOR_OF]->(p:Person) "
                         "where p.id = $id return relationships(path) as relationships",
                         id = p_id)
    
        movieDict = {} #电影
        personDict = {} #演员
        person_actorof_movie = {} # 三元组
        while data.forward():
            cursor = data.current
            for relation in cursor['relationships']:
                source_node = relation.start_node
                target_node = relation.end_node
                source_node_id = source_node['id']
                target_node_id = target_node['id']
                relation_type = list(relation.types())[0]
                source_node_label = str(source_node.labels).strip(":")
                target_node_label = str(target_node.labels).strip(":")
                source_node_name = source_node['title']
                target_node_name = target_node['name']
                # 存储三元组关系
                if source_node_id in person_actorof_movie.keys():
                    target_dict = person_actorof_movie.get(source_node_id)
                    target_dict.setdefault(target_node_id,relation_type)
                else:
                    target_dict = {target_node_id:relation_type}
                    person_actorof_movie[source_node_id] = target_dict
                # 存储节点
                if ("Movie" == source_node_label) and (source_node_id not in movieDict.keys()):
                    movie = Movie(source_node_id, source_node_name)
                    movieDict[source_node_id] = movie
                if ("Person" == target_node_label) and (target_node_id not in personDict.keys()):
                    person = Person(target_node_id, target_node_name)
                    personDict[target_node_id] = person
               
        json_list = []
        for source_key, value in person_actorof_movie.items():
            for target_key, rel_type in value.items():
                person_movie_dict = {}
                person_movie_dict['source'] = movieDict.get(source_key).name
                person_movie_dict['rel_type'] = rel_type
                person_movie_dict['target'] = personDict.get(target_key).name
                json_list.append(person_movie_dict)
                    
        print(len(json_list))
        for i in range(len(json_list)):
            print("{}-[{}]->{}".format(json_list[i]['source'], json_list[i]['rel_type'], json_list[i]['target']))
    
        return json_list
    
    if __name__ == '__main__':
        graph = initNeo4j()
        json_list = get_person_actorof_movie(graph, 'e425fdb6bade4fc19d09754d1ae4670f')

    二.展示出来

    from pyecharts import options as opts
    from pyecharts.charts import Graph
    
    #明星主演的电影
    movie_person_dict = set()
    nodes = []
    links = []
    for i in range(len(json_list)):
        if json_list[i]['source'] not in movie_person_dict:
            movie_person_dict.add(json_list[i]['source'])
            nodes.append({'name':json_list[i]['source'], "symbolSize": 10, 'draggable': 'true'})
        if json_list[i]['target'] not in movie_person_dict:
            movie_person_dict.add(json_list[i]['target'])
            nodes.append({'name':json_list[i]['target'], "symbolSize": 10, 'draggable': 'true'})
        links.append({'source':json_list[i]['source'], 'target':json_list[i]['target']})
        
    graph = Graph(init_opts=opts.InitOpts(width='1000px', height='800px'))
    graph.add("", nodes, links, repulsion=8000, edge_symbol=['','arrow'])
    graph.set_global_opts(title_opts=opts.TitleOpts(title="明星主演的电影"))
    
    graph.render_notebook()

    三.如下图

  • 相关阅读:
    Qt画笔实现折线图
    Qt动态布局
    ffmpeg录制流媒体,正常方式停止录制
    解决libvlc_media_player_stop时死锁的方法
    Ubuntu 16 修改时区!
    qt窗口最小化之后无法打开
    Qt 之 去除窗口部件被选中后的焦点虚线框
    WINDOWS中, 如何查看一个运行中的程序是64位还是32位的
    DHTMLX学习总结
    mui plus.uploader.createUpload 上传文件服务端获取文件名中文乱码问题
  • 原文地址:https://www.cnblogs.com/little-horse/p/13752356.html
Copyright © 2011-2022 走看看