本篇调用NEO4J接口构建知识图谱,找了很多构建图谱的方法,很少有为本体添加属性,因此,本人写了为本体添加属性以及为两个节点创建关系的方法,下面是一个完整的流程,欢迎评论提问指正。
from neo4j import GraphDatabase
import pandas as pd
与neo4j建立连接
driver = GraphDatabase.driver("bolt://192.168.133.133:6666", auth=("neo4j", "neo4j"))
添加节点属性
def add_person_attribute(tx,df):
"""
本体:人
属性:姓名、年龄
"""
for line in df.values:
person_name = line[0]
person_age = line[1]
tx.run("MERGE (:person {name: $person_name , "
"age: $person_age }) ",
person_name = person_name ,
person_age = person_age )
def add_computer_attribute(tx,df):
"""
本体:电脑
属性:品牌、尺寸
"""
for line in df.values:
computer_brand = line[0]
computer_size = line[1]
tx.run("MERGE (:computer {brand: $computer_brand , "
"size: $computer_size }) ",
computer_brand = computer_brand ,
computer_size = computer_size )
为节点添加关系
def add_relation(tx,df):
"""
本体:人、电脑
关系:拥有
"""
for line in df.values:
person_name = line[0]
computer_brand = line[1]
tx.run("MATCH (a:person {name: $person_name}) "
"MATCH (b:computer {brand: $computer_brand}) "
"MERGE (a)-[:have]->(b)",
person_name = person_name,
computer_brand = computer_brand )
写入neo4j
person_attribute = pd.read_csv('../data/person_attribute .csv')
computer_attribute = pd.read_csv('../data/computer_attribute.csv')
person_computer = pd.read_csv('../data/person_computer .csv')
with driver.session() as session:
session.write_transaction(add_person_attribute, person_attribute )
session.write_transaction(add_computer_attribute, computer_attribute )
session.write_transaction(add_relation, person_computer )