运行环境


  • windows11
  • JDK 8
  • anaconda3
  • python 3.9
  • Neo4j 3.5.32
  • python jupyter库
  • py2neo
  • Visual Studio Code 2022

项目地址:
Gitee : https://gitee.com/ccuni/py2neo-neo4j-actual-combat

GitHub:https://github.com/unirithe/py2neo-neo4j-actual-combat

一、数据集说明

数据集来自 IMDB 影视网的电影、演员数据,数据并不全,仅供学习参考。
数据集参考上方的 Gitee 或 GitHub地址

  • movie_act.csv 演员id到电影id的映射信息

  • movie_actor.csv 5334个演员的信息,名称和头像

  • movie_moive.csv 2926部电影的详情信息

  • movie_popularity.csv 保留着62部受欢迎的电影信息

  • user_user.csv 不知道有啥用的id信息

二、数据预处理

这里将原先的csv数据转为 pandas的DataFrame后再转化成字典,从而能构建Node对象,插入到Neo4j中

2.1 选择受欢迎的电影

list_mid = df['popularity']['movieid_id']# 查找受欢迎的电影信息
# Find the movies which is popularity
df_popularity_movie = df['movie'][df['movie']['movieid'].isin(list_mid)]
df_popularity_movie

# 将DataFrame格式转化为dict,到时候方便插入Neo4j
# make DataFrame to Dict, in order to insert neo4j
dict_movie = {}for i in range(len(df_popularity_movie)):row = df_popularity_movie.iloc[i]dict_movie.update({row['movieid'] : row.to_dict()})
print('rows: ' , len(dict_movie))

2.2 查找每部受欢迎电影的所有演员

dict_actor_movie = {}
for mid in df_popularity_movie['movieid']:flag = df['actor_movie']['movieid_id'].eq(mid)actors = df['actor_movie'][flag]['actorid_id'].to_list()dict_actor_movie.update({mid : actors})
print('rows: ' , len(dict_actor_movie))

2.3 查找热门电影里每个演员的信息

dict_actor = {}
actors = set()
for ac in dict_actor_movie.values():for actor in ac:actors.add(actor)
for aid in actors:flag = (df['actor']['actorid'] == aid)row = df['actor'][flag].iloc[0]dict_actor.update({aid: row.to_dict()})
print('rows: ' , len(dict_actor_movie))

三、Py2Neo 操作

3.1 连接 Neo4j

from py2neo import Graph
url = "http://localhost:7474"
username = "neo4j"
password = "123456"
graph = Graph(url, auth=(username, password))
print("neo4j info: {}".format(str(graph)))

