Gremlin创建schema(包括实体和关系)

1、构建图谱schema,流程包括图创建、实体构建以及关系构建。

      创建图时需要指定图库名称以及主键字段。

       实体构建时需要指定主键字段,每个属性需要指定数据类型,是否非空以及默认值。关系构建时需要包括关系名称、指向头实体的标签,指向尾实体的标签等字段。

Java代码展示:

import com.gridgraph.driver.GridGraphAuthenticationException;
import com.gridgraph.driver.GridGraphSecureCluster;
import org.apache.tinkerpop.gremlin.driver.Client;
public class AddSchema {public static void main(String[] args) throws Exception {try{String address = "localhost";int port = 9999;String username = "";String password = "";String database = "实体1";GridGraphSecureCluster cluster = new GridGraphSecureCluster(address, port, username, password);Client client = cluster.connect(true);StringBuilder sb = new StringBuilder();sb.append(String.format("graph=GridGraphFactory.createGraph('%s');graph.createPrimaryKey('id');", database));sb.append("equipSchema = graph.createSchema('实体1', SchemaType.VERTEX);");sb.append("equipSchema.createProperty('属性1', GridDataType.STRING, false, false, null);");sb.append("equipSchema.createProperty('属性2', GridDataType.STRING, false, false, null);");sb.append("manuSchema = graph.createSchema('实体2', SchemaType.VERTEX);");sb.append("manuSchema.createProperty('属性1', GridDataType.STRING, false, false, null);");sb.append("manuSchema.createProperty('属性2', GridDataType.STRING, false, false, null);");sb.append("subSchema = graph.createSchema('实体3', SchemaType.VERTEX);");sb.append("subSchema.createProperty('属性1', GridDataType.STRING, false, false, null);");sb.append("subSchema.createProperty('属性2', GridDataType.STRING, false, false, null);");sb.append("relSchema = graph.createSchema('关系', SchemaType.EDGE);");sb.append("relSchema.createProperty('h_table', GridDataType.STRING, false, false, null);");sb.append("relSchema.createProperty('t_table', GridDataType.STRING, false, false, null);");sb.append("relSchema.createProperty('r', GridDataType.STRING, false, false, null);");client.submit(sb.toString());client.close();} catch (GridGraphAuthenticationException e) {throw new RuntimeException(e);}}
}

Python代码展示:

#encoding=utf8
from gremlin_python.driver import clientif __name__ == '__main__':client = client.Client('ws://localhost:9999/gremlin', None, username='', password='')database = "实体1"prefix = f"graph=GridGraphFactory.createGraph('{database}');graph.createPrimaryKey('id');"    client.submit(prefix +f'''equipSchema = graph.createSchema('实体1', SchemaType.VERTEX);equipSchema.createProperty('属性1', GridDataType.STRING, false, false, null);equipSchema.createProperty('属性2', GridDataType.STRING, false, false, null);manuSchema = graph.createSchema('实体2', SchemaType.VERTEX);manuSchema.createProperty('属性1', GridDataType.STRING, false, false, null);manuSchema.createProperty('属性2', GridDataType.STRING, false, false, null);subSchema = graph.createSchema('实体3', SchemaType.VERTEX);subSchema.createProperty('属性1', GridDataType.STRING, false, false, null);subSchema.createProperty('属性2', GridDataType.STRING, false, false, null);relSchema = graph.createSchema('关系', SchemaType.EDGE)relSchema.createProperty('h_table', GridDataType.STRING, false, false, null)relSchema.createProperty('t_table', GridDataType.STRING, false, false, null)relSchema.createProperty('r', GridDataType.STRING, false, false, null)''')client.close()

2、填入数据,添加实体时,需要指定实体主键、属性以及对应的属性值,添加关系时,需要指定头实体、尾实体以及关系名,最终形成知识图谱。

Java代码展示:

