三种创建Neo4j知识图谱方法详解

使用Neo4j创建知识图谱有以下三种方式:

1、通过Neo4j Desktop导入数据集;

2、通过Python py2neo graph.run()命令执行create语句

3、通过Python py2neo graph.create()命令执行创建节点及关系

根据目前实践,第一种、第二种适合批量操作,而第二种更适合在线操作,下面将一一详细介绍。

一、通过Neo4j Desktop导入数据集

(1)前序文章已介绍过Neo4j Desktop下载安装,在此不再赘述,如下图,在创建一个Project Graph后,打开Graph,点击Open Folder,下面有选项Import,选择Import则可以打开默认Import目录,我们需要上传的文件就需要保存在该路径下。

(2)在Neo4j Browser执行load语句,命令如下:

load CSV with headers from 'file:///directors.csv' as line create (actor:Person {name:line.name,year:line.year})

原始文件数据内容如下,要注意的是csv文件格式为GB1213,而导入数据格式要求为utf-8,所以导入前先将csv文件格式转换为utf-8,否则会乱码。我用的是notepad++打开csv文件,Encoding为utf-8。

导入之后查询可见下图。

 二、通过Python py2neo graph.run()命令执行create语句

(1)直接上代码

import py2neo
from py2neo import Graph,Node,Relationship
from base import openfile
import re

graph=Graph(
    "http://localhost:11010/",
    username="admin",
    password="password"
)

def read_data():
    file="d:/share/movie/directors.csv"
    punc = ':· - ...:-'
    with open ( file, 'r', encoding='utf-8' ) as f :
        context = f.read ( ).split('\n')
    for text in context[1:]:
        text1 = re.sub(r"[%s]+" % punc, "", text.strip( ).split(',')[0]) #名字中间不能带特殊符号,所以先去掉
        text2 = text.strip( ).split(',')[1]
        graph.run (
            "CREATE (" + text1 + ":Person {name:'" + text1 + "', year:" + text2 + "})" )

if __name__ == "__main__":
    read_data()

执行结果如下:

 三、通过Python py2neo graph.create()命令

因为更多的使用第二种方法,这块没有深入研究,附简单代码:

from py2neo import Graph,Node,Relationship,NodeMatcher
graph=Graph('http://localhost:11010',username='admin',password='password')
test_node_1 = Node(label = "Person",name = "time")
test_node_2 = Node(label = "Person",name = "title")
graph.create(test_node_1)
graph.create(test_node_2)
node_1_call_node_2 = Relationship(test_node_1,'CALL',test_node_2)
node_1_call_node_2['count'] = 1
graph.create(node_1_call_node_2)
发布了123 篇原创文章 · 获赞 12 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/haiziccc/article/details/103135005