输出结果:neo4j info: Graph(‘http://localhost:7474’)

3.2 插入电影和演员节点

from py2neo import Graph, Node, Subgraph
import time
s_time = time.time()node_list = []graph.delete_all()for mid, movie in dict_movie.items():node_list.append(Node("movie", **movie))
for aid, actor in dict_actor.items():node_list.append(Node("actor", **actor))
graph.create(subgraph=Subgraph(node_list))# 查看一个节点
print(node_list[0])

输出当前Neo4j 电影和演员节点的个数

print('movie: ', graph.nodes.match("movie").count())
print('actor: ', graph.nodes.match('actor').count())

输出结果:
movie: 62
actor: 240

3.3 建立电影和演员之间的联系

from py2neo import NodeMatcher, Relationship
node_matcher = NodeMatcher(graph)
list_rel = []
for mid, actors in dict_actor_movie.items(): node_movie = node_matcher.match("movie", movieid=mid).first()if node_movie != None:for actor in actors:node_actor = node_matcher.match("actor", actorid=actor).first()if node_actor != None:list_rel.append(Relationship(node_actor, "acted", node_movie, name='acted'))# 批量建立
# batch build
once = 50
maxi = len(list_rel)
for i in range(0, maxi, once):subgraph = Subgraph(relationships=list_rel[i:i+once])graph.separate(subgraph)graph.create(subgraph)print(f'[INFO] >> created {len(subgraph)} relations')

输出结果:

登录 Neo4j 的web页面查询插入的结果:http://localhost:7474

四、基于Neo4j的数据分析

4.1 查找电影的所有关系

from py2neo import RelationshipMatcher
rmatcher = RelationshipMatcher(graph)i = 0
for node_movie in graph.nodes.match('movie').all():print(i, '-' * 10 , node_movie['name'] + '-' *10)for rel in graph.match([None, node_movie]).all():print('--', rel)i += 1print('\n\n')

部分输出结果:(共有62部受欢迎的电影)

4.2 查找根据演员数和评分排序的Top10电影

nodes_movie = graph.nodes.match('movie').all()#关于已出现的演员人数的前十名
# Top10 about the number of appeared actor  # 如果演员人数一致就根据评分判断,选择评分高的电影
# If the number of actors is the same,
#   judge according to the score and choose the film with high rate.
rm = RelationshipMatcher(graph)
'''Top10
'''
dict_movie_top10 = {}
for node_movie in nodes_movie:list_actors = rm.match([None, node_movie], r_type='acted').all()count = len(list_actors)dict_movie_top10.update({node_movie: {'count':int(count), 'actors':list_actors}})list_movie_top10 = sorted(dict_movie_top10.items(), key = lambda k : (k[1]['count'], float(k[0]['rate'])), reverse=True)[:10]# list_movie_top10 is a list([turple(Node, dict)])
print('------------------ Top10 ------------------')
for node_movie, dict_count in list_movie_top10:print(dict_count['count'], node_movie['rate'], node_movie['name'])

输出结果:

翻译过后:
Translate to chinese

排名 评分 电影名称
1 9.1 《肖申克的救赎》
2 9.1 《Dekalog》
3 9.0 《黑暗骑士》
4 9.0 《教父:第二部》
5 8.9 《低俗小说》
6 8.8 《费城总是阳光明媚》
7 8.8 《星球大战5:帝国反击战》
8 8.8 《搏击俱乐部》
9 8.7 《指环王:双塔奇兵》
10 8.6 《星球大战》

4.3 保存 Top10数据到 Neo4j

graph.delete(Subgraph(graph.nodes.match('actor_top10').all()))
graph.delete(Subgraph(graph.nodes.match('movie_top10').all()))
graph.delete(Subgraph(RelationshipMatcher(graph).match(name='acted_top10')))rel_top10 = []
nodeMatcher = NodeMatcher(graph)
for node_movie, dict_count in list_movie_top10:for actor_rel in dict_count['actors']:actor = Node('actor_top10', **dict(actor_rel.start_node))movie = Node('movie_top10', **dict(node_movie))actor_find = nodeMatcher.match('actor_top10', name=actor['name']).first()movie_find = nodeMatcher.match('movie_top10', name=movie['name']).first()if actor_find != None: ator = actor_find if movie_find != None: movie = movie_findrel_top10.append(Relationship(actor, "acted", movie, name='acted_top10'))sub_rels=Subgraph(relationships=rel_top10)graph.separate(subgraph=sub_rels)graph.create(subgraph = sub_rels)print('The number of actor_top10 node: ',graph.nodes.match('actor_top10').count())
print('The number of moive_top10 node: ', graph.nodes.match('movie_top10').count())
print('The number of relationsip: ', graph.relationships.match(name='acted_top10').count())

输出结果:

从 web中查询的结果如下:

五、总结

通过本次的尝试,我们使用py2neo进行了Neo4j的增删改查,熟悉使用 Node、Relationship、Graph,另外,还有大量的 pandas相关的操作。最终分析了影视电影和演员之间的关系,当然还有更多指标可以分析,比如:出现次数最多的演员以及电影、同步出现率最高的电影等等。

py2neo实现neo4j的增删改查还是挺轻松的。

Neo4j 实战篇(一)基于Py2Neo构建电影知识图谱相关推荐

  1. Python+Neo4j构建时光网TOP100电影知识图谱

    Python+Neo4j构建时光网TOP100电影知识图谱 环境 1.Neo4j 3.5.6(2019年6月25日) 2.Java 1.8.0_181 3.Annaconda 3 一.准备工作 Neo ...

  2. 知识图谱实战应用11-基于py2neo构建一个简单的问答功能

    大家好,我是微学AI,今天给大家介绍一下知识图谱实战应用10-基于py2neo构建一个简单的问答功能,利用知识图谱来实现智能的问答功能.知识图谱是一种用于表示实体之间关系的图形化模型,它是人工智能和自 ...

  3. 线下课程推荐 | 知识图谱理论与实战:构建行业知识图谱 (第四期)

    知识,是智能的前提. 2012年,Google推出"Google Knowledge Graph",并利用其在搜索引擎中增强搜索结果,这便是"知识图谱"名称的由 ...

  4. mysql实现知识图谱_基于电影知识图谱的智能问答系统学习记录

    学习了"谓之小一"大佬的基于电影知识图谱的智能问答系统,做个记录.地址如下:https://github.com/weizhixiaoyi/DouBan-KGQA 一.知识图谱构建 ...

  5. 使用Neo4j+InteractiveGraph实现豆瓣电影知识图谱可视化

    0.介绍 本文基于豆瓣电影数据构建了一个电影知识图谱.其中包括电影.演员.导演三种节点及相关关系.并使用InteractiveGraph对图谱完成可视化工作. 数据丰富,图谱包含2.7万个节点,5万条 ...

  6. Neo4j构建目标知识图谱

    一.引言 本文主要介绍怎样借助Neo4j构建知识图谱,主要分为软件安装.参数配置.知识图谱定义.图谱展示.案例介绍等环节,整理最近的工作的同时也方便新手快速搭建目标知识图谱. 二.软件安装 本节内容主 ...

  7. neo4j构建农业知识图谱

    neo4j构建农业知识图谱 农业知识图谱(Agriculture_KnowledgeGraph)项目环境构建 前言 1.环境构建 2.导入数据 2.1导入节点HudongItem数据 2.2导入节点N ...

  8. Neo4j 小白必看的电影知识图谱(Movie Graph:Try Neo4j with live data)

    Neo4j 电影知识图谱 Movie Graph初探 前言 1. 创建Graph 2. 查找Data 3. 查询Relation 4. 解决方案 前言 使用实时数据尝试Neo4j,演示常见查询模式的完 ...

  9. 如何构建行业知识图谱 (以医疗行业为例)

    The world is not made of strings,but is made of things. - 辛格博士,from Google 随着人工智能走到台前,人们越来越认识到,场景才是盘 ...

最新文章

  1. 这是我见过最卡通的 Python 算法了,通俗易懂
  2. java的初始化顺序
  3. Python库cx_orcal 在64位win7上的安装记录
  4. 100个直接可以拿来用的JavaScript实用功能代码片段
  5. void init(void) 分析 ! \linux-1.0\init\main.c
  6. 动态规划 - Floyd算法求最短路径 - (Matlab建模)
  7. 如何学习matlab 知乎,知乎日报
  8. python去重复记录_python如何处理重复值数据?
  9. “你出命,我出钱!”靠玩命,他又做了一次首富
  10. SAP License:SAP顾问应具有哪些能力
  11. linux的I/O多路转接select的fd_set数据结构和相应FD_宏的实现分析
  12. Win10加装SSD固态硬盘后卡顿现象的解决方法
  13. Oracle 11g 下载安装
  14. 手把手式介绍 ADNI 影像数据下载
  15. oppo怎么修改dns服务器地址,OPPO R7/R7 Plus修改DNS图文教程
  16. Adaptable DL with nGraph™ Compiler and ONNX*
  17. 轻松Git与Github入门
  18. 如何通俗易懂地理解什么叫泛型?
  19. Allegro自动备份PCB设计文件的方法
  20. window和frame的用法

热门文章

  1. 搭建easy-mock数据模拟服务器
  2. 猫咪藏在哪个房间python_‎App Store 上的“敢问猫在何方 - 妈妈把我的猫咪藏起来了”...
  3. 《东周列国志》第四十八回 刺先克五将乱晋 召士会寿余绐秦
  4. 本地调试公众号微信登录,微信支付
  5. 综述天分、标网、矢网、扫频仪的异同
  6. 电子变压器的设计工艺重不重要?
  7. 【附源码】计算机毕业设计JAVA东理咨询交流论坛
  8. 百度飞浆之PaddleHub视频移动人脸识别
  9. Linux文件类型与扩展名
  10. 无法打开到主机的连接。 在端口 23: 连接失败