import com.gridgraph.driver.GridGraphAuthenticationException;
import com.gridgraph.driver.GridGraphSecureCluster;
import org.apache.tinkerpop.gremlin.driver.Client;
public class AddData {public static void main(String[] args) throws Exception {try{String address = "localhost";int port = 9999;String username = "";String password = "";String database = "实体1";GridGraphSecureCluster cluster = new GridGraphSecureCluster(address, port, username, password);Client client = cluster.connect(true);StringBuilder sb = new StringBuilder();sb.append(String.format("graph=GridGraphFactory.openGraph('%s');", database));sb.append("e1 = graph.addVertex(T.label, '实体1', 'id', '1', '属性1', '1', '属性2', '2');");sb.append("e2 = graph.addVertex(T.label, '实体2', 'id', '2', '属性1', '1', '属性2', '2');");sb.append("e3 = graph.addVertex(T.label, '实体3', 'id', '3', '属性1', '1', '属性2', '2');");sb.append("e1.addEdge('关系', e2, 'h_table', '实体1', 't_table', '实体3', 'r', 'r1');");sb.append("e1.addEdge('关系', e3, 'h_table', '实体1', 't_table', '实体3', 'r', 'r2');");sb.append("graph.tx().commit();");client.submit(sb.toString());client.close();} catch (GridGraphAuthenticationException e) {throw new RuntimeException(e);}}

Python代码展示:

#encoding=utf8
from gremlin_python.driver import client
if __name__ == '__main__':client = client.Client('ws://localhost:9999/gremlin', None, username='', password='')database = "实体1"prefix = f"graph=GridGraphFactory.openGraph('{database}');g=graph.traversal();"client.submit(prefix +f'''e1 = graph.addVertex(T.label, '实体1', 'id', '1', '属性1', '1', '属性2', '2')         e2 = graph.addVertex(T.label, '实体2', 'id', '2', '属性1', '1', '属性2', '2')e3 = graph.addVertex(T.label, '实体3', 'id', '3', '属性1', '1', '属性2', '2')e1.addEdge('关系', e2, 'h_table', '实体1', 't_table', '实体3', 'r', 'r1')e1.addEdge('关系', e3, 'h_table', '实体1', 't_table', '实体3', 'r', 'r2')graph.tx().commit();''')client.close()

3、打印schema结构

对于每一个实体,遍历图数据库中所有的schema,同时遍历每一个schema中的每一个属性,生成“实体类型(属性1,属性2,属性3)”的结构;

对于每一个关系,可以遍历所有关系数据中的 头标签、关系名、尾标签,对其进行去重,生成“头标签--[r:关系名]-->尾标签”的结构。

Java代码展示:

import com.gridgraph.driver.GridGraphAuthenticationException;
import com.gridgraph.driver.GridGraphSecureCluster;
import org.apache.tinkerpop.gremlin.driver.Client;
import org.apache.tinkerpop.gremlin.driver.Result;
import org.apache.tinkerpop.gremlin.driver.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class SchemaPrompt {public static void main(String[] args) throws Exception {try{String address = "localhost";int port = 9999;String username = "";String password = "";String database = "实体1";GridGraphSecureCluster cluster = new GridGraphSecureCluster(address, port, username, password);Client client = cluster.connect(true);client.submit(String.format("graph=GridGraphFactory.openGraph('%s');g=graph.traversal();return;", database));ResultSet resultSet = client.submit("return graph.schemas().stream().map{s -> s.getName()};");StringBuilder entity_str = new StringBuilder("实体有:");StringBuilder rel_str = new StringBuilder("关系有:");List<String> resultList = resultSet.all().get().stream().map(Result::getString).collect(Collectors.toList());List<String> entities = new ArrayList<>();List<String> rels = new ArrayList<>();for(String table:resultList){ResultSet typeSet = client.submit(String.format("return graph.getSchema('%s').getType().toString();", table));List<String> typeList = typeSet.all().get().stream().map(Result::getString).collect(Collectors.toList());if(typeList.get(0).equals("VERTEX")){ //实体类型StringBuilder entity = new StringBuilder();entity.append(table);ResultSet prosSet = client.submit(String.format("return graph.getSchema('%s').getProperties().stream().map{s -> s.getName()};", table));List<String> prosList = prosSet.all().get().stream().map(Result::getString).collect(Collectors.toList());entity.append("(");for(int i = 0; i < prosList.size(); i++) {String pro = prosList.get(i);if (pro.equals("_id"))continue;entity.append(pro);if(i < prosList.size() - 1)entity.append(',');}entity.append(")");entities.add(entity.toString());}else if(typeList.get(0).equals("EDGE")){ResultSet relationSet = client.submit(String.format("return g.E().hasLabel('%s').valueMap('h_table', 'r', 't_table').dedup();", table));List<Result> relationList = relationSet.all().get();for(Result rel:relationList){Map<String, String> a_rel = rel.get(Map.class);String h_table = a_rel.get("h_table");String t_table = a_rel.get("t_table");String r = a_rel.get("r");rels.add(String.format("%s--[r:%s]->%s", h_table, r, t_table));}}}entity_str.append(String.join(",", entities));rel_str.append(String.join(",", rels));System.out.println(entity_str);System.out.println(rel_str);
client.close();} catch (GridGraphAuthenticationException e) {throw new RuntimeException(e);}}
}

Python代码展示:

#encoding=utf8
from gremlin_python.driver import client
if __name__ == '__main__':client = client.Client('ws://localhost:9999/gremlin', None, username='', password='')database = "实体1"prefix = f'graph=GridGraphFactory.openGraph("{database}");g=graph.traversal();'tables = client.submit(prefix + "graph.schemas().stream().map{s -> s.getName()};").all().result()entities, rels = [], []for table in tables:tp = client.submit(prefix + f"graph.getSchema('{table}').getType().toString();").one()[0]if tp == 'VERTEX': #实体类型pros = client.submit(prefix + f"graph.getSchema('{table}')" + ".getProperties().stream().map{s -> s.getName()};").all().result()pros = [pro for pro in pros if pro != '_id']entities.append(f"{table}({','.join(pros)})")elif tp == 'EDGE':rs = client.submit(prefix + f"g.E().hasLabel('{table}').valueMap('h_table', 'r', 't_table').dedup();").all().result()for mp in rs:rels.append(f"{mp['h_table']}--[r:{mp['r']}]-->{mp['t_table']}")
'''            也可以用:g.E().hasLabel('关系').toList().stream().map{e -> e.outVertex().schema().getName()+"--[r:"+e.values('r').next()+ "]-->"  +  e.inVertex().schema().getName()}.distinct()
'''print("实体有:" + ",".join(entities))print("关系有:" + ",".join(rels))client.close()

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.pswp.cn/pingmian/84487.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

[论文阅读]TrustRAG: Enhancing Robustness and Trustworthiness in RAG

TrustRAG: Enhancing Robustness and Trustworthiness in RAG [2501.00879] TrustRAG: Enhancing Robustness and Trustworthiness in Retrieval-Augmented Generation 代码&#xff1a;HuichiZhou/TrustRAG: Code for "TrustRAG: Enhancing Robustness and Trustworthin…

鸿蒙Next仓颉语言开发实战教程:店铺详情页

各位好&#xff0c;幽蓝君又来分享仓颉开发教程了&#xff0c;今天的内容是店铺详情页&#xff1a; 这个页面的内容看似简单&#xff0c;其实有很多小细节需要注意&#xff0c;主要还是让大家熟悉List容器的使用。 整个页面由导航栏和List容器两大部分组成&#xff0c;导航栏我…

FEMFAT许可使用数据分析工具介绍

在高度竞争和快速变化的工程仿真领域&#xff0c;数据驱动的决策变得越来越重要。为了更好地了解FEMFAT许可的使用情况、提高资源利用率、优化工作流程&#xff0c;FEMFAT许可使用数据分析工具应运而生。本文将为您介绍这款强大的工具&#xff0c;助您轻松驾驭FEMFAT许可数据&a…

大模型原理面试题及参考答案

目录 什么是大语言模型(LLM)?它与传统语言模型的本质差异在哪里? 自回归模型(autoregressive)与掩码语言模型(masked LM)的异同是什么?各适合于哪些任务? Transformer 的核心构件——多头自注意力机制如何捕捉长距离依赖? 位置编码(positional encoding)的作用…

Gartner<Reference Architecture Brief: Data Integration>学习心得

数据集成参考架构解析 引言 在当今数字化时代,数据已成为企业最宝贵的资产之一。随着企业规模的不断扩大和业务的日益复杂,数据来源也变得多样化,包括客户关系管理(CRM)、企业资源规划(ERP)、人力资源管理(HR)和市场营销等领域的运营系统。这些系统虽然在其特定功能…

JAVASE:方法

JavaSE 方法详解 一、方法的核心概念 方法&#xff08;Method&#xff09;是一组执行特定任务的语句集合&#xff0c;它将代码逻辑封装为可复用的单元&#xff0c;提高代码的模块化和可维护性。 方法的组成&#xff1a; [修饰符] 返回类型 方法名([参数列表]) {// 方法体[r…

MXNet-cu101 + CUDA 10.1 在 Windows 11 上启用 GPU 的完整指南

一、报错信息 (pytorch) C:\Users\Administrator\Desktop\test>D:/conda/anaconda3/envs/pytorch/python.exe c:/Users/Administrator/Desktop/test/test.py Traceback (most recent call last): File “c:/Users/Administrator/Desktop/test/test.py”, line 1, in import…

Python基础数据类型与运算符全面解析

Python作为一门动态类型语言&#xff0c;拥有丰富的内置数据类型和运算符系统&#xff0c;构成了编程的基础。本文将深入介绍Python核心数据类型的基本概念、特点及使用方法&#xff0c;并系统梳理运算符的分类、优先级和实际应用示例&#xff0c;帮助开发者全面掌握Python的基…

Mysql分区(单服务器应对大数据量方案)

参考资料&#xff1a; 参考视频 参考博客 分区的复杂操作 参考资料 概述&#xff1a; 这里只讲实操&#xff0c;不讲原理&#xff0c;看原理请看参考资料Mysql自5.1后支持分区&#xff0c;在Mysql8之后只有InnoDB支持分区&#xff0c;Mysiam不支持分区本例只是一个简单的说…

[Java恶补day22] 240. 搜索二维矩阵Ⅱ

编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target 。该矩阵具有以下特性&#xff1a; 每行的元素从左到右升序排列。 每列的元素从上到下升序排列。 示例 1&#xff1a; 输入&#xff1a;matrix [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17…

基于Master-Slave主从博弈论的储能与能源协调算法matlab仿真

目录 1.课题概述 2.系统仿真结果 3.核心程序 4.系统仿真参数 5.系统原理简介 6.参考文献 7.完整工程文件 1.课题概述 基于Master-Slave主从博弈论的储能与能源协调算法matlab仿真.主从博弈&#xff08;Stackelberg Game&#xff09;是一种具有层级决策结构的博弈模型&am…

vue-print-nb 打印相关问题

一、背景与解决方案 1、ElementUI表格打印通病&#xff0c;均面临边框丢失、宽度超出问题&#xff1a;相关解决代码有注释&#xff1b; 2、大多数情况下不会打印页眉页脚的日期、网址、未配置popTitle显示的undefined&#xff1a;相关解决代码有注释&#xff1b; 3、打印预览页…

Agent应用案例精选,以及主流Agent框架开源项目推荐

一、Agent技术概述 在人工智能领域,Agent(智能体)是指能够感知环境、自主决策并执行动作以实现特定目标的智能系统。随着大语言模型(LLM)的快速发展,基于LLM的Agent系统已成为当前AI研究的热点方向,为复杂任务解决提供了全新范式。 Agent的核心特征 自主性(Autonomy): 能够…

Linux下基础IO

1 文件 这里首先得理解一下文件&#xff0c;文件存放在磁盘中&#xff08;磁盘是永久性存储介质&#xff0c;是一种外设&#xff0c;也是一种输入输出设备&#xff09;&#xff0c;磁盘上的文件的所有操作&#xff0c;都是对外设的输入和输出简称IO&#xff0c;linux下一切皆⽂…

云原生核心技术 (6/12): K8s 从零到一:使用 Minikube/kind 在本地搭建你的第一个 K8s 集群

摘要 本文是一篇保姆级的实践指南&#xff0c;旨在解决学习 Kubernetes (K8s) 时“环境搭建难”的头号痛点。我们将对比分析 Minikube、kind、K3s 和 Docker Desktop Kubernetes 等主流本地 K8s 环境方案的优缺点&#xff0c;帮助你选择最适合自己的工具。随后&#xff0c;文章…

线程运行的现象和相关指令

一.多个线程运行的现象 1.规律 交替执行谁先谁后&#xff0c;不由我们控制 2.举例 Slf4j(topic "c.Test6") public class Test06 {public static void main(String[] args) {//创建并运行线程1new Thread(()->{while (true){log.debug("running");…

Windows网络配置避坑指南

Windows网络配置避坑指南 一、网络配置是什么?防火墙的“信任开关”二、何时需要手动切换网络配置文件?​必需切换的场景高危!绝对禁止选错的两个场景三、3种切换指南(Win10/11通用)方法1:图形化操作(推荐小白)​方法2:用PowerShell强制切换方法3:注册表底层修改(应…

基于ThinkPHP8.*的后台管理框架--Veitool框架学习使用

基于ThinkPHP8.*的后台管理框架--Veitool框架学习使用 一、安装部署二、目录结构 一、安装部署 环境要求 Linux、Unix、macOS、Windows Nginx、Apache、IIS PHP > 8.1.0 MySQL > 5.7 下载地址 官网下载&#xff1a;https://www.veitool.com/download 境内仓库&#xff…

Java多线程通信核心机制详解

在Java中&#xff0c;多线程通信与协作主要通过以下几种核心机制实现&#xff0c;每种方式适用于不同的并发场景&#xff1a; &#x1f504; 一、共享变量同步控制&#xff08;基础方式&#xff09; // 使用volatile保证可见性 private volatile boolean flag false;// 线程A…

Django知识-视图

视图设置 一个视图函数&#xff0c;简称视图&#xff0c;是一个简单的Python 函数&#xff0c;它接受Web请求并且返回Web响应。代码写在哪里也无所谓&#xff0c;只要它在你的应用目录下面。但是为了方便视图一般被定义在“应用/views.py”文件中。 视图的第一个参数必须为Ht…