You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将本地目录的CSV数据导入Memgraph并使用Python运行DFS算法?

将本地CSV加载至Memgraph并使用Python运行DFS的步骤

一、加载本地CSV到Memgraph

1. 准备CSV数据

确保CSV文件结构清晰,区分节点和边数据:

  • 节点文件(如nodes.csv):包含节点唯一标识、属性和标签
    id,name,label
    1,Alice,Person
    2,Bob,Person
    3,Charlie,Person
    
  • 边文件(如edges.csv):包含起始节点ID、目标节点ID和关系类型
    start_id,end_id,relationship
    1,2,FRIENDS_WITH
    2,3,FRIENDS_WITH
    1,3,WORKS_WITH
    

2. 导入数据到Memgraph

方式1:直接通过Memgraph Lab/mgconsole执行Cypher命令

连接Memgraph后,执行以下命令导入节点和边:

  • 导入节点:
    LOAD CSV FROM "/本地路径/nodes.csv" WITH HEADER AS row
    CREATE (n:Person {id: toInteger(row.id), name: row.name});
    
  • 导入边:
    LOAD CSV FROM "/本地路径/edges.csv" WITH HEADER AS row
    MATCH (a:Person {id: toInteger(row.start_id)}), (b:Person {id: toInteger(row.end_id)})
    CREATE (a)-[r:FRIENDS_WITH]->(b);
    

方式2:Docker运行Memgraph时挂载本地目录

如果用Docker启动Memgraph,先挂载CSV所在本地目录到容器:

docker run -p 7687:7687 -v /本地CSV目录:/data/csv memgraph/memgraph

然后在Cypher中使用容器内路径:

LOAD CSV FROM "/data/csv/nodes.csv" WITH HEADER AS row
CREATE (n:Person {id: toInteger(row.id), name: row.name});

二、用Python实现DFS算法

1. 安装依赖

安装Memgraph的Python客户端mgclient:

pip install mgclient

2. 连接Memgraph并获取图数据

import mgclient

# 建立数据库连接
conn = mgclient.connect(host='localhost', port=7687)
cursor = conn.cursor()

# 提取所有节点信息
cursor.execute("MATCH (n:Person) RETURN n.id, n.name")
nodes = {row[0]: row[1] for row in cursor.fetchall()}

# 构建邻接表
cursor.execute("MATCH (a)-[r]->(b) RETURN a.id, b.id")
adjacency = {node_id: [] for node_id in nodes.keys()}
for a_id, b_id in cursor.fetchall():
    adjacency[a_id].append(b_id)

3. 实现DFS遍历

方式1:手动实现DFS逻辑

def dfs(start_id, adjacency, visited=None):
    if visited is None:
        visited = set()
    visited.add(start_id)
    print(f"访问节点: {nodes[start_id]}")
    # 遍历所有邻接节点
    for neighbor_id in adjacency[start_id]:
        if neighbor_id not in visited:
            dfs(neighbor_id, adjacency, visited)
    return visited

# 从ID为1的节点开始DFS
dfs(1, adjacency)

方式2:使用Cypher内置路径查询实现DFS

直接通过Cypher查询获取DFS路径:

cursor.execute("""
    MATCH path=(n:Person {id:1})-[*]->(m:Person)
    RETURN nodes(path) AS path_nodes
""")
# 打印所有DFS路径
for row in cursor.fetchall():
    path_names = [node['name'] for node in row[0]]
    print(f"DFS路径: {' -> '.join(path_names)}")

4. 关闭连接

conn.close()

内容的提问来源于stack exchange,提问作者MPesi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 04:00:37