LLM - 使用 Neo4j 可视化 GraphRAG 构建的 知识图谱(KG) 教程

ops/2024/10/18 18:44:29/

欢迎关注我的CSDN:https://spike.blog.csdn.net/
本文地址:https://spike.blog.csdn.net/article/details/142938982

免责声明:本文来源于个人知识与公开资料,仅用于学术交流,欢迎讨论,不支持转载。


<a class=Neo4j" />

Neo4j 是一个高性能的图形数据库,允许用户以图形的形式存储和检索数据,这种形式非常适合处理复杂的关系和网络结构,因其在数据关系处理方面的强大能力而广受欢迎,尤其是在社交网络、推荐系统、网络分析等领域。

构建 GraphRAG知识图谱,请参考:配置 GraphRAG + Ollama 服务 构建 中文知识图谱 教程(踩坑记录)

  • Doc:https://neo4j.com/docs/apoc/current/

Neo4j__18">1. 配置 Neo4j 服务

准备 Docker,参考 Docker - Neo4j

docker pull neo4j:5.24.1

启动 Docker (直接启动,同时运行服务):

docker run --network=host --gpus all --rm --name neo4j-apoc \
-e NEO4J_apoc_export_file_enabled=true \
-e NEO4J_apoc_import_file_enabled=true \
-e NEO4J_apoc_import_file_use__neo4j__config=true \
-e NEO4J_PLUGINS=\[\"apoc\"\] \
--volume=[your folder]:[your folder] \
neo4j:5.24.1

或者,进入 Docker,再启动服务:

docker run --network=host --gpus all -it --name neo4j-apoc -e NEO4J_apoc_export_file_enabled=true -e NEO4J_apoc_import_file_enabled=true -e NEO4J_apoc_import_file_use__neo4j__config=true -e NEO4J_PLUGINS=\[\"apoc\"\] --volume=[your folder]:[your folder] neo4j:5.24.1 /bin/bashbin/neo4j start

注意:使用 Neo4j + APOC 版本的 Docker。APOC(Awesome Procedures on Cypher) 是 Neo4j 图数据库的一个插件,提供一组强大的过程和函数,扩展 Cypher 查询语言的功能。参考:Neo4J and APOC

日志:

Installing Plugin 'apoc' from /var/lib/neo4j/labs/apoc-*-core.jar to /var/lib/neo4j/plugins/apoc.jar
Applying default values for plugin apoc to neo4j.conf
2024-10-15 01:40:54.429+0000 INFO  Logging config in use: File '/var/lib/neo4j/conf/user-logs.xml'
2024-10-15 01:40:54.443+0000 INFO  Starting...
2024-10-15 01:40:55.191+0000 INFO  This instance is ServerId{0350f51a} (0350f51a-ef80-414f-b82f-8e4b38fc369f)
2024-10-15 01:40:56.078+0000 INFO  ======== Neo4j 5.24.1 ========
2024-10-15 01:40:58.875+0000 INFO  Anonymous Usage Data is being sent to Neo4j, see https://neo4j.com/docs/usage-data/
2024-10-15 01:40:58.910+0000 INFO  Bolt enabled on 0.0.0.0:7687.
2024-10-15 01:40:59.325+0000 INFO  HTTP enabled on 0.0.0.0:7474.
2024-10-15 01:40:59.326+0000 INFO  Remote interface available at http://localhost:7474/
2024-10-15 01:40:59.328+0000 INFO  id: 3C118963730B6744966FCB5FC5D9D5795B11AD1F791A4DDC113D02D1F926441F
2024-10-15 01:40:59.329+0000 INFO  name: system
2024-10-15 01:40:59.329+0000 INFO  creationDate: 2024-10-15T01:40:57.342Z
2024-10-15 01:40:59.329+0000 INFO  Started.

启动服务:http://[your ip]:7474/browser/,默认账户和密码都是 neo4j,需要修改新密码 xxxxxx,建议 neo4j123 (自定义)。

启动页面,注意,实体和关系都空的,即:

<a class=Neo4j" />

2. 注入知识图谱数据

数据位于:/var/lib/neo4j/data/databases/neo4j,其中 neo4j 是数据库。

读取 GraphRAG知识图谱数据,如下:

import os
import pandas as pdrag_dir = "[your folder]/llm/graphrag/ragtest/output/"entities = pd.read_parquet(os.path.join(rag_dir, "create_final_entities.parquet"))
relationships = pd.read_parquet(os.path.join(rag_dir, "create_final_relationships.parquet"))
text_units = pd.read_parquet(os.path.join(rag_dir, "create_final_text_units.parquet"))
communities = pd.read_parquet(os.path.join(rag_dir, "create_final_communities.parquet"))
community_reports = pd.read_parquet(os.path.join(rag_dir, "create_final_community_reports.parquet"))

测试数据:

entities.head(2)
relationships.head(2)
text_units.head(2)
communities.head(2)
community_reports.head(2)

连接服务器:

NEO4J_URI = "neo4j://localhost:7687"
NEO4J_USERNAME = "neo4j"
NEO4J_PASSWORD = "xxxxxx"	# 之前修改的密码
NEO4J_DATABASE = "neo4j"  	# 默认
driver = GraphDatabase.driver(NEO4J_URI, auth=(NEO4J_USERNAME, NEO4J_PASSWORD))

注意:社区版本,不能创建新的 Database 只能使用默认的 neo4j,创建命令 CREATE DATABASE my-database,参考

数据导入函数:

def import_data(cypher, df, batch_size=1000):for i in range(0,len(df), batch_size):batch = df.iloc[i: min(i+batch_size, len(df))]result = driver.execute_query("UNWIND $rows AS value " + cypher, rows=batch.to_dict('records'),database_=NEO4J_DATABASE)print(result.summary.counters)return 

导入 text_units 命令:

#导入text_units
cypher_text_units = """
MERGE (c:__Chunk__ {id:value.id})
SET c += value {.text, .n_tokens}
WITH c, value
UNWIND value.document_ids AS document
MATCH (d:__Document__ {id:document})
MERGE (c)-[:PART_OF]->(d)
"""import_data(cypher_text_units, text_units)

运行成功,日志:

{'_contains_updates': True, 'labels_added': 99, 'relationships_created': 235, 'nodes_created': 99, 'properties_set': 396}

导入 entities 数据的命令:

#导入entities
cypher_entities= """
MERGE (e:__Entity__ {id:value.id})
SET e += value {.human_readable_id, .description, name:replace(value.name,'"','')}
WITH e, value
CALL db.create.setNodeVectorProperty(e, "description_embedding", value.description_embedding)
CALL apoc.create.addLabels(e, case when coalesce(value.type,"") = "" then [] else [apoc.text.upperCamelCase(replace(value.type,'"',''))] end) yield node
UNWIND value.text_unit_ids AS text_unit
MATCH (c:__Chunk__ {id:text_unit})
MERGE (c)-[:HAS_ENTITY]->(e)
"""import_data(cypher_entities, entities)

导入 relationships 数据的命令:

#导入relationships
cypher_relationships = """MATCH (source:__Entity__ {name:replace(value.source,'"','')})MATCH (target:__Entity__ {name:replace(value.target,'"','')})// not necessary to merge on id as there is only one relationship per pairMERGE (source)-[rel:RELATED {id: value.id}]->(target)SET rel += value {.rank, .weight, .human_readable_id, .description, .text_unit_ids}RETURN count(*) as createdRels
"""import_data(cypher_relationships, relationships)

导入 communities 数据的命令:

#导入communities
cypher_communities = """
MERGE (c:__Community__ {community:value.id})
SET c += value {.level, .title}
/*
UNWIND value.text_unit_ids as text_unit_id
MATCH (t:__Chunk__ {id:text_unit_id})
MERGE (c)-[:HAS_CHUNK]->(t)
WITH distinct c, value
*/
WITH *
UNWIND value.relationship_ids as rel_id
MATCH (start:__Entity__)-[:RELATED {id:rel_id}]->(end:__Entity__)
MERGE (start)-[:IN_COMMUNITY]->(c)
MERGE (end)-[:IN_COMMUNITY]->(c)
RETURn count(distinct c) as createdCommunities
"""import_data(cypher_communities, communities)

导入 community_reports 数据的命令:

#导入community_reports
cypher_community_reports = """MATCH (c:__Community__ {community: value.community})
SET c += value {.level, .title, .rank, .rank_explanation, .full_content, .summary}
WITH c, value
UNWIND range(0, size(value.findings)-1) AS finding_idx
WITH c, value, finding_idx, value.findings[finding_idx] as finding
MERGE (c)-[:HAS_FINDING]->(f:Finding {id: finding_idx})
SET f += finding"""
import_data(cypher_community_reports, community_reports)

3. 测试效果

启动 Neo4j 页面,知识图谱可视化,包括 Node labels 和 Relationship types 等功能,即:

数据

其他知识图谱元素的可视化,参考 Neo4j 的文档。


http://www.ppmy.cn/ops/126538.html

相关文章

深入了解React 工作原理是什么

前端面试题包括ECMScript,TypeScript,Nodejs,React,Webgl,Webpack,Threejs等还在整理中&#xff0c;在线地址前端面试题&#xff0c;源码地址大家多多支持才有动力给大家分享更多好的面试题。 React 的工作原理基于以下几个关键概念&#xff1a;虚拟 DOM&#xff08;Virtual D…

@PostConstruct和afterPropertiesSet方法执行多次的原因

近日&#xff0c;遇到一个问题&#xff0c;PostConstruct方法会莫名执行多次&#xff0c;单看代码看不出问题&#xff0c;印象中也只会在bean初始化的时候执行一次而已。 然后问AI&#xff0c;问百度&#xff0c;没找到原因。 后面自己猜测&#xff08;现在都是面向猜测编程&am…

大数据治理:定义、重要性及实践

大数据治理&#xff1a;定义、重要性及实践 引言 大数据治理是当代企业信息管理和数据管理的重要环节&#xff0c;它涉及到数据的获取、处理、存储、安全、质量、生命周期管理等方方面面。随着信息技术的迅猛发展和数据量的爆炸式增长&#xff0c;大数据治理已经成为企业提升…

Vue 3 中的状态管理:深入探讨 Vuex 和 Pinia 的比较与最佳实践

文章目录 1. 引言2. Vuex 的使用及其状态管理模型2.1 Vuex 的核心概念2.2 Vuex 的优点与局限性 3. Pinia 的特点及与 Vuex 的比较3.1 Pinia 的核心特点3.2 Pinia 与 Vuex 的主要区别 4. 如何在 Vue 3 中实现状态管理的最佳实践4.1 小型应用中的最佳实践4.2 大型应用中的最佳实践…

python多线程lock使用方法进行文件锁定

如果写文件想让这个线程写的时候&#xff0c;别的线程不会干扰写&#xff0c;也就是不中间插内容 需要使用thread.lock方法 代码&#xff1a; import threading import datetime import random from queue import Queue lockthreading.Lock() def writelog():lock.acquire()w…

Java中数组的定义与使用

1. 数组的基本概念 1.1 什么是数组 数组的定义&#xff1a;一个相同元素的集合 在java中&#xff0c;包含6个整形类型元素的数组 数组中存放的元素其类型相同数组的空间是连在一起的每个空间有自己的编号&#xff0c;其实位置的编号为0&#xff0c;即数组的下标。 那在程序中如…

DevExpress WPF中文教程:Data Grid(数据网格)实现细节一览

DevExpress WPF拥有120个控件和库&#xff0c;将帮助您交付满足甚至超出企业需求的高性能业务应用程序。通过DevExpress WPF能创建有着强大互动功能的XAML基础应用程序&#xff0c;这些应用程序专注于当代客户的需求和构建未来新一代支持触摸的解决方案。 无论是Office办公软件…

哪家云电脑便宜又好用?ToDesk云电脑、顺网云、达龙云全方位评测

陈老老老板&#x1f934; &#x1f9d9;‍♂️本文专栏&#xff1a;生活&#xff08;主要讲一下自己生活相关的内容&#xff09;生活就像海洋,只有意志坚强的人,才能到达彼岸。 &#x1f9d9;‍♂️本文简述&#xff1a;讲一下市面上云电脑的对比。 &#x1f9d9;‍♂️上一篇文…