Neo4j启动
打开cmd切换到neo4j安装目录的bin下,输入以下命令
neo4j console
CSV数据样例
实体
关系
文章来源:https://www.toymoban.com/news/detail-617596.html
生成CSV代码
def write2csv2(entities, relations):
out_path = r'D:\Neo4j\XXX\import'
entity_types = {"装备": "equipment", "组织": "organization"}
relation_types = {'配备': 'Equip'}
for et in entity_types:
with open(os.path.join(out_path, entity_types[et] + '.csv'), 'w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
# 写入数据
writer.writerow([entity_types[et]])
for e in entities:
if e['label'] == et:
writer.writerow([e['text']])
for rt in relation_types:
with open(os.path.join(out_path, relation_types[rt] + '.csv'), 'w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
# 写入数据
writer.writerow(["from_entity", "to_entity"])
for r in relations:
if r['type'] == rt:
# print(r['from_entity']['label'])
writer.writerow(
[r['from_entity']['text'],
r['to_entity']['text']])
# 关闭CSV文件
file.close()
导入实体
load csv with headers
from 'file:///entity.csv' as line
fieldterminator ','
create (
p:entity_name{
entity_name: line.entity_name
}
)
导入关系
load csv with headers from "file:///relation.csv"
as row
merge (f1:from_entity_name{name:row.from_entity})
merge (f2:to_entity_name{name:row.to_entity})
merge (f1)-[r:relation_name]->(f2)
查询实体
MATCH (n) RETURN n
MATCH (n) RETURN n LIMIT 25
查询关系
MATCH p=()-->() RETURN p
MATCH p=()-[r:relation_name]->() RETURN p LIMIT 25
删除所有数据
match (n) detach delete n
读取本地任意路径CSV文件
如果想读取不在import directory中的CSV,则:
(1)先改变neo4j默认设置,即:删除dbms.directories.import=import或者在该语句前加“#”;
(2)使用 “LOAD CSV FROM file:///C:/XXX/name.csv”(即:file:///+绝对路径), 导入本地CSV文件 。文章来源地址https://www.toymoban.com/news/detail-617596.html
到了这里,关于Neo4j导入CSV文件(实体和关系)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!