Appearance
OpenSPG Schema DSL 解析与图谱构建详解
目录
1. 概述
1.1 什么是Schema DSL?
Schema DSL (Domain Specific Language) 是OpenSPG提供的一种声明式语言,用于定义知识图谱的语义结构。通过编写.schema文件或DSL字符串,用户可以方便地定义实体类型、属性、关系和逻辑规则。
1.2 为什么需要Schema DSL?
- 简洁直观:相比Java API,DSL更接近自然语言描述
- 易于维护:Schema定义集中在文本文件中,便于版本管理
- 快速原型:通过文本编辑器即可快速构建Schema原型
- 跨语言:DSL文本可以被不同语言的客户端解析使用
1.3 解析流程概览
Schema DSL文本
↓
[阶段1] DSL解析 (SchemaScriptTranslateUtil)
↓
SchemaModel (中间模型)
↓
[阶段2] 模型转换 (SchemaModelConvertor)
↓
BaseAdvancedType (Schema对象)
↓
[阶段3] 预处理 (PreProcessStage: 验证、继承)
↓
[阶段4] 持久化 (ProcessStage: 数据库)
↓
[阶段5] 同步 (PostProcessStage: 图存储、搜索引擎)
↓
知识图谱结构2. Schema DSL格式详解
2.1 基本语法结构
namespace <命名空间>
<类型名>(<中文名>): <类型类别>
desc: <描述信息>
properties:
<属性名>(<中文名>): <属性类型>
index: <索引类型>
constraint: <约束条件>
rule: [[ <逻辑规则> ]]
properties:
<子属性名>(<中文名>): <子属性类型>
relations:
<关系名>(<中文名>): <目标类型>
properties:
<关系属性名>(<中文名>): <属性类型>
rule: [[ <逻辑规则> ]]2.2 类型类别
| 类别 | DSL关键字 | 说明 | 示例 |
|---|---|---|---|
| 实体类型 | EntityType | 现实世界中的对象 | 人物、公司、产品 |
| 概念类型 | ConceptType | 抽象概念分类 | 行政区划、会员等级 |
| 事件类型 | EventType | 发生的事件 | 交易事件、登录事件 |
| 标准类型 | StandardType | 标准化数据类型 | 手机号、邮箱、时间戳 |
2.3 基础数据类型
Text- 文本字符串Integer- 整数Float- 浮点数Boolean- 布尔值Timestamp- 时间戳
2.4 索引类型
index: Text # 全文检索索引
index: KeyWord # 精确匹配索引
index: Vector # 向量索引
index: FullText # 全文本索引
index: TextAndVector # 文本+向量混合索引2.5 约束类型
constraint: NotNull # 非空约束
constraint: Unique # 唯一约束
constraint: MultiValue # 多值约束
constraint: Enum="值1,值2,值3" # 枚举约束
constraint: RangeConstraint(0, +) # 范围约束(最小值,最大值)
constraint: Regular="正则表达式" # 正则表达式约束
constraint: NotNull,MultiValue # 组合约束2.6 逻辑规则
逻辑规则使用KGDSL语言编写,包裹在 [[ ]] 中:
rule: [[
Define (s:Person)-[p:closeRel]->(o:Person) {
GraphStructure {
(s)-[p1:parent]->(o)
(s)-[p2:children]->(o)
}
Rule {
// 推理规则
}
}
]]2.7 完整示例
schema
namespace DEFAULT
Person(自然人): EntityType
desc: 表示现实世界中的自然人
properties:
age(年龄): Integer
constraint: RangeConstraint(0, 150)
mobile(联系方式): STD.ChinaMobile
home(家庭住址): Administration
workCompany(就职公司): Company
properties:
confidence(置信度): Text
relations:
parent(父母): Person
children(子女): Person
semantics: inverseOf parent
closeRel(近亲): Person
rule: [[
Define (s:DEFAULT.Person)-[p:closeRel]->(o:DEFAULT.Person) {
GraphStructure {
(s)-[p1:parent]->(o)
(s)-[p2:children]->(o)
}
}
]]
Company(公司): EntityType
properties:
name(公司名称): Text
index: Text
constraint: NotNull
establishDate(成立日期): STD.Timestamp
industry(所属行业): Text
Administration(行政区划): ConceptType
conceptLayerConfig:
hypernymPredicate: locateAt
layerNames: ["国","省","市","区"]
ExchangeGoods(兑换商品事件): EventType
eventTime(发生时间): STD.Timestamp
subject(主体): AlipayUser, AlipayMember
object(客体): Goods3. 解析流程五阶段
3.1 阶段1:DSL文本解析
负责类: SchemaScriptTranslateUtil
位置: server/biz/schema/src/main/java/com/antgroup/openspg/server/biz/schema/model/SchemaScriptTranslateUtil.java
核心方法:
java
public static SchemaModel translateScript(String script)工作流程:
解析namespace声明
javaString firstLine = lines.get(0); if (firstLine.contains("namespace")) { namespace = firstLine.replace("namespace", "").trim(); }按缩进层级分组
- 缩进0:类型声明行
- 缩进1:properties、relations、desc等关键字
- 缩进2:具体的属性/关系定义
- 缩进3+:属性配置(index、constraint、rule等)
解析类型声明
java// 格式:TypeName(ChineseName): TypeCategory Person(自然人): EntityType使用正则提取:
name,nameZh,type解析属性列表
- 识别
properties:关键字 - 逐行解析属性定义
- 提取index、constraint、rule配置
- 支持嵌套子属性
- 识别
解析关系列表
- 识别
relations:关键字 - 解析关系定义及其属性
- 提取逻辑规则
- 识别
构建中间模型
javaSchemaModel schemaModel = new SchemaModel(); schemaModel.setNamespace(namespace); schemaModel.setNodeTypeModels(nodeTypeList);
输出: SchemaModel 对象
java
public class SchemaModel {
private String namespace; // 命名空间
private List<NodeTypeModel> nodeTypeModels; // 类型列表
}
public class NodeTypeModel {
private String name; // 类型名
private String nameZh; // 中文名
private String type; // 类型类别
private String desc; // 描述
private List<PropertyModel> properties; // 属性列表
private List<EdgeTypeModel> relations; // 关系列表
}3.2 阶段2:模型转换
负责类: SchemaModelConvertor
位置: server/biz/schema/src/main/java/com/antgroup/openspg/server/biz/schema/model/SchemaModelConvertor.java
核心方法:
java
public static BaseAdvancedType convert2NodeTypeModel(NodeTypeModel model)转换过程:
根据类型创建对应的Java对象
javaswitch (SPGTypeEnum.valueOf(nodeTypeModel.getType())) { case ENTITY_TYPE: return new EntityType(...); case CONCEPT_TYPE: return new ConceptType(...); case EVENT_TYPE: return new EventType(...); case STANDARD_TYPE: return new StandardType(...); }转换属性定义
PropertyModel→Property- 创建
SPGTypeRef引用 - 构建约束对象
Constraint - 设置索引配置
PropertyAdvancedConfig
转换关系定义
EdgeTypeModel→Relation- 建立主体-客体类型引用
- 转换关系属性
设置逻辑规则
javaif (propertyModel.getRule() != null) { property.setLogicalRule( new LogicalRule(null, null, rule.getContent()) ); }
输出: BaseAdvancedType 对象(EntityType、ConceptType等)
3.3 阶段3:预处理阶段
负责类: PreProcessStage
位置: server/core/schema/service/src/main/java/com/antgroup/openspg/server/core/schema/service/alter/stage/PreProcessStage.java
核心职责:
加载在线Schema
- 查询数据库中已发布的Schema版本
- 构建
SchemaMap索引
Schema约束检查 (
SchemaAlterChecker)- 类型名称唯一性检查
- 属性/关系名称冲突检查
- 父类型存在性验证
- 约束兼容性验证
- 循环继承检测
完成继承属性 (
completeInheritedProperty)java// 遍历父类型链 while (parentTypeIdentifier != null) { BaseSPGType parentType = getParentType(parentTypeIdentifier); parentTypes.add(parentType); parentTypeIdentifier = parentType.getParentTypeInfo() .getParentTypeIdentifier(); } // 添加继承的属性到子类型 for (BaseSPGType parentType : parentTypes) { for (Property property : parentType.getProperties()) { if (!property.getInherited()) { Property newProp = PropertyUtils.inheritProperty( spgType.toRef(), property ); spgType.getProperties().add(newProp); } } }添加内置属性 (
BuiltInPropertyHandler)- 为EventType添加:eventTime、subject、object
- 为所有高级类型添加:id、name等
关键验证规则:
java
// 1. 类型存在性
if (parentType == null || parentType.isDelete()) {
throw SchemaException.spgTypeNotExist(parentTypeIdentifier);
}
// 2. 属性唯一性
Set<String> propertyNames = new HashSet<>();
for (Property property : spgType.getProperties()) {
if (!propertyNames.add(property.getName())) {
throw SchemaException.propertyDuplicate(property.getName());
}
}
// 3. 约束兼容性
if (constraint.getConstraintTypeEnum() == RANGE) {
if (!property.getObjectTypeRef().isNumericType()) {
throw SchemaException.constraintNotCompatible();
}
}3.4 阶段4:持久化阶段
负责类: ProcessStage
位置: server/core/schema/service/src/main/java/com/antgroup/openspg/server/core/schema/service/alter/stage/ProcessStage.java
核心职责:
分配Ontology ID和版本号
javaOntologyIdHandler.assignOntologyId(spgType); spgType.setVersion(nextVersion);持久化到数据库
根据
AlterOperation执行不同操作:javaswitch (spgType.getAlterOperation()) { case CREATE: spgTypeService.create(spgType); break; case UPDATE: spgTypeService.update(spgType); break; case DELETE: spgTypeService.delete(spgType); break; }数据库表结构
SPG_TYPE表 (SPG类型表):
sqlCREATE TABLE spg_type ( id BIGINT PRIMARY KEY, ontology_id BIGINT, name VARCHAR(255), name_zh VARCHAR(255), namespace VARCHAR(255), type VARCHAR(50), -- ENTITY_TYPE, CONCEPT_TYPE等 parent_type_id BIGINT, description TEXT, version INT, status VARCHAR(20), create_time TIMESTAMP, update_time TIMESTAMP );SPG_PROPERTY表 (属性表):
sqlCREATE TABLE spg_property ( id BIGINT PRIMARY KEY, ontology_id BIGINT, name VARCHAR(255), name_zh VARCHAR(255), subject_type_id BIGINT, -- 所属类型ID object_type_id BIGINT, -- 属性值类型ID multi_value BOOLEAN, index_type VARCHAR(50), constraint_json TEXT, logical_rule TEXT, inherited BOOLEAN, create_time TIMESTAMP );SPG_RELATION表 (关系表):
sqlCREATE TABLE spg_relation ( id BIGINT PRIMARY KEY, ontology_id BIGINT, name VARCHAR(255), name_zh VARCHAR(255), subject_type_id BIGINT, -- 主体类型ID object_type_id BIGINT, -- 客体类型ID multi_value BOOLEAN, logical_rule TEXT, create_time TIMESTAMP );SPG_CONSTRAINT表 (约束表):
sqlCREATE TABLE spg_constraint ( id BIGINT PRIMARY KEY, property_id BIGINT, constraint_type VARCHAR(50), -- NOT_NULL, ENUM, RANGE等 constraint_config TEXT, -- JSON配置 create_time TIMESTAMP );
3.5 阶段5:同步阶段
负责类: PostProcessStage
位置: server/core/schema/service/src/main/java/com/antgroup/openspg/server/core/schema/service/alter/stage/PostProcessStage.java
核心职责:
5.1 同步到图存储
GraphStorageSyncer - 将Schema同步到Neo4j/TuGraph
Neo4j同步示例:
cypher
-- 1. 创建节点标签(对应EntityType)
CREATE CONSTRAINT IF NOT EXISTS
FOR (n:DEFAULT_Person)
REQUIRE n.id IS UNIQUE;
-- 2. 创建属性索引
CREATE INDEX IF NOT EXISTS
FOR (n:DEFAULT_Person)
ON (n.name);
CREATE FULLTEXT INDEX IF NOT EXISTS person_fulltext
FOR (n:DEFAULT_Person)
ON EACH [n.name, n.description];
-- 3. 创建关系类型(对应Relation)
// 关系类型在Neo4j中是隐式的,通过创建关系实例定义
// 例如:CREATE (:DEFAULT_Person)-[:parent]->(:DEFAULT_Person)TuGraph同步示例:
json
// 1. 创建Vertex Label
{
"label": "DEFAULT_Person",
"type": "VERTEX",
"properties": [
{"name": "id", "type": "STRING", "primary": true},
{"name": "name", "type": "STRING", "index": true},
{"name": "age", "type": "INT32"},
{"name": "mobile", "type": "STRING"}
]
}
// 2. 创建Edge Label
{
"label": "parent",
"type": "EDGE",
"constraints": [
["DEFAULT_Person", "DEFAULT_Person"]
],
"properties": []
}同步代码:
java
public void syncToGraphStore(ProjectSchema schema) {
GraphStoreClient client = GraphStoreClientDriverManager.getClient(
graphStoreUrl
);
SPGSchemaAlterCmd cmd = new SPGSchemaAlterCmd();
cmd.setSchema(schema);
// 执行Schema同步
client.alterSchema(cmd);
}5.2 同步到搜索引擎
SearchEngineSyncer - 将Schema同步到Elasticsearch
Elasticsearch索引映射:
json
PUT /default_person_idx
{
"mappings": {
"properties": {
"id": {
"type": "keyword"
},
"name": {
"type": "text",
"analyzer": "ik_max_word",
"fields": {
"keyword": {
"type": "keyword"
}
}
},
"age": {
"type": "integer"
},
"mobile": {
"type": "keyword"
},
"description": {
"type": "text",
"analyzer": "ik_smart"
},
"embedding": {
"type": "dense_vector",
"dims": 768,
"index": true,
"similarity": "cosine"
}
}
},
"settings": {
"number_of_shards": 3,
"number_of_replicas": 1
}
}索引类型映射:
| SPG索引类型 | Elasticsearch类型 | 说明 |
|---|---|---|
TEXT | text | 全文检索,使用分词器 |
EXACT | keyword | 精确匹配 |
VECTOR | dense_vector | 向量搜索 |
TEXT_AND_VECTOR | text + dense_vector | 混合搜索 |
RANGE | integer/float | 范围查询 |
4. 核心代码详解
4.1 SchemaScriptTranslateUtil 解析器
完整解析流程:
java
public static SchemaModel translateScript(String script) {
SchemaModel schemaModel = new SchemaModel();
// 1. 分割行
List<String> lines = Splitter.on(LINE_SEPARATOR)
.omitEmptyStrings()
.splitToList(script.trim());
// 2. 解析namespace
String firstLine = lines.get(0);
if (firstLine.contains("namespace")) {
String namespace = firstLine.replace("namespace", "").trim();
schemaModel.setNamespace(namespace);
}
// 3. 按类型分组
List<NodeTypeModel> nodeTypeList = new ArrayList<>();
List<String> typeList = null;
for (int i = 1; i < lines.size(); i++) {
String line = lines.get(i);
// 跳过空行和注释
if (StringUtils.isBlank(line) || line.startsWith("#")) {
continue;
}
int indentCount = indentCount(line); // 计算缩进
// 缩进为0表示新的类型声明
if (indentCount == 0) {
if (CollectionUtils.isNotEmpty(typeList)) {
// 处理上一个类型
NodeTypeModel nodeTypeModel = toNodeTypeModel(namespace, typeList);
nodeTypeList.add(nodeTypeModel);
}
typeList = new ArrayList<>();
typeList.add(line);
} else {
// 累积类型定义的行
typeList.add(line);
}
}
schemaModel.setNodeTypeModels(nodeTypeList);
return schemaModel;
}缩进计算:
java
private static int indentCount(String input) {
int count = 0;
for (char c : input.toCharArray()) {
if (c == '\t') {
count = count + 4; // Tab等于4个空格
} else if (c == ' ') {
count++;
} else {
break; // 遇到非空白字符停止
}
}
return count;
}类型信息提取:
java
private static MutableTriple<String, String, String> getType(String s) {
// 输入格式: Person(自然人): EntityType
// 输出: (Person, 自然人, EntityType)
List<String> list = Splitter.on(CharMatcher.anyOf("():"))
.omitEmptyStrings()
.trimResults()
.splitToList(s);
return MutableTriple.of(
list.get(0), // name
list.get(1), // nameZh
list.get(2) // type
);
}属性解析:
java
private static List<PropertyModel> getPropertyModelList(
String namespace, List<String> propStrList) {
List<PropertyModel> result = new ArrayList<>();
PropertyModel last = null;
String currentStep = null; // PROP, RULE等状态
for (String line : propStrList) {
int currentLineCount = indentCount(line);
// 识别属性定义行: name(nameZh): Type
if (line.contains("):")) {
MutableTriple<String, String, String> propType = getType(line);
PropertyModel propertyModel = new PropertyModel();
propertyModel.setName(propType.getLeft());
propertyModel.setNameZh(propType.getMiddle());
propertyModel.setType(propType.getRight());
last = propertyModel;
result.add(propertyModel);
}
// 解析index配置
if (line.contains("index:") && last != null) {
String scriptName = Splitter.on(":")
.trimResults()
.splitToList(line)
.get(1);
last.setIndex(IndexTypeEnum.getByScriptName(scriptName).name());
}
// 解析constraint配置
if (line.contains("constraint:") && last != null) {
String constraintStr = Splitter.on(":")
.trimResults()
.splitToList(line)
.get(1);
Constraint constraint = parseConstraint(constraintStr);
last.setConstraint(constraint);
}
// 解析rule配置
if (line.trim().startsWith("rule:")) {
currentStep = "RULE";
// 收集规则内容...
}
}
return result;
}约束解析:
java
private static void parseConstraintForProperty(
String expression, List<BaseConstraintItem> constraintItems) {
// 1. 解析带值的约束 (Enum, Regular)
Pattern pattern = Pattern.compile(
"(Enum|Regular)\\s*?=\\s*?\"([^\"]+)\"",
Pattern.CASE_INSENSITIVE
);
Matcher matcher = pattern.matcher(expression);
while (matcher.find()) {
String constraintType = matcher.group(1).toLowerCase();
String constraintValue = matcher.group(2).trim();
if ("enum".equals(constraintType)) {
String[] enumValues = constraintValue.split(",");
List<String> values = Arrays.stream(enumValues)
.map(String::trim)
.collect(Collectors.toList());
constraintItems.add(new EnumConstraint(values));
} else if ("regular".equals(constraintType)) {
constraintItems.add(new RegularConstraint(constraintValue));
}
// 从表达式中移除已解析的部分
expression = expression.replaceFirst(matcher.group(), "");
}
// 2. 解析标志型约束 (MultiValue, NotNull)
String[] array = expression.split(",");
for (String cons : array) {
cons = cons.trim();
if ("multivalue".equalsIgnoreCase(cons)) {
constraintItems.add(new MultiValConstraint());
} else if ("notnull".equalsIgnoreCase(cons)) {
constraintItems.add(new NotNullConstraint());
}
}
}4.2 SchemaAlterPipeline 处理管道
管道设计:
java
@Slf4j
public class SchemaAlterPipeline {
/** 处理阶段列表 */
private List<BaseAlterStage> stages;
/**
* 执行管道
*/
public void run(SchemaAlterContext context) {
for (BaseAlterStage stage : stages) {
log.info("start to execute stage: {}", stage.getName());
try {
stage.execute(context);
log.info("finish to execute stage: {}", stage.getName());
} catch (Exception e) {
log.error("stage {} execution failed", stage.getName(), e);
throw e;
}
}
}
}阶段接口:
java
public abstract class BaseAlterStage {
private final String name;
public BaseAlterStage(String name) {
this.name = name;
}
/**
* 执行阶段逻辑
*/
public abstract void execute(SchemaAlterContext context);
public String getName() {
return name;
}
}Spring配置:
java
@Configuration
public class SchemaAlterConfig {
@Bean
public SchemaAlterPipeline schemaAlterPipeline(
PreProcessStage preProcessStage,
ProcessStage processStage,
PostProcessStage postProcessStage) {
SchemaAlterPipeline pipeline = new SchemaAlterPipeline();
pipeline.setStages(Arrays.asList(
preProcessStage, // 预处理
processStage, // 持久化
postProcessStage // 同步
));
return pipeline;
}
}4.3 SchemaAlterContext 上下文
上下文结构:
java
public class SchemaAlterContext {
/** 项目信息 */
private Project project;
/** 已发布的Schema(在线版本) */
private ProjectSchema releasedSchema;
/** 待修改的Schema(草稿) */
private SchemaDraft alterSchema;
/** 在线Schema索引 */
private SchemaMap onlineSchemaMap;
/** 修改Schema索引 */
private SchemaMap alterSchemaMap;
/** 操作用户 */
private String operator;
/** 操作时间 */
private Date operateTime;
// Getters and Setters...
}5. 完整示例
5.1 完整Schema DSL示例
schema
namespace DEFAULT
# ==================== 标准类型定义 ====================
ChinaMobile(中国手机号): StandardType
spreadable: true
constraintItems: Regular="^1[3-9]\\d{9}$"
Timestamp(时间戳): StandardType
spreadable: true
# ==================== 概念类型定义 ====================
Administration(行政区划): ConceptType
desc: 中国行政区划体系
conceptLayerConfig:
hypernymPredicate: locateAt
layerNames: ["国","省","市","区"]
MemberDegree(会员等级): ConceptType
desc: 会员等级分类
conceptLayerConfig:
hypernymPredicate: isA
conceptMultiVersionConfig:
pattern: yyyyMMdd
maxVersion: 3
ttl: 30
# ==================== 实体类型定义 ====================
Company(公司): EntityType
desc: 企业组织实体
properties:
name(公司名称): Text
index: Text
constraint: NotNull
establishDate(成立日期): Timestamp
index: KeyWord
industry(所属行业): Text
index: Text
registeredCapital(注册资本): Float
constraint: RangeConstraint(0, +)
Person(自然人): EntityType
desc: 表示现实世界中的自然人
properties:
age(年龄): Integer
constraint: RangeConstraint(0, 150)
mobile(联系方式): ChinaMobile
index: KeyWord
home(家庭住址): Administration
desc: 居住地址
workCompany(就职公司): Company
desc: 工作单位
properties:
confidence(置信度): Text
desc: 信息置信度
startDate(入职日期): Timestamp
relations:
parent(父母): Person
desc: 父母关系
children(子女): Person
desc: 子女关系,与parent互逆
semantics: inverseOf parent
closeRel(近亲): Person
desc: 近亲关系,通过父母和子女关系推导
rule: [[
Define (s:DEFAULT.Person)-[p:closeRel]->(o:DEFAULT.Person) {
GraphStructure {
(s)-[p1:parent]->(o)
(s)-[p2:children]->(o)
}
Rule {
// 推理规则:父母和子女都是近亲
}
}
]]
AlipayUser(支付宝用户): EntityType
parent: Person
desc: 支付宝平台用户,继承Person的所有属性
properties:
regTime(注册时间): Timestamp
constraint: NotNull
regMobile(注册手机号): ChinaMobile
constraint: NotNull
regAddress(注册地址): Administration
regDevice(注册设备): Device
relations:
collectApp(收藏的小程序): App
properties:
collectTime(收藏时间): Timestamp
AlipayMember(支付宝会员): EntityType
parent: AlipayUser
desc: 支付宝会员用户
properties:
degree(会员等级): MemberDegree
constraint: NotNull
mark(信誉分): Integer
constraint: RangeConstraint(0, 1000)
rule: [[
Define (s:DEFAULT.AlipayMember)-[p:mark]->(o:Integer) {
GraphStructure {}
Rule {
// 默认信誉分为100
o = 100
}
}
]]
Device(设备): EntityType
properties:
deviceId(设备ID): Text
index: KeyWord
constraint: NotNull,Unique
deviceType(设备类型): Text
constraint: Enum="iOS,Android,Windows,Mac"
App(应用小程序): EntityType
properties:
appId(应用ID): Text
index: KeyWord
constraint: NotNull,Unique
appName(应用名称): Text
index: Text
Goods(商品): EntityType
properties:
goodsId(商品ID): Text
constraint: NotNull,Unique
goodsName(商品名称): Text
index: Text
price(价格): Float
constraint: RangeConstraint(0, +)
category(类别): Text
index: KeyWord
# ==================== 事件类型定义 ====================
ExchangeGoods(兑换商品事件): EventType
desc: 用户使用积分兑换商品的事件
eventTime(发生时间): Timestamp
subject(主体): AlipayUser, AlipayMember
object(客体): Goods
properties:
pointsUsed(使用积分): Integer
constraint: RangeConstraint(0, +)
exchangeChannel(兑换渠道): Text
constraint: Enum="App,Web,MiniProgram"5.2 Java API调用示例
java
package com.example.openspg.schema;
import com.antgroup.openspg.server.api.facade.dto.schema.request.SchemaAlterRequest;
import com.antgroup.openspg.server.biz.schema.SchemaManager;
import com.antgroup.openspg.server.biz.schema.model.SchemaModel;
import com.antgroup.openspg.server.biz.schema.model.SchemaScriptTranslateUtil;
import com.antgroup.openspg.core.schema.model.alter.SchemaDraft;
import com.antgroup.openspg.core.schema.model.type.BaseAdvancedType;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
/**
* Schema DSL 解析完整示例
*/
public class SchemaDSLExample {
private final SchemaManager schemaManager;
public SchemaDSLExample(SchemaManager schemaManager) {
this.schemaManager = schemaManager;
}
/**
* 从DSL文件创建Schema
*/
public void createSchemaFromDSLFile(String dslFilePath, Long projectId)
throws IOException {
// ========== 1. 读取DSL文件 ==========
String dslContent = Files.readString(Paths.get(dslFilePath));
System.out.println("读取Schema DSL文件:" + dslFilePath);
// ========== 2. 解析DSL为中间模型 ==========
SchemaModel schemaModel = SchemaScriptTranslateUtil.translateScript(dslContent);
System.out.println("解析完成,namespace: " + schemaModel.getNamespace());
System.out.println("类型数量: " + schemaModel.getNodeTypeModels().size());
// ========== 3. 转换为Schema对象 ==========
List<BaseAdvancedType> spgTypes = schemaModel.getNodeTypeModels().stream()
.map(SchemaModelConvertor::convert2NodeTypeModel)
.collect(Collectors.toList());
// 设置为创建操作
spgTypes.forEach(type ->
type.setAlterOperation(AlterOperationEnum.CREATE)
);
// ========== 4. 构建Schema草稿 ==========
SchemaDraft schemaDraft = new SchemaDraft();
schemaDraft.setAlterSpgTypes(spgTypes);
// ========== 5. 提交Schema修改请求 ==========
SchemaAlterRequest request = new SchemaAlterRequest();
request.setProjectId(projectId);
request.setSchemaDraft(schemaDraft);
System.out.println("提交Schema修改请求...");
schemaManager.alterSchema(request);
System.out.println("Schema创建成功!");
// ========== 6. 验证Schema ==========
ProjectSchema projectSchema = schemaManager.getProjectSchema(projectId);
System.out.println("验证:项目Schema中包含 " +
projectSchema.getSpgTypes().size() + " 个类型");
// 打印所有类型
for (BaseSPGType spgType : projectSchema.getSpgTypes()) {
System.out.println(" - " + spgType.getName() +
" (" + spgType.getNameZh() + "): " +
spgType.getSpgTypeEnum());
}
}
/**
* 从DSL字符串创建Schema
*/
public void createSchemaFromDSLString(Long projectId) {
// ========== 1. 定义DSL字符串 ==========
String dslContent = """
namespace DEMO
User(用户): EntityType
properties:
username(用户名): Text
index: KeyWord
constraint: NotNull,Unique
email(邮箱): Text
index: Text
constraint: Regular="^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"
age(年龄): Integer
constraint: RangeConstraint(0, 150)
relations:
follows(关注): User
properties:
followTime(关注时间): Timestamp
Post(帖子): EntityType
properties:
title(标题): Text
index: Text
constraint: NotNull
content(内容): Text
index: Text
createTime(创建时间): Timestamp
relations:
author(作者): User
Comment(评论): EntityType
properties:
content(评论内容): Text
index: Text
createTime(评论时间): Timestamp
relations:
post(所属帖子): Post
commenter(评论者): User
""";
// ========== 2. 解析并创建Schema ==========
SchemaModel schemaModel = SchemaScriptTranslateUtil.translateScript(dslContent);
List<BaseAdvancedType> spgTypes = schemaModel.getNodeTypeModels().stream()
.map(SchemaModelConvertor::convert2NodeTypeModel)
.peek(type -> type.setAlterOperation(AlterOperationEnum.CREATE))
.collect(Collectors.toList());
SchemaDraft schemaDraft = new SchemaDraft();
schemaDraft.setAlterSpgTypes(spgTypes);
SchemaAlterRequest request = new SchemaAlterRequest();
request.setProjectId(projectId);
request.setSchemaDraft(schemaDraft);
schemaManager.alterSchema(request);
System.out.println("从DSL字符串创建Schema成功!");
}
/**
* 更新Schema
*/
public void updateSchemaFromDSL(Long projectId) throws IOException {
// ========== 1. 获取现有Schema ==========
ProjectSchema existingSchema = schemaManager.getProjectSchema(projectId);
// ========== 2. 定义更新的DSL ==========
String updateDSL = """
namespace DEMO
User(用户): EntityType
properties:
username(用户名): Text
index: KeyWord
constraint: NotNull,Unique
email(邮箱): Text
index: Text
phoneNumber(手机号): Text
index: KeyWord
constraint: Regular="^1[3-9]\\d{9}$"
age(年龄): Integer
constraint: RangeConstraint(0, 150)
bio(个人简介): Text
index: Text
relations:
follows(关注): User
properties:
followTime(关注时间): Timestamp
blocks(屏蔽): User
""";
// ========== 3. 解析更新DSL ==========
SchemaModel updateModel = SchemaScriptTranslateUtil.translateScript(updateDSL);
// ========== 4. 对比并生成更新操作 ==========
List<BaseAdvancedType> updateTypes = new ArrayList<>();
for (NodeTypeModel nodeTypeModel : updateModel.getNodeTypeModels()) {
String typeName = nodeTypeModel.getName();
// 查找现有类型
BaseSPGType existingType = existingSchema.getByName(typeName);
if (existingType == null) {
// 新增类型
BaseAdvancedType newType = SchemaModelConvertor
.convert2NodeTypeModel(nodeTypeModel);
newType.setAlterOperation(AlterOperationEnum.CREATE);
updateTypes.add(newType);
} else {
// 更新类型
BaseAdvancedType updatedType = SchemaModelConvertor
.convert2NodeTypeModel(nodeTypeModel);
updatedType.setAlterOperation(AlterOperationEnum.UPDATE);
updatedType.setOntologyId(existingType.getOntologyId());
// 标记新增的属性
markNewProperties(updatedType, existingType);
updateTypes.add(updatedType);
}
}
// ========== 5. 提交更新 ==========
SchemaDraft updateDraft = new SchemaDraft();
updateDraft.setAlterSpgTypes(updateTypes);
SchemaAlterRequest request = new SchemaAlterRequest();
request.setProjectId(projectId);
request.setSchemaDraft(updateDraft);
schemaManager.alterSchema(request);
System.out.println("Schema更新成功!");
}
/**
* 标记新增的属性
*/
private void markNewProperties(
BaseAdvancedType updatedType,
BaseSPGType existingType) {
Set<String> existingPropNames = existingType.getProperties().stream()
.map(Property::getName)
.collect(Collectors.toSet());
for (Property property : updatedType.getProperties()) {
if (existingPropNames.contains(property.getName())) {
property.setAlterOperation(AlterOperationEnum.UPDATE);
} else {
property.setAlterOperation(AlterOperationEnum.CREATE);
}
}
}
/**
* Schema到DSL的反向转换
*/
public String schemaToDSL(Long projectId) {
// ========== 1. 获取Schema ==========
ProjectSchema projectSchema = schemaManager.getProjectSchema(projectId);
// ========== 2. 转换为SchemaModel ==========
SchemaModel schemaModel = new SchemaModel();
schemaModel.setNamespace(projectSchema.getNamespace());
List<NodeTypeModel> nodeTypeModels = projectSchema.getSpgTypes().stream()
.filter(type -> !type.isBuiltIn()) // 过滤内置类型
.map(this::convertToNodeTypeModel)
.collect(Collectors.toList());
schemaModel.setNodeTypeModels(nodeTypeModels);
// ========== 3. 生成DSL字符串 ==========
String dslString = SchemaScriptTranslateUtil.translateSchema(schemaModel);
System.out.println("生成的Schema DSL:");
System.out.println(dslString);
return dslString;
}
/**
* 导出Schema到文件
*/
public void exportSchemaToDSLFile(Long projectId, String outputPath)
throws IOException {
String dslContent = schemaToDSL(projectId);
Files.writeString(Paths.get(outputPath), dslContent);
System.out.println("Schema已导出到: " + outputPath);
}
}5.3 REST API调用示例
bash
# 1. 通过HTTP API提交Schema DSL
curl -X POST http://localhost:8887/public/v1/schema/alterSchema \
-H "Content-Type: application/json" \
-d '{
"projectId": 1,
"schemaDraft": {
"dslScript": "namespace DEFAULT\n\nUser(用户): EntityType\n properties:\n username(用户名): Text\n index: KeyWord\n constraint: NotNull"
}
}'
# 2. 查询Schema
curl -X GET "http://localhost:8887/public/v1/schema/queryProjectSchema?projectId=1"
# 3. 导出Schema为DSL
curl -X GET "http://localhost:8887/public/v1/schema/exportDSL?projectId=1"6. 使用指南
6.1 从零开始创建Schema
步骤1:规划Schema结构
首先明确要建模的领域:
- 有哪些实体类型?
- 实体有哪些属性?
- 实体之间有哪些关系?
- 是否需要概念分类?
- 是否需要事件类型?
步骤2:编写DSL文件
创建 schema.dsl 文件:
schema
namespace MyDomain
# 首先定义基础实体
User(用户): EntityType
properties:
username(用户名): Text
index: KeyWord
constraint: NotNull,Unique
# 然后定义关系
User(用户): EntityType
properties:
username(用户名): Text
relations:
follows(关注): User步骤3:验证DSL语法
使用解析工具验证:
java
String dslContent = Files.readString(Paths.get("schema.dsl"));
try {
SchemaModel model = SchemaScriptTranslateUtil.translateScript(dslContent);
System.out.println("DSL语法正确!");
} catch (Exception e) {
System.err.println("DSL语法错误: " + e.getMessage());
}步骤4:提交到OpenSPG
java
schemaManager.alterSchema(request);6.2 Schema版本管理
方案1:Git版本控制
bash
# 初始化Git仓库
git init schema-repo
cd schema-repo
# 创建Schema文件
echo "namespace MyDomain
User(用户): EntityType
properties:
username(用户名): Text" > user.schema
# 提交版本
git add user.schema
git commit -m "Initial schema: User entity"
# 修改Schema
echo " email(邮箱): Text" >> user.schema
git commit -am "Add email property to User"
# 查看历史
git log --oneline方案2:Schema文件命名规范
schema/
├── v1.0/
│ ├── user.schema
│ └── post.schema
├── v1.1/
│ ├── user.schema # 更新版本
│ ├── post.schema
│ └── comment.schema # 新增
└── v2.0/
├── user.schema
├── post.schema
├── comment.schema
└── like.schema # 新增方案3:使用OpenSPG版本管理
OpenSPG会自动管理Schema版本,每次alter操作都会:
- 保存历史版本
- 分配新版本号
- 记录操作时间和操作人
java
// 查询Schema历史版本
List<SchemaVersion> versions = schemaManager.getSchemaVersions(projectId);
// 回滚到指定版本
schemaManager.rollbackToVersion(projectId, versionId);6.3 Schema迁移策略
向后兼容的修改(推荐):
schema
# ✅ 添加新属性(可选)
User(用户): EntityType
properties:
username(用户名): Text
nickname(昵称): Text # 新增,可选
# ✅ 添加新关系
User(用户): EntityType
relations:
follows(关注): User
blocks(屏蔽): User # 新增关系
# ✅ 添加新类型
Comment(评论): EntityType # 全新的实体类型不兼容的修改(需谨慎):
schema
# ⚠️ 删除属性(会丢失数据)
# 删除 email 属性
# ⚠️ 修改属性类型(可能导致数据转换失败)
age(年龄): Text # 原来是 Integer
# ⚠️ 添加 NotNull 约束到已有属性
username(用户名): Text
constraint: NotNull # 如果已有数据有null值,会失败安全的迁移步骤:
备份数据
bash# 导出现有数据 curl -X POST http://localhost:8887/api/v1/export \ -d '{"projectId": 1}' \ -o backup.json创建新Schema版本
java// 不要直接修改,而是创建新版本 SchemaAlterRequest request = new SchemaAlterRequest(); request.setProjectId(projectId); request.setCreateNewVersion(true);数据迁移
java// 编写数据迁移脚本 DataMigrationTask task = new DataMigrationTask(); task.setSourceVersion(oldVersion); task.setTargetVersion(newVersion); task.execute();验证
java// 验证新Schema下的数据完整性 ValidationResult result = schemaManager.validateData(projectId); if (!result.isValid()) { // 回滚 schemaManager.rollback(projectId); }
6.4 常见问题排查
问题1:DSL解析失败
错误信息: illegal indentation at line 10解决方案:
- 检查缩进是否一致(使用Tab或4个空格)
- 检查是否有Tab和空格混用
问题2:类型不存在
错误信息: SPG type 'Company' does not exist解决方案:
- 检查类型名称拼写
- 确保被引用的类型已经定义
- 检查namespace是否正确
问题3:约束验证失败
错误信息: Constraint validation failed for property 'age'解决方案:
- 检查约束定义是否合理
- 检查现有数据是否满足约束
- 考虑先迁移数据再添加约束
7. 最佳实践
7.1 Schema设计原则
命名规范
- 类型名:帕斯卡命名法(PascalCase)
- 属性/关系名:驼峰命名法(camelCase)
- 中文名:简洁明确
模块化设计
schema/ ├── common.schema # 通用类型(User、Tag等) ├── business.schema # 业务实体 ├── event.schema # 事件类型 └── concept.schema # 概念分类继承层次
- 不要超过3层继承
- 抽象共性到父类型
- 避免循环继承
7.2 性能优化
索引策略
- 高频查询字段:添加
index: KeyWord - 全文搜索字段:使用
index: Text - 向量搜索:使用
index: Vector
- 高频查询字段:添加
批量操作
java// ✅ 好的做法:批量提交 SchemaDraft draft = new SchemaDraft(); draft.setAlterSpgTypes(Arrays.asList(type1, type2, type3)); schemaManager.alterSchema(request); // ❌ 不好的做法:逐个提交 for (BaseAdvancedType type : types) { SchemaDraft draft = new SchemaDraft(); draft.setAlterSpgTypes(Arrays.asList(type)); schemaManager.alterSchema(request); // 多次数据库操作 }Schema缓存
java// 缓存ProjectSchema,避免重复查询 @Cacheable(value = "schema", key = "#projectId") public ProjectSchema getProjectSchema(Long projectId) { return schemaManager.getProjectSchema(projectId); }
7.3 文档化
schema
namespace MyDomain
# ==========================================
# 用户域
# 维护者: 张三
# 最后更新: 2025-01-15
# ==========================================
User(用户): EntityType
desc: 系统用户实体,包含基本信息和行为数据
properties:
username(用户名): Text
index: KeyWord
constraint: NotNull,Unique
# 用户唯一标识,注册时生成,不可修改
email(邮箱): Text
index: Text
constraint: Regular="^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"
# 用户邮箱,用于登录和通知附录
A. DSL语法速查表
| 元素 | 语法 | 示例 |
|---|---|---|
| 命名空间 | namespace <名称> | namespace DEFAULT |
| 类型定义 | <名称>(<中文名>): <类别> | Person(人物): EntityType |
| 属性定义 | <名称>(<中文名>): <类型> | age(年龄): Integer |
| 关系定义 | <名称>(<中文名>): <目标类型> | worksAt(工作于): Company |
| 索引配置 | index: <类型> | index: Text |
| 约束配置 | constraint: <约束> | constraint: NotNull |
| 逻辑规则 | rule: [[ <KGDSL> ]] | rule: [[ Define ... ]] |
| 描述 | desc: <描述文本> | desc: 用户实体 |
| 继承 | parent: <父类型> | parent: Person |
B. 核心类路径速查
| 功能 | 类名 | 完整路径 |
|---|---|---|
| DSL解析器 | SchemaScriptTranslateUtil | server/biz/schema/.../SchemaScriptTranslateUtil.java |
| 中间模型 | SchemaModel | server/biz/schema/.../SchemaModel.java |
| 节点模型 | NodeTypeModel | server/biz/schema/.../NodeTypeModel.java |
| 模型转换器 | SchemaModelConvertor | server/biz/schema/.../SchemaModelConvertor.java |
| 处理管道 | SchemaAlterPipeline | server/core/schema/service/.../SchemaAlterPipeline.java |
| 预处理阶段 | PreProcessStage | server/core/schema/service/.../stage/PreProcessStage.java |
| 持久化阶段 | ProcessStage | server/core/schema/service/.../stage/ProcessStage.java |
| 同步阶段 | PostProcessStage | server/core/schema/service/.../stage/PostProcessStage.java |
| Schema管理 | SchemaManager | server/biz/schema/.../SchemaManager.java |
C. 参考资源
- OpenSPG官方文档: https://openspg.yuque.com/ndx6g9/docs
- GitHub仓库: https://github.com/OpenSPG/openspg
- KGDSL语法:
reasoner/kgdsl-parser/src/main/antlr4/KGDSL.g4
版本信息
- 文档版本: 1.0
- OpenSPG版本: 0.8
- 最后更新: 2025-12-13
许可证
本文档基于 Apache License 2.0 开源协议。