使用python向neo4j中批量导入txt和csv三元组数据

1.导入txt文件

数据示例:

(头实体,关系,尾实体)
(头实体,关系,尾实体)
。。。。。。

在执行python代码之前在neo4j中执行这个命令,清空所有节点
match (n) detach delete n

代码:

import py2neo
from py2neo import Graph,Node,Relationship,NodeMatcher
import csv

graph = Graph('http://localhost:7474',user='neo4j',password='自己的密码,neo4j的初始密码是neo4j')

# 打开txt文件
with open("数据文件路径", "r", encoding='utf-8') as file:
    lines = file.readlines()

for line in lines:
    # 分割每行数据
    triple = line.strip().split(", ")

    triple[0] = triple[0].replace("(", "")
    triple[2] = triple[2].replace(")", "")

    # 创建节点和关系
    head_node = Node("Entity", name=triple[0], primary_label="Entity", primary_key="name")
    tail_node = Node("Entity", name=triple[2], primary_label="Entity", primary_key="name")
    relationship = Relationship(head_node, triple[1], tail_node)

    graph.merge(head_node, "Entity", "name")
    graph.merge(tail_node, "Entity", "name")
    graph.merge(relationship)


#关闭连接  这行代码会报错,AttributeError: 'Graph' object has no attribute 'close'
# 是为了看什么时候导入完成,报错的时候说明前面的执行完了,就导入完成了
graph.close()

2.导入csv格式

数据示例:

头实体 关系 尾实体
头实体 关系 尾实体

代码:

with open("数据文件路径", "r", encoding='utf-8') as f:
    reader = csv.reader(f)
    for item in reader:
        head_node = Node("Entity", name=item[0], primary_label="Entity", primary_key="name")
        tail_node = Node("Entity", name=item[2], primary_label="Entity", primary_key="name")
        relationship = Relationship(head_node, item[1], tail_node)

        graph.merge(head_node, "Entity", "name")
        graph.merge(tail_node, "Entity", "name")
        graph.merge(relationship)


#关闭连接
graph.close()

路虽远,行则将至。

相关推荐

  1. 使用pythonneo4j批量导入txtcsv三元数据

    2023-12-19 16:02:01       46 阅读
  2. pythoncsv数据导入neo4j

    2023-12-19 16:02:01       30 阅读
  3. 使用apoc将数据数据库导入neo4j

    2023-12-19 16:02:01       28 阅读
  4. neo4j导出导入数据库

    2023-12-19 16:02:01       25 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-19 16:02:01       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-19 16:02:01       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-19 16:02:01       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-19 16:02:01       18 阅读

热门阅读

  1. 脚本执行权限——chmod +x、chmod -x

    2023-12-19 16:02:01       41 阅读
  2. 某知名经济开发区绩效管理体系建设纪实

    2023-12-19 16:02:01       37 阅读
  3. C#使用HtmlAgilityPack解析HTML结构

    2023-12-19 16:02:01       33 阅读
  4. 绘制动态图表 Python

    2023-12-19 16:02:01       35 阅读
  5. html懒人加载实现

    2023-12-19 16:02:01       32 阅读
  6. 自动生成请假条 - Python实现

    2023-12-19 16:02:01       33 阅读