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
繁體地址,請注明出處:http://hk.pswp.cn/pingmian/84487.shtml
英文地址,請注明出處:http://en.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…