前言
我们在前面讲解 GraphRag 从原始文本中提取知识图谱和构建图结构的时候,最后存储的文件是parquet 格式,文件存储在下面文件夹:

这节我们就探索一下怎么将我们生成好的图谱文件导入到我们的 Neo4j 图数据库,最后进行可视化分析,也能和我们之前的项目混合检索结合起来。
一、准备工作
新建一个 python 脚本文件,比如 graphrag_import.py 可以放在项目的根目录,这里可以随便选择,然后设置我们GraphRAG 生成的图谱文件目录:
GRAPHRAG_FOLDER="artifacts"
安装 neo4j ,如果前面安装过,可以忽略:
pipinstall--upgrade--quietneo4j
导入我们需要的库:
importpandasaspd
fromneo4jimportGraphDatabase
importtime
设置我们的 Neo4j 图库地址,账户密码,以及要导入的数据库名字:
NEO4J_URI="bolt://********:7687"
NEO4J_USERNAME="neo****"
NEO4J_PASSWORD="*****"
NEO4J_DATABASE="****"
driver=GraphDatabase.driver(NEO4J_URI,auth=(NEO4J_USERNAME,NEO4J_PASSWORD))
下载一个语料数据集,https://www.gutenberg.org/cache/epub/24022/pg24022.txt 。
根目录新建 /ragtest/input 空文件,然后把下载好的语料文件放入 input 下面。
二、创建约束
定义一个批处理方法, 使用批处理方法将数据导入 Neo4j 。
参数:statement 是要执行的 Cypher 查询,df 是要导入的数据框,batch_size 是每批要导入的行数。
defbatched_import(statement,df,batch_size=1000):
total=len(df)
start_s=time.time()
forstartinrange(0,total,batch_size):
batch=df.iloc[start:min(start+batch_size,total)]
result=driver.execute_query("UNWIND$rowsASvalue"+statement,
rows=batch.to_dict('records'),
database_=NEO4J_DATABASE)
print(result.summary.counters)
print(f'{total}rowsin{time.time()-start_s}s.')
returntotal
Neo4j 中的索引用于查找图形查询的起点,例如快速找到要连接的两个节点。
为了避免重复,我们主要在实体类型的 ID 上创建约束。
我们使用一些类型作为标记,前后带有两个下划线,以将它们与实际实体类型区分开来。
这些标签(如 __Entity__ , __Document__, __Chunk__, __Community__, __Covariate__)通常用于标识不同类型的节点。
标签本身没有固定的意义,它们的意义完全取决于你的数据模型和应用程序如何使用它们。
Entity__` 通常代表一个实体( `Entity` ),可能是现实世界中的某个对象、人物、地点或其他可识别的对象。比如,在一个知识图谱中,`__Entity 可能代表“公司”、“人物”等。
Document__` 可以是一个特殊类型的节点,代表一个文档(Document)或文件,通常是文本数据的容器。比如,在文档分析或文本挖掘的场景中,`__Document 可能指代一本书、一篇文章、一份报告等。
Chunk__` (块)表示文档的某个片段或块(`Chunk`),在图数据库上下文中,这可能指的是数据的一个片段或部分,通常用于文本分块处理。例如,在自然语言处理任务中,文档可能被拆分成句子、段落或者更小的片段,这些片段可能被标记为 `__Chunk。
Community__` 这个标签表示一个社区(`Community`),通常用于表示图结构中的聚类或群体。例如,在社交网络分析中,`__Community 可能表示具有共同兴趣的用户群体,或者在知识图谱中表示相互关联的实体群组。
Covariate__` 这个标签可能代表协变量(`Covariate`),即与其他变量一起在统计模型中使用的变量。在一些机器学习或统计模型中,`__Covariate 可能表示影响或关联其他数据点的属性或特征
下面是一个简单的neo4j查询语句:
MATCH(e:Entity)-[:CONTAINS]->(d
ocument)
WHEREe.type='Community'ANDd.covariate='SomeValue'
RETURNe,d
这个查询查找类型为"Community"的实体,这些实体包含具有特定协变量值的文档。
需要注意的是,这些术语的确切用法可能因具体的数据模型和应用场景而异。
在使用 Neo4j 时,重要的是根据您的特定需求来设计和实现数据模型。
关于 Neo4j 的查询部分,后面再细说。
创建一个约束(constraint):
statements="""
createconstraintchunk_idifnotexistsfor(c:__Chunk__)requirec.idisunique;
createconstraintdocument_idifnotexistsfor(d:__Document__)required.idisunique;
createconstraintentity_idifnotexistsfor(c:__Community__)requirec.communityisunique;
createconstraintentity_idifnotexistsfor(e:__Entity__)requiree.idisunique;
createconstraintentity_titleifnotexistsfor(e:__Entity__)requiree.nameisunique;
createconstraintentity_titleifnotexistsfor(e:__Covariate__)requiree.titleisunique;
createconstraintrelated_idifnotexistsfor()-[rel:RELATED]->()requirerel.idisunique;
""".split(";")
forstatementinstatements:
iflen((statementor"").strip())>0:
print(statement)
driver.execute_query(statement)
通过字符串 split 函数将字符串分割成数组,然后执行循环取值,最后交给 Neo4j 执行。
这个创建约束的语句具体含义是:为所有标签为 __Chunk__ 的节点创建一个约束,要求它们的 id 属性必须是唯一的。
如果这个约束已经存在,则不会重复创建。
执行成功,可以看到结果下面是这样:

三、导入文档
我们现在需要加载文档的 parquet 文件, 使用 Python 的 pandas 库来读取和处理数据,然后使用其 id 创建节点并添加 title 属性。
我们不需要存储 text_unit_ids,因为我们可以创建关系,并且文本内容也包含在块中,如下面所示。
doc_df=pd.read_parquet(f'{GRAPHRAG_FOLDER}/create_final_documents.parquet',columns=["id","title"])
doc_df.head(2)
执行它:

导入文档到图数据库:
#importdocuments
statement="""
MERGE(d:__Document__{id:value.id})
SETd+=value{.title}
"""
batched_import(statement,doc_df)
得到结果:

然后我们加载文本单元,为每个 id 创建一个节点并设置文本和标记数量。
然后我们将它们连接到我们之前创建的文档。
text_df=pd.read_parquet(f'{GRAPHRAG_FOLDER}/create_final_text_units.parquet',
columns=["id","text","n_tokens","document_ids"])
text_df.head(2)
得到下面结果:

导入文本单元到图数据库:
statement="""
MERGE(c:__Chunk__{id:value.id})
SETc+=value{.text,.n_tokens}
WITHc,value
UNWINDvalue.document_idsASdocument
MATCH(d:__Document__{id:document})
MERGE(c)-[
ART_OF]->(d)
"""
batched_import(statement,text_df)
这段 cypher 的含义是创建或更新一个 __Chunk__ 节点,设置其属性。
对于与这个 Chunk 相关的每个Document :找到对应的 __Document__ 节点。
创建一个从 __Chunk__ 到 __Document__ 的 PART_OF 关系。
运行结果:

加载实体:
entity_df=pd.read_parquet(f'{GRAPHRAG_FOLDER}/create_final_entities.parquet',
columns=["name","type","description","human_readable_id","id","description_embedding","text_unit_ids"])
entity_df.head(2)
运行结果:

导入实体:
entity_statement="""
MERGE(e:__Entity__{id:value.id})
SETe+=value{.human_readable_id,.description,name:replace(value.name,'"','')}
WITHe,value
CALLdb.create.setNodeVectorProperty(e,"description_embedding",value.description_embedding)
CALLapoc.create.addLabels(e,casewhencoalesce(value.type,"")=""then[]else[apoc.text.upperCamelCase(replace(value.type,'"',''))]end)yieldnode
UNWINDvalue.text_unit_idsAStext_unit
MATCH(c:__Chunk__{id:text_unit})
MERGE(c)-[:HAS_ENTITY]->(e)
"""
batched_import(entity_statement,entity_df)
运行结果:

加载关系:
rel_df=pd.read_parquet(f'{GRAPHRAG_FOLDER}/create_final_relationships.parquet',
columns=["source","target","id","rank","weight","human_readable_id","description","text_unit_ids"])
rel_df.head(2)

导入关系:
rel_statement="""
MATCH(source:__Entity__{name:replace(value.source,'"','')})
MATCH(target:__Entity__{name:replace(value.target,'"','')})
//notnecessarytomergeonidasthereisonlyonerelationshipperpair
MERGE(source)-[rel:RELATED{id:value.id}]->(target)
SETrel+=value{.rank,.weight,.human_readable_id,.description,.text_unit_ids}
RETURNcount(*)ascreatedRels
"""
batched_import(rel_statement,rel_df)
运行结果:

加载社区:
community_df=pd.read_parquet(f'{GRAPHRAG_FOLDER}/create_final_communities.parquet',
columns=["id","level","title","text_unit_ids","relationship_ids"])
community_df.head(2)
运行结果:

导入社区:
statement="""
MERGE(c:__Community__{community:value.id})
SETc+=value{.level,.title}
/*
UNWINDvalue.text_unit_idsastext_unit_id
MATCH(t:__Chunk__{id:text_unit_id})
MERGE(c)-[:HAS_CHUNK]->(t)
WITHdistinctc,value
*/
WITH*
UNWINDvalue.relationship_idsasrel_id
MATCH(start:__Entity__)-[:RELATED{id:rel_id}]->(end:__Entity__)
MERGE(start)-[:IN_COMMUNITY]->(c)
MERGE(end)-[:IN_COMMUNITY]->(c)
RETURNcount(distinctc)ascreatedCommunities
"""
batched_import(statement,community_df)
运行结果:

加载社区报告:
community_report_df=pd.read_parquet(f'{GRAPHRAG_FOLDER}/create_final_community_reports.parquet',
columns=["id","community","level","title","summary","findings","rank","rank_explanation","full_content"])
community_report_df.head(2)
运行结果:

导入社区报告:
#importcommunities
community_statement="""
MERGE(c:__Community__{community:value.community})
SETc+=value{.level,.title,.rank,.rank_explanation,.full_content,.summary}
WITHc,value
UNWINDrange(0,size(value.findings)-1)ASfinding_idx
WITHc,value,finding_idx,value.findings[finding_idx]asfinding
MERGE(c)-[:HAS_FINDING]->(f:Finding{id:finding_idx})
SETf+=finding
"""
batched_import(community_statement,community_report_df)
运行结果:

至此 GraphRag 文件导入完毕,我们可以进入 Neo4j 的浏览器界面进行可视化分析。
每个实体可以点开,可以看到石猴为中心的各种关系。

点开社区,可以看到这是对某一事件的整合,并且关联了哪些人物。

可视化分析方式还有很多,可以查看文档,文本单元等等,对于我们不同的输入检索文本我们需要做不同的数据分析,至于我们想要的结果,也是一目了然。
四、总结
通过导入让 GraphRag 生成的图文件能够存储到我们的 Neo4J 里面,然后使用 Neo4J 可视化分析GraphRAG 索引结果,让我们能够更为直观的了解整个 GraphRAG 索引结果。