Apache AGE:创建顶点标签并从CSV为employees图加载新顶点
针对
employees图的新顶点标签创建与CSV导入操作(Gremlin兼容数据库) 1. 连接目标图
先通过Gremlin控制台或客户端连接到你的employees图实例,以JanusGraph为例:
graph = JanusGraphFactory.open('your-graph-config.properties') g = graph.traversal()
2. 创建新顶点标签及属性键
根据需求创建新的顶点标签(比如department存储部门信息,或employee_contact存储电话),同时提前定义所需属性键:
// 开启管理事务 mgmt = graph.openManagement() // 创建属性键(按需定义) dept_name = mgmt.makePropertyKey('dept_name').dataType(String.class).make() phone = mgmt.makePropertyKey('phone').dataType(String.class).make() // 创建顶点标签 mgmt.makeVertexLabel('department').make() mgmt.makeVertexLabel('employee_contact').make() // 提交变更 mgmt.commit()
3. 准备CSV文件
确保CSV格式清晰,包含必要的关联字段(比如关联现有员工的employee_id):
- 部门数据CSV示例:
dept_id,dept_name 1,研发部 2,市场部 3,人事部 - 员工联系方式CSV示例:
employee_id,phone E001,138xxxx1234 E002,139xxxx5678
4. 导入CSV数据到图中
小规模数据:Gremlin脚本直接导入
// 导入部门顶点 new File('/path/to/departments.csv').eachLine { line -> if (!line.startsWith('dept_id')) { // 跳过表头 def cols = line.split(',') graph.addVertex(label, 'department', 'dept_id', cols[0], 'dept_name', cols[1]) } } graph.tx().commit() // 导入员工联系方式并关联现有员工 new File('/path/to/employee_contacts.csv').eachLine { line -> if (!line.startsWith('employee_id')) { def cols = line.split(',') // 匹配现有员工顶点 def employee = g.V().has('employee_id', cols[0]).next() // 创建联系方式顶点并建立关联边 def contact = graph.addVertex(label, 'employee_contact', 'phone', cols[1]) employee.addEdge('has_contact', contact) } } graph.tx().commit()
大规模数据:使用批量导入工具
如果数据量较大,推荐用数据库自带的批量导入工具,比如JanusGraph的bulk-loader或Neo4j的neo4j-admin import。以JanusGraph为例,需先编写映射配置文件(定义CSV字段与顶点属性的对应关系),再执行命令:
bin/janusgraph.sh import \ -c conf/janusgraph.properties \ -f conf/import/vertex-mapping.json \ -s conf/import/schema-definition.properties
5. 验证导入结果
执行Gremlin查询确认数据已正确导入:
// 查询所有新创建的部门顶点 g.V().hasLabel('department').valueMap() // 查询带有联系方式的员工及对应电话 g.V().hasLabel('employee').out('has_contact').valueMap('phone')
内容的提问来源于stack exchange,提问作者Abdul Manan
相关产品推荐
相关产品推荐

