Neo4j导入CSV文件(实体和关系)

文章介绍了如何启动Neo4j数据库,利用CSV数据样例进行实体和关系的导入,并提供了导入后的查询和删除数据的方法。此外,还讲解了如何从本地任意路径读取CSV文件进行导入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Neo4j启动

打开cmd切换到neo4j安装目录的bin下,输入以下命令

neo4j console

CSV数据样例

实体

在这里插入图片描述

关系

在这里插入图片描述

生成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文件 。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值