当前位置:   article > 正文

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

neo4j导入csv关系

Neo4j启动

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

neo4j console
  • 1

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()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

导入实体

load csv with headers
from 'file:///entity.csv' as line
fieldterminator ','
create (
	p:entity_name{
    	entity_name: line.entity_name
    }
)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

导入关系

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)
  • 1
  • 2
  • 3
  • 4
  • 5

查询实体

MATCH (n) RETURN n

MATCH (n) RETURN n LIMIT 25
  • 1
  • 2
  • 3

查询关系

MATCH p=()-->() RETURN p

MATCH p=()-[r:relation_name]->() RETURN p LIMIT 25
  • 1
  • 2
  • 3

删除所有数据

match (n) detach delete n
  • 1

读取本地任意路径CSV文件

如果想读取不在import directory中的CSV,则:
(1)先改变neo4j默认设置,即:删除dbms.directories.import=import或者在该语句前加“#”;
(2)使用 “LOAD CSV FROM file:///C:/XXX/name.csv”(即:file:///+绝对路径), 导入本地CSV文件 。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/563962?site
推荐阅读
相关标签
  

闽ICP备14008679号