Appearance
OpenSPG 构建器模块 Java 接口使用文档
目录
- 1. 概述
- 2. 核心架构
- 3. SourceReader 数据读取器
- 4. Processor 数据处理器
- 5. SinkWriter 数据写入器
- 6. 数据记录模型
- 7. 配置类详解
- 8. 完整示例
- 9. 扩展开发指南
1. 概述
OpenSPG的Builder模块负责知识图谱的构建,实现了从数据源到知识图谱的完整ETL流程。本文档详细介绍Builder模块中的Java接口和类的使用方法。
1.1 数据流转架构
┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ Data Source │ -> │ SourceReader │ -> │ Processor │ -> │ SinkWriter │ -> │ Graph Store │
└──────────────┘ └──────────────┘ └──────────────┘ └──────────────┘ └─────────────┘
↓ ↓ ↓ ↓ ↓
CSV/JSON BaseSourceReader BaseProcessor BaseSinkWriter Neo4j/TuGraph
Database CsvFileSourceReader SPGTypeMappingP... GraphStoreSinkWriter
String StringSourceReader PythonProcessor Neo4jSinkWriter
LLMExtractProcessor1.2 模块位置
- 包路径:
com.antgroup.openspg.builder - 核心模块:
builder/core- 核心执行引擎builder/model- 数据模型定义builder/runner/local- 本地执行器
2. 核心架构
2.1 物理执行节点基类
所有执行节点都继承自 BasePhysicalNode:
位置: com.antgroup.openspg.builder.core.physical.BasePhysicalNode
java
package com.antgroup.openspg.builder.core.physical;
/**
* 物理执行节点的基类
*
* 三种类型的物理节点:
* 1. 数据源节点 (Source Nodes) - 从文件、数据库等读取数据
* 2. 处理节点 (Processing Nodes) - 处理数据(提取、映射、转换等)
* 3. 写入节点 (Sink Nodes) - 将结果写入图存储、搜索引擎等
*/
public abstract class BasePhysicalNode implements Comparable<BasePhysicalNode> {
/** 节点ID */
protected final String id;
/** 节点名称 */
protected final String name;
/** 运行时上下文 - 提供项目ID、任务ID、并行度等信息 */
protected BuilderContext context;
/** 是否已初始化 */
private volatile boolean isInitialized = false;
/**
* 构造函数
* @param id 节点ID
* @param name 节点名称
*/
public BasePhysicalNode(String id, String name) {
this.id = id;
this.name = name;
}
/**
* 初始化节点
* @param context 构建上下文
*/
public void init(BuilderContext context) throws BuilderException {
this.context = context;
if (!isInitialized) {
synchronized (this) {
if (!isInitialized) {
doInit(context);
isInitialized = true;
}
}
}
}
/**
* 子类实现具体的初始化逻辑
*/
public void doInit(BuilderContext context) throws BuilderException {}
/**
* 关闭资源
*/
public abstract void close() throws Exception;
}2.2 BuilderContext 运行时上下文
位置: com.antgroup.openspg.builder.core.runtime.BuilderContext
提供运行时信息:
projectId: 项目IDtaskId: 任务IDparallelism: 并行度batchSize: 批量大小graphStoreUrl: 图存储连接地址pythonExec: Python解释器路径pythonPaths: Python库路径
3. SourceReader 数据读取器
3.1 BaseSourceReader 基类
位置: com.antgroup.openspg.builder.runner.local.physical.source.BaseSourceReader
java
package com.antgroup.openspg.builder.runner.local.physical.source;
/**
* 数据源节点的基类
*
* 作为整个pipeline的起点,通过数据源配置读取数据
* 为下游节点提供数据进行进一步处理
*
* 在多并行度任务中,需要考虑通过数据分区实现并行读取
*/
public abstract class BaseSourceReader<C> extends BasePhysicalNode {
/**
* 数据源配置
* 每种数据源的配置都不同,需要独立实现
* 例如:
* - CSV源配置:文件路径、起始行、列名
* - 数据库源配置:数据库名、表名、用户名密码、列名
*/
protected final C config;
public BaseSourceReader(String id, String name, C config) {
super(id, name);
this.config = config;
}
/**
* 根据数据源配置读取数据
*
* @return 已读取的数据集合。数据源节点主要以BuilderRecord的形式返回原始数据
*/
public abstract List<BaseRecord> read();
}3.2 CsvFileSourceReader - CSV文件读取器
位置: com.antgroup.openspg.builder.runner.local.physical.source.impl.CsvFileSourceReader
java
package com.antgroup.openspg.builder.runner.local.physical.source.impl;
/**
* CSV文件数据源读取器
*/
public class CsvFileSourceReader extends BaseSourceReader<CsvSourceNodeConfig> {
private Queue<BaseRecord> queue;
private CSVReader csvReader;
private Iterator<String[]> lines;
private AtomicLong lineNumber;
public CsvFileSourceReader(String id, String name, CsvSourceNodeConfig config) {
super(id, name, config);
}
@Override
public void doInit(BuilderContext context) throws BuilderException {
// 初始化队列,大小为 batchSize * parallelism
queue = new ArrayBlockingQueue<>(context.getBatchSize() * context.getParallelism());
// 打开CSV文件
try {
csvReader = new CSVReaderBuilder(new FileReader(config.getUrl()))
.withSkipLines(config.getStartRow() - 1)
.build();
} catch (FileNotFoundException e) {
throw new BuilderException(e, "csv file={} is not exist.", config.getUrl());
}
lineNumber = new AtomicLong(config.getStartRow() - 1);
lines = csvReader.iterator();
}
@Override
public List<BaseRecord> read() {
putQueue(); // 填充队列
List<BaseRecord> results = new ArrayList<>(context.getBatchSize());
// 批量读取数据
for (int i = 0; i < context.getBatchSize(); i++) {
BaseRecord poll = queue.poll();
if (poll == null) {
putQueue();
poll = queue.poll();
}
if (poll == null) {
break;
}
results.add(poll);
}
return results;
}
@Override
public void close() throws Exception {
if (csvReader != null) {
csvReader.close();
}
}
/**
* 解析CSV行为BuilderRecord
*/
private BuilderRecord parse(String[] fields) {
Map<String, String> props = new HashMap<>(config.getColumns().size());
for (int i = 0; i < config.getColumns().size(); i++) {
String column = config.getColumns().get(i);
if (i >= fields.length) {
props.put(column, null);
} else {
props.put(column, fields[i]);
}
}
return new BuilderRecord("line" + lineNumber.get(), null, props);
}
}使用示例:
java
// 创建CSV源配置
CsvSourceNodeConfig config = new CsvSourceNodeConfig(
"/path/to/data.csv", // 文件路径
1, // 起始行(第1行)
Arrays.asList("id", "name", "age") // 列名
);
// 创建CSV读取器
CsvFileSourceReader reader = new CsvFileSourceReader("source_1", "CSV Source", config);
// 初始化
BuilderContext context = createContext();
reader.init(context);
// 读取数据
List<BaseRecord> records = reader.read();
// 处理记录...
// 关闭
reader.close();3.3 StringSourceReader - 字符串读取器
位置: com.antgroup.openspg.builder.runner.local.physical.source.impl.StringSourceReader
用于处理字符串类型的数据源。
3.4 SourceReaderFactory - 数据源工厂
位置: com.antgroup.openspg.builder.runner.local.physical.source.SourceReaderFactory
java
public class SourceReaderFactory {
/**
* 根据逻辑节点类型创建对应的数据源读取器
*/
public static BaseSourceReader<?> getSourceReader(BaseLogicalNode<?> baseNode) {
switch (baseNode.getType()) {
case CSV_SOURCE:
return new CsvFileSourceReader(
baseNode.getId(),
baseNode.getName(),
((CsvSourceNode) baseNode).getNodeConfig());
case STRING_SOURCE:
return new StringSourceReader(
baseNode.getId(),
baseNode.getName(),
((StringSourceNode) baseNode).getNodeConfig());
default:
throw new IllegalArgumentException("illegal nodeType=" + baseNode.getType());
}
}
}4. Processor 数据处理器
4.1 BaseProcessor 基类
位置: com.antgroup.openspg.builder.core.physical.process.BaseProcessor
java
package com.antgroup.openspg.builder.core.physical.process;
/**
* 处理节点的基类
*
* 进一步处理来自上游节点的数据,例如:
* - 知识抽取
* - 数据映射
* - 算子执行
*
* 目前支持:
* - 知识抽取处理器
* - 映射处理器
*/
public abstract class BaseProcessor<C> extends BasePhysicalNode {
/** 处理器配置 */
protected final C config;
public BaseProcessor(String id, String name, C config) {
super(id, name);
this.config = config;
}
/**
* 处理输入记录并将执行结果输出到下游节点
*
* @param inputs 来自上游节点的输出结果
* @return 已处理的数据集合
*/
public abstract List<BaseRecord> process(List<BaseRecord> inputs);
}4.2 SPGTypeMappingProcessor - SPG类型映射处理器
位置: com.antgroup.openspg.builder.core.physical.process.SPGTypeMappingProcessor
将原始数据映射为SPG类型实例。
java
package com.antgroup.openspg.builder.core.physical.process;
/**
* SPG类型映射处理器
*
* 将BuilderRecord(原始KV数据)映射为SPGRecord(SPG类型实例)
*/
public class SPGTypeMappingProcessor extends BaseProcessor<SPGTypeMappingNodeConfigs> {
private final List<SPGTypeMappingHelper> mappingHelpers;
public SPGTypeMappingProcessor(String id, String name, SPGTypeMappingNodeConfigs config) {
super(id, name, config);
this.mappingHelpers = config.getMappingNodeConfigs().stream()
.map(SPGTypeMappingHelper::new)
.collect(Collectors.toList());
}
@Override
public void doInit(BuilderContext context) throws BuilderException {
super.doInit(context);
this.mappingHelpers.forEach(x -> x.init(context));
}
@Override
public List<BaseRecord> process(List<BaseRecord> inputs) {
List<BaseSPGRecord> resultSpgRecords = new ArrayList<>(inputs.size());
// 按SPG类型标识符分组
List<BuilderRecord> emptyIdentifierRecords = new ArrayList<>(inputs.size());
Map<SPGTypeIdentifier, List<BuilderRecord>> identifierRecords = new HashMap<>();
for (BaseRecord baseRecord : inputs) {
BuilderRecord record = (BuilderRecord) baseRecord;
if (record.getIdentifier() == null) {
emptyIdentifierRecords.add(record);
} else {
List<BuilderRecord> existedRecords =
identifierRecords.computeIfAbsent(record.getIdentifier(), k -> new ArrayList<>());
existedRecords.add(record);
}
}
// 为每个映射助手处理记录
for (SPGTypeMappingHelper mappingHelper : mappingHelpers) {
// 处理无标识符的记录
for (BuilderRecord record : emptyIdentifierRecords) {
resultSpgRecords.addAll(toSPGRecords(mappingHelper, record));
}
// 处理有标识符的记录
List<BuilderRecord> identifiedRecords = identifierRecords.get(mappingHelper.getIdentifier());
if (CollectionUtils.isNotEmpty(identifiedRecords)) {
for (BuilderRecord record : identifiedRecords) {
resultSpgRecords.addAll(toSPGRecords(mappingHelper, record));
}
}
}
return (List) resultSpgRecords;
}
private List<BaseSPGRecord> toSPGRecords(SPGTypeMappingHelper mappingHelper, BuilderRecord record) {
if (mappingHelper.isFiltered(record)) {
return Collections.emptyList();
}
return mappingHelper.toSPGRecords(record, true);
}
@Override
public void close() throws Exception {}
}使用示例:
java
// 创建映射配置
SPGTypeMappingNodeConfig personMappingConfig = new SPGTypeMappingNodeConfig();
personMappingConfig.setSpgTypeName("Person");
personMappingConfig.setIdField("id");
personMappingConfig.setPropertyMappings(Map.of(
"name", "name",
"age", "age"
));
SPGTypeMappingNodeConfigs configs = new SPGTypeMappingNodeConfigs();
configs.setMappingNodeConfigs(Arrays.asList(personMappingConfig));
// 创建处理器
SPGTypeMappingProcessor processor = new SPGTypeMappingProcessor(
"mapping_1",
"Person Mapping",
configs
);
// 初始化
processor.init(context);
// 处理数据
List<BaseRecord> builderRecords = reader.read();
List<BaseRecord> spgRecords = processor.process(builderRecords);
// 关闭
processor.close();4.3 PythonProcessor - Python处理器
位置: com.antgroup.openspg.builder.core.physical.process.PythonProcessor
支持使用Python脚本处理数据,适用于NLP、深度学习等场景。
java
package com.antgroup.openspg.builder.core.physical.process;
/**
* Python处理器
*
* 通过Pemja(Python嵌入式Java适配器)调用Python函数处理数据
*/
public class PythonProcessor extends BaseProcessor<PythonNodeConfig> {
PemjaConfig config;
public PythonProcessor(String id, String name, PythonNodeConfig config) {
super(id, name, config);
this.config = config.getPemjaConfig();
}
@Override
public void doInit(BuilderContext context) throws BuilderException {
super.doInit(context);
// 设置Python路径
if (StringUtils.isBlank(config.getPythonPaths())) {
config.setPythonPaths(context.getPythonPaths());
}
if (StringUtils.isBlank(config.getPythonExec())) {
config.setPythonExec(context.getPythonExec());
}
}
@Override
public List<BaseRecord> process(List<BaseRecord> inputs) {
List<BaseRecord> outputs = Lists.newArrayList();
for (BaseRecord record : inputs) {
// 将记录转换为Map
Map map = new ObjectMapper().convertValue(record, Map.class);
// 调用Python函数
List<Object> results = (List<Object>) PemjaUtils.invoke(config, map);
// 将结果转换为StringRecord
results.forEach(result ->
outputs.add(new StringRecord(JSON.toJSONString(result)))
);
}
return outputs;
}
@Override
public void close() throws Exception {}
}Python脚本示例:
python
# entity_processor.py
def process(record):
"""
处理单条记录
Args:
record: dict类型的记录
Returns:
list[dict]: 处理后的记录列表
"""
# 实体链接
entity_name = record.get('name')
linked_entity = entity_linking(entity_name)
# 添加处理结果
record['linked_entity_id'] = linked_entity['id']
record['confidence'] = linked_entity['confidence']
return [record]
def entity_linking(name):
"""实体链接逻辑"""
# 调用NLP模型或知识库查询
return {
'id': 'E12345',
'confidence': 0.95
}Java端配置:
java
// 创建Python处理器配置
PemjaConfig pemjaConfig = new PemjaConfig();
pemjaConfig.setPythonExec("/usr/bin/python3");
pemjaConfig.setPythonPaths("/path/to/python/libs");
pemjaConfig.setModuleName("entity_processor");
pemjaConfig.setFunctionName("process");
PythonNodeConfig pythonConfig = new PythonNodeConfig();
pythonConfig.setPemjaConfig(pemjaConfig);
// 创建处理器
PythonProcessor pythonProcessor = new PythonProcessor(
"python_1",
"Entity Linking",
pythonConfig
);
// 使用
pythonProcessor.init(context);
List<BaseRecord> results = pythonProcessor.process(inputs);
pythonProcessor.close();4.4 其他处理器
| 处理器类 | 位置 | 功能 |
|---|---|---|
LLMBasedExtractProcessor | builder.core.physical.process | 基于LLM的知识抽取 |
LLMNlExtractProcessor | builder.core.physical.process | 基于LLM的自然语言抽取 |
RelationMappingProcessor | builder.core.physical.process | 关系映射处理 |
VectorizerProcessor | builder.core.physical.process | 向量化处理 |
CheckProcessor | builder.core.physical.process | 数据校验处理 |
ParagraphSplitProcessor | builder.core.physical.process | 段落分割处理 |
5. SinkWriter 数据写入器
5.1 BaseSinkWriter 基类
位置: com.antgroup.openspg.builder.runner.local.physical.sink.BaseSinkWriter
java
package com.antgroup.openspg.builder.runner.local.physical.sink;
/**
* Sink节点的基类
*
* 将物理执行计划的执行结果输出到指定存储,例如:
* - 图存储
* - 搜索引擎
* - 键值存储
*
* 继承自BasePhysicalNode,同时也有自己的writer方法来实现数据输出
*/
public abstract class BaseSinkWriter<C> extends BasePhysicalNode {
/**
* Sink写入器配置
*
* 以TuGraph和Elasticsearch为例:
* - TuGraph: schema("tugraph"), graphName("default"),
* host("127.0.0.1:9090"), accessId, accessKey
* - Elasticsearch: schema("elasticsearch"), host("127.0.0.1"),
* scheme("http"), port("9200")
*/
protected final C config;
public BaseSinkWriter(String id, String name, C config) {
super(id, name);
this.config = config;
}
/**
* 将物理执行计划的执行结果输出到指定存储
*
* @param records 上游处理节点生成的数据
*/
public abstract void write(List<BaseRecord> records);
}5.2 GraphStoreSinkWriter - 图存储写入器
位置: com.antgroup.openspg.builder.runner.local.physical.sink.impl.GraphStoreSinkWriter
写入OpenSPG标准图存储接口。
java
package com.antgroup.openspg.builder.runner.local.physical.sink.impl;
/**
* 图存储写入器
*
* 将SPGRecord写入图数据库(Neo4j、TuGraph等)
*/
public class GraphStoreSinkWriter extends BaseSinkWriter<GraphStoreSinkNodeConfig> {
private GraphStoreClient graphStoreClient;
private CheckProcessor checkProcessor;
private ExecuteNode node = new ExecuteNode();
public GraphStoreSinkWriter(String id, String name, GraphStoreSinkNodeConfig config) {
super(id, name, config);
}
@Override
public void doInit(BuilderContext context) throws BuilderException {
// 获取图存储客户端
graphStoreClient = GraphStoreClientDriverManager.getClient(context.getGraphStoreUrl());
// 初始化校验处理器
checkProcessor = new CheckProcessor();
checkProcessor.init(context);
if (context.getExecuteNodes() != null) {
this.node = context.getExecuteNodes().get(getId());
}
}
@Override
public void write(List<BaseRecord> records) {
if (!config.getIsWriter()) {
return; // 不写入模式(可用于测试)
}
// 设置节点状态为运行中
if (node != null) {
node.setStatus(StatusEnum.RUNNING);
}
// 如果是UPSERT操作,先进行校验
if (RecordAlterOperationEnum.UPSERT == context.getOperation()) {
records = checkProcessor.process(records);
}
// 替换不可展开的标准属性类型为文本类型
records.forEach(record -> replaceUnSpreadableStandardProperty((BaseSPGRecord) record));
// 批量写入图存储
batchWriteToGraphStore(records);
}
/**
* 批量写入图存储
*/
private void batchWriteToGraphStore(List<BaseRecord> records) {
// 转换为SPGRecordAlterItem
List<SPGRecordAlterItem> items = records.stream()
.map(record -> new SPGRecordAlterItem(context.getOperation(), (BaseSPGRecord) record))
.collect(Collectors.toList());
// 调用图存储客户端写入
graphStoreClient.manipulateRecord(new SPGRecordManipulateCmd(items));
}
/**
* 替换不可展开的标准属性类型
*/
private void replaceUnSpreadableStandardProperty(BaseSPGRecord record) {
if (SPGRecordTypeEnum.RELATION.equals(record.getRecordType())) {
return;
}
record.getProperties().forEach(property -> {
if (!property.isSemanticProperty() || !property.getObjectTypeRef().isStandardType()) {
return;
}
SPGTypeIdentifier spgTypeIdentifier = property.getObjectTypeRef().getBaseSpgIdentifier();
if (!context.getCatalog().isSpreadable(spgTypeIdentifier)) {
Property propertyType = ((SPGPropertyRecord) property).getProperty();
propertyType.setObjectTypeRef(TEXT_REF);
}
});
}
@Override
public void close() throws Exception {
if (node != null) {
node.setStatus(StatusEnum.FINISH);
}
}
}使用示例:
java
// 创建图存储写入配置
GraphStoreSinkNodeConfig sinkConfig = new GraphStoreSinkNodeConfig();
sinkConfig.setIsWriter(true); // 启用写入
// 创建写入器
GraphStoreSinkWriter writer = new GraphStoreSinkWriter(
"sink_1",
"Graph Store Sink",
sinkConfig
);
// 初始化
BuilderContext context = createContext();
context.setGraphStoreUrl("neo4j://localhost:7687?user=neo4j&password=password");
context.setOperation(RecordAlterOperationEnum.UPSERT);
writer.init(context);
// 写入数据
List<BaseRecord> spgRecords = processor.process(inputs);
writer.write(spgRecords);
// 关闭
writer.close();5.3 Neo4jSinkWriter - Neo4j写入器
位置: com.antgroup.openspg.builder.runner.local.physical.sink.impl.Neo4jSinkWriter
直接写入Neo4j数据库(不通过CloudExt抽象层)。
5.4 SinkWriterFactory - 写入器工厂
位置: com.antgroup.openspg.builder.runner.local.physical.sink.SinkWriterFactory
java
public class SinkWriterFactory {
/**
* 根据逻辑节点类型创建对应的数据写入器
*/
public static BaseSinkWriter<?> getSinkWriter(BaseLogicalNode<?> baseNode) {
switch (baseNode.getType()) {
case GRAPH_SINK:
return new GraphStoreSinkWriter(
baseNode.getId(),
baseNode.getName(),
((GraphStoreSinkNode) baseNode).getNodeConfig());
case NEO4J_SINK:
return new Neo4jSinkWriter(
baseNode.getId(),
baseNode.getName(),
((Neo4jSinkNode) baseNode).getNodeConfig());
default:
throw new IllegalArgumentException("illegal nodeType=" + baseNode.getType());
}
}
}6. 数据记录模型
6.1 BaseRecord - 记录基类
位置: com.antgroup.openspg.builder.model.record.BaseRecord
java
package com.antgroup.openspg.builder.model.record;
/**
* 所有记录类型的基类
*/
public abstract class BaseRecord extends BaseValObj {}6.2 BuilderRecord - 构建记录
位置: com.antgroup.openspg.builder.model.record.BuilderRecord
java
package com.antgroup.openspg.builder.model.record;
/**
* 基础数据的传输协议,格式为键值对(KV)
*
* 用于数据源读取的原始数据表示
*/
@Getter
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class BuilderRecord extends BaseRecord {
/** 记录ID */
private final String recordId;
/** SPG类型标识符 */
@Setter
private SPGTypeIdentifier identifier;
/** 单条数据记录的键值对表示 */
private final Map<String, String> props;
/**
* 获取属性值
*/
public String getPropValue(String propKey) {
return props.get(propKey);
}
/**
* 创建新的BuilderRecord,使用新的属性Map
*/
public BuilderRecord withNewProps(Map<String, String> newProps) {
return new BuilderRecord(recordId, identifier, newProps);
}
@Override
public String toString() {
return JSON.toJSONString(this);
}
}使用示例:
java
// 创建BuilderRecord
Map<String, String> props = new HashMap<>();
props.put("id", "P001");
props.put("name", "张三");
props.put("age", "30");
BuilderRecord record = new BuilderRecord(
"record_001", // 记录ID
new SPGTypeIdentifier("default", "Person"), // SPG类型
props // 属性映射
);
// 访问属性
String name = record.getPropValue("name"); // "张三"
// 修改属性
Map<String, String> newProps = new HashMap<>(props);
newProps.put("age", "31");
BuilderRecord updatedRecord = record.withNewProps(newProps);6.3 BaseSPGRecord - SPG记录基类
位置: com.antgroup.openspg.builder.model.record.BaseSPGRecord
SPG类型实例的抽象基类,所有具体的SPG记录都继承自此类。
6.4 SPG记录类型层次
BaseRecord (基类)
├── BuilderRecord (原始KV数据)
├── StringRecord (字符串数据)
└── BaseSPGRecord (SPG实例数据)
├── EntityRecord (实体记录)
├── ConceptRecord (概念记录)
├── EventRecord (事件记录)
├── RelationRecord (关系记录)
├── StandardRecord (标准类型记录)
└── ChunkRecord (文本块记录)6.5 EntityRecord - 实体记录
java
/**
* 实体类型记录
*/
public class EntityRecord extends BaseSPGRecord {
public EntityRecord(
String id, // 实体ID
String name, // 实体名称
SPGTypeIdentifier spgTypeIdentifier // SPG类型标识
) {
super(id, name, spgTypeIdentifier);
}
@Override
public SPGRecordTypeEnum getRecordType() {
return SPGRecordTypeEnum.ENTITY;
}
}6.6 RelationRecord - 关系记录
java
/**
* 关系类型记录
*/
public class RelationRecord extends BaseSPGRecord {
private String srcId; // 源实体ID
private String dstId; // 目标实体ID
private String relationName; // 关系名称
public RelationRecord(
String id,
String srcId,
String dstId,
String relationName,
SPGTypeIdentifier srcType,
SPGTypeIdentifier dstType
) {
super(id, relationName, srcType);
this.srcId = srcId;
this.dstId = dstId;
this.relationName = relationName;
}
@Override
public SPGRecordTypeEnum getRecordType() {
return SPGRecordTypeEnum.RELATION;
}
}7. 配置类详解
7.1 BaseNodeConfig - 节点配置基类
位置: com.antgroup.openspg.builder.model.pipeline.config.BaseNodeConfig
所有节点配置的基类,包含节点类型信息。
7.2 CsvSourceNodeConfig - CSV源配置
位置: com.antgroup.openspg.builder.model.pipeline.config.CsvSourceNodeConfig
java
package com.antgroup.openspg.builder.model.pipeline.config;
@Getter
public class CsvSourceNodeConfig extends BaseNodeConfig {
/** 起始行 */
private final int startRow;
/** 文件URL */
private final String url;
/** 列名列表 */
private final List<String> columns;
public CsvSourceNodeConfig(String url, int startRow, List<String> columns) {
super(NodeTypeEnum.CSV_SOURCE);
this.url = url;
this.startRow = startRow;
this.columns = columns;
}
}使用示例:
java
// 创建CSV源配置
CsvSourceNodeConfig csvConfig = new CsvSourceNodeConfig(
"/data/employees.csv", // 文件路径
2, // 从第2行开始(跳过标题行)
Arrays.asList("id", "name", "age", "department") // 列名
);7.3 GraphStoreSinkNodeConfig - 图存储写入配置
位置: com.antgroup.openspg.builder.model.pipeline.config.GraphStoreSinkNodeConfig
java
@Getter
@Setter
public class GraphStoreSinkNodeConfig extends BaseNodeConfig {
/** 是否启用写入 */
private Boolean isWriter = true;
public GraphStoreSinkNodeConfig() {
super(NodeTypeEnum.GRAPH_SINK);
}
}7.4 PythonNodeConfig - Python处理器配置
位置: com.antgroup.openspg.builder.model.pipeline.config.PythonNodeConfig
java
@Getter
@Setter
public class PythonNodeConfig extends BaseNodeConfig {
/** Pemja配置 */
private PemjaConfig pemjaConfig;
public PythonNodeConfig() {
super(NodeTypeEnum.PYTHON);
}
}
/**
* Pemja配置(Python嵌入式Java适配器)
*/
@Getter
@Setter
public class PemjaConfig {
/** Python解释器路径 */
private String pythonExec;
/** Python库路径 */
private String pythonPaths;
/** Python模块名 */
private String moduleName;
/** Python函数名 */
private String functionName;
/** 额外参数 */
private Map<String, Object> kwargs;
}7.5 SPGTypeMappingNodeConfig - SPG类型映射配置
位置: com.antgroup.openspg.builder.model.pipeline.config.SPGTypeMappingNodeConfig
java
@Getter
@Setter
public class SPGTypeMappingNodeConfig extends BaseNodeConfig {
/** SPG类型名称 */
private String spgTypeName;
/** ID字段映射 */
private String idField;
/** 名称字段映射 */
private String nameField;
/** 属性映射:SPG属性名 -> 源字段名 */
private Map<String, String> propertyMappings;
/** 过滤条件 */
private String filterExpression;
public SPGTypeMappingNodeConfig() {
super(NodeTypeEnum.SPG_TYPE_MAPPING);
}
}完整使用示例:
java
// 配置Person类型的映射
SPGTypeMappingNodeConfig personMapping = new SPGTypeMappingNodeConfig();
personMapping.setSpgTypeName("Person");
personMapping.setIdField("id");
personMapping.setNameField("name");
// 属性映射
Map<String, String> propertyMappings = new HashMap<>();
propertyMappings.put("name", "employee_name"); // SPG属性 -> 源字段
propertyMappings.put("age", "employee_age");
propertyMappings.put("email", "employee_email");
personMapping.setPropertyMappings(propertyMappings);
// 过滤条件(可选)
personMapping.setFilterExpression("age >= 18");
// 配置Company类型的映射
SPGTypeMappingNodeConfig companyMapping = new SPGTypeMappingNodeConfig();
companyMapping.setSpgTypeName("Company");
companyMapping.setIdField("company_id");
companyMapping.setNameField("company_name");
companyMapping.setPropertyMappings(Map.of(
"name", "company_name",
"industry", "company_industry"
));
// 创建映射配置集合
SPGTypeMappingNodeConfigs configs = new SPGTypeMappingNodeConfigs();
configs.setMappingNodeConfigs(Arrays.asList(personMapping, companyMapping));8. 完整示例
8.1 完整的数据构建Pipeline
java
package com.example.openspg.builder;
import com.antgroup.openspg.builder.core.runtime.BuilderContext;
import com.antgroup.openspg.builder.model.pipeline.config.*;
import com.antgroup.openspg.builder.model.record.*;
import com.antgroup.openspg.builder.runner.local.physical.source.impl.CsvFileSourceReader;
import com.antgroup.openspg.builder.core.physical.process.SPGTypeMappingProcessor;
import com.antgroup.openspg.builder.core.physical.process.PythonProcessor;
import com.antgroup.openspg.builder.runner.local.physical.sink.impl.GraphStoreSinkWriter;
import java.util.*;
/**
* 完整的知识图谱构建示例
*
* 数据流: CSV文件 -> 类型映射 -> Python处理 -> 图存储
*/
public class CompleteBuilderExample {
public static void main(String[] args) throws Exception {
// ========== 1. 创建构建上下文 ==========
BuilderContext context = new BuilderContext();
context.setProjectId(1L);
context.setTaskId(100L);
context.setParallelism(1);
context.setBatchSize(100);
context.setGraphStoreUrl("neo4j://localhost:7687?user=neo4j&password=password&database=neo4j");
context.setPythonExec("/usr/bin/python3");
context.setPythonPaths("/usr/lib/python3/site-packages");
context.setOperation(RecordAlterOperationEnum.UPSERT);
// ========== 2. 创建CSV数据源 ==========
CsvSourceNodeConfig csvConfig = new CsvSourceNodeConfig(
"/data/employees.csv",
1, // 从第1行开始
Arrays.asList("id", "name", "age", "email", "company_id")
);
CsvFileSourceReader csvReader = new CsvFileSourceReader(
"csv_source_1",
"Employee CSV Source",
csvConfig
);
// ========== 3. 创建SPG类型映射处理器 ==========
SPGTypeMappingNodeConfig personMappingConfig = new SPGTypeMappingNodeConfig();
personMappingConfig.setSpgTypeName("Person");
personMappingConfig.setIdField("id");
personMappingConfig.setNameField("name");
Map<String, String> propertyMappings = new HashMap<>();
propertyMappings.put("name", "name");
propertyMappings.put("age", "age");
propertyMappings.put("email", "email");
personMappingConfig.setPropertyMappings(propertyMappings);
SPGTypeMappingNodeConfigs mappingConfigs = new SPGTypeMappingNodeConfigs();
mappingConfigs.setMappingNodeConfigs(Arrays.asList(personMappingConfig));
SPGTypeMappingProcessor mappingProcessor = new SPGTypeMappingProcessor(
"mapping_1",
"Person Mapping",
mappingConfigs
);
// ========== 4. 创建Python处理器(实体链接)==========
PemjaConfig pemjaConfig = new PemjaConfig();
pemjaConfig.setPythonExec("/usr/bin/python3");
pemjaConfig.setPythonPaths("/opt/python_processors");
pemjaConfig.setModuleName("entity_processor");
pemjaConfig.setFunctionName("link_entities");
PythonNodeConfig pythonConfig = new PythonNodeConfig();
pythonConfig.setPemjaConfig(pemjaConfig);
PythonProcessor pythonProcessor = new PythonProcessor(
"python_1",
"Entity Linking",
pythonConfig
);
// ========== 5. 创建图存储写入器 ==========
GraphStoreSinkNodeConfig sinkConfig = new GraphStoreSinkNodeConfig();
sinkConfig.setIsWriter(true);
GraphStoreSinkWriter graphWriter = new GraphStoreSinkWriter(
"sink_1",
"Graph Store Sink",
sinkConfig
);
// ========== 6. 初始化所有节点 ==========
csvReader.init(context);
mappingProcessor.init(context);
pythonProcessor.init(context);
graphWriter.init(context);
// ========== 7. 执行数据处理流程 ==========
System.out.println("开始构建知识图谱...");
int totalRecords = 0;
List<BaseRecord> batch;
while (!(batch = csvReader.read()).isEmpty()) {
System.out.println("读取批次,大小: " + batch.size());
// 步骤1: 类型映射
List<BaseRecord> mappedRecords = mappingProcessor.process(batch);
System.out.println("映射后记录数: " + mappedRecords.size());
// 步骤2: Python处理(实体链接)
List<BaseRecord> linkedRecords = pythonProcessor.process(mappedRecords);
System.out.println("链接后记录数: " + linkedRecords.size());
// 步骤3: 写入图存储
graphWriter.write(linkedRecords);
totalRecords += batch.size();
System.out.println("已处理记录数: " + totalRecords);
}
// ========== 8. 关闭所有节点 ==========
csvReader.close();
mappingProcessor.close();
pythonProcessor.close();
graphWriter.close();
System.out.println("知识图谱构建完成!总共处理 " + totalRecords + " 条记录。");
}
}8.2 使用工厂模式的简化版本
java
package com.example.openspg.builder;
import com.antgroup.openspg.builder.core.logical.*;
import com.antgroup.openspg.builder.runner.local.physical.source.SourceReaderFactory;
import com.antgroup.openspg.builder.runner.local.physical.sink.SinkWriterFactory;
/**
* 使用工厂模式的简化构建示例
*/
public class FactoryBasedBuilderExample {
public static void main(String[] args) throws Exception {
// ========== 1. 创建逻辑节点 ==========
// CSV源逻辑节点
CsvSourceNode csvSourceNode = new CsvSourceNode(
"csv_source_1",
"Employee CSV Source",
new CsvSourceNodeConfig("/data/employees.csv", 1,
Arrays.asList("id", "name", "age", "email"))
);
// 图存储Sink逻辑节点
GraphStoreSinkNode graphSinkNode = new GraphStoreSinkNode(
"graph_sink_1",
"Graph Store Sink",
new GraphStoreSinkNodeConfig()
);
// ========== 2. 使用工厂创建物理节点 ==========
BaseSourceReader<?> sourceReader = SourceReaderFactory.getSourceReader(csvSourceNode);
BaseSinkWriter<?> sinkWriter = SinkWriterFactory.getSinkWriter(graphSinkNode);
// ========== 3. 初始化和执行 ==========
BuilderContext context = createContext();
sourceReader.init(context);
sinkWriter.init(context);
List<BaseRecord> records = sourceReader.read();
sinkWriter.write(records);
sourceReader.close();
sinkWriter.close();
System.out.println("完成!");
}
private static BuilderContext createContext() {
BuilderContext context = new BuilderContext();
context.setProjectId(1L);
context.setGraphStoreUrl("neo4j://localhost:7687?user=neo4j&password=password");
context.setBatchSize(100);
context.setParallelism(1);
return context;
}
}9. 扩展开发指南
9.1 自定义数据源Reader
java
package com.example.openspg.custom;
import com.antgroup.openspg.builder.runner.local.physical.source.BaseSourceReader;
import com.antgroup.openspg.builder.model.record.BaseRecord;
import com.antgroup.openspg.builder.model.record.BuilderRecord;
import java.sql.*;
import java.util.*;
/**
* 自定义MySQL数据源Reader
*/
public class MySQLSourceReader extends BaseSourceReader<MySQLSourceConfig> {
private Connection connection;
private PreparedStatement statement;
private ResultSet resultSet;
public MySQLSourceReader(String id, String name, MySQLSourceConfig config) {
super(id, name, config);
}
@Override
public void doInit(BuilderContext context) throws BuilderException {
try {
// 建立数据库连接
String url = String.format("jdbc:mysql://%s:%d/%s",
config.getHost(),
config.getPort(),
config.getDatabase()
);
connection = DriverManager.getConnection(
url,
config.getUsername(),
config.getPassword()
);
// 准备SQL查询
String sql = String.format("SELECT %s FROM %s WHERE %s",
String.join(",", config.getColumns()),
config.getTableName(),
config.getWhereClause() != null ? config.getWhereClause() : "1=1"
);
statement = connection.prepareStatement(sql);
statement.setFetchSize(context.getBatchSize());
resultSet = statement.executeQuery();
} catch (SQLException e) {
throw new BuilderException(e, "Failed to initialize MySQL connection");
}
}
@Override
public List<BaseRecord> read() {
List<BaseRecord> records = new ArrayList<>(context.getBatchSize());
try {
int count = 0;
while (resultSet.next() && count < context.getBatchSize()) {
Map<String, String> props = new HashMap<>();
for (String column : config.getColumns()) {
String value = resultSet.getString(column);
props.put(column, value);
}
BuilderRecord record = new BuilderRecord(
"mysql_" + resultSet.getRow(),
null,
props
);
records.add(record);
count++;
}
} catch (SQLException e) {
throw new RuntimeException("Failed to read from MySQL", e);
}
return records;
}
@Override
public void close() throws Exception {
if (resultSet != null) resultSet.close();
if (statement != null) statement.close();
if (connection != null) connection.close();
}
}
/**
* MySQL数据源配置
*/
@Getter
@Setter
public class MySQLSourceConfig extends BaseNodeConfig {
private String host;
private int port;
private String database;
private String tableName;
private String username;
private String password;
private List<String> columns;
private String whereClause;
public MySQLSourceConfig() {
super(NodeTypeEnum.CUSTOM_SOURCE);
}
}9.2 自定义Processor
java
package com.example.openspg.custom;
import com.antgroup.openspg.builder.core.physical.process.BaseProcessor;
import com.antgroup.openspg.builder.model.record.BaseRecord;
import com.antgroup.openspg.builder.model.record.BuilderRecord;
import java.util.*;
import java.util.stream.Collectors;
/**
* 自定义数据清洗Processor
*/
public class DataCleaningProcessor extends BaseProcessor<DataCleaningConfig> {
public DataCleaningProcessor(String id, String name, DataCleaningConfig config) {
super(id, name, config);
}
@Override
public List<BaseRecord> process(List<BaseRecord> inputs) {
return inputs.stream()
.map(record -> (BuilderRecord) record)
.filter(this::isValid) // 过滤无效记录
.map(this::cleanRecord) // 清洗数据
.collect(Collectors.toList());
}
/**
* 验证记录是否有效
*/
private boolean isValid(BuilderRecord record) {
// 必填字段检查
for (String requiredField : config.getRequiredFields()) {
String value = record.getPropValue(requiredField);
if (value == null || value.trim().isEmpty()) {
return false;
}
}
// 数据类型检查
if (config.getNumericFields() != null) {
for (String numericField : config.getNumericFields()) {
String value = record.getPropValue(numericField);
if (value != null && !isNumeric(value)) {
return false;
}
}
}
return true;
}
/**
* 清洗记录数据
*/
private BuilderRecord cleanRecord(BuilderRecord record) {
Map<String, String> cleanedProps = new HashMap<>();
for (Map.Entry<String, String> entry : record.getProps().entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (value == null) {
continue;
}
// 去除前后空格
value = value.trim();
// 统一大小写(如果配置)
if (config.getLowercaseFields() != null &&
config.getLowercaseFields().contains(key)) {
value = value.toLowerCase();
}
// 移除特殊字符(如果配置)
if (config.getRemoveSpecialChars()) {
value = value.replaceAll("[^a-zA-Z0-9\\u4e00-\\u9fa5\\s]", "");
}
cleanedProps.put(key, value);
}
return record.withNewProps(cleanedProps);
}
private boolean isNumeric(String str) {
try {
Double.parseDouble(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}
@Override
public void close() throws Exception {
// 清理资源
}
}
/**
* 数据清洗配置
*/
@Getter
@Setter
public class DataCleaningConfig extends BaseNodeConfig {
private List<String> requiredFields; // 必填字段
private List<String> numericFields; // 数字字段
private List<String> lowercaseFields; // 需要转小写的字段
private Boolean removeSpecialChars; // 是否移除特殊字符
public DataCleaningConfig() {
super(NodeTypeEnum.CUSTOM_PROCESSOR);
}
}9.3 自定义SinkWriter
java
package com.example.openspg.custom;
import com.antgroup.openspg.builder.runner.local.physical.sink.BaseSinkWriter;
import com.antgroup.openspg.builder.model.record.BaseRecord;
import com.antgroup.openspg.builder.model.record.BaseSPGRecord;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import java.util.*;
/**
* 自定义Elasticsearch写入器
*/
public class ElasticsearchSinkWriter extends BaseSinkWriter<ElasticsearchSinkConfig> {
private RestHighLevelClient esClient;
public ElasticsearchSinkWriter(String id, String name, ElasticsearchSinkConfig config) {
super(id, name, config);
}
@Override
public void doInit(BuilderContext context) throws BuilderException {
// 初始化Elasticsearch客户端
esClient = new RestHighLevelClient(
RestClient.builder(
new HttpHost(config.getHost(), config.getPort(), config.getScheme())
)
);
}
@Override
public void write(List<BaseRecord> records) {
if (records.isEmpty()) {
return;
}
try {
BulkRequest bulkRequest = new BulkRequest();
for (BaseRecord record : records) {
if (record instanceof BaseSPGRecord) {
BaseSPGRecord spgRecord = (BaseSPGRecord) record;
// 构建文档
Map<String, Object> document = buildDocument(spgRecord);
// 添加到批量请求
IndexRequest indexRequest = new IndexRequest(config.getIndexName())
.id(spgRecord.getId())
.source(document);
bulkRequest.add(indexRequest);
}
}
// 执行批量写入
if (bulkRequest.numberOfActions() > 0) {
esClient.bulk(bulkRequest, RequestOptions.DEFAULT);
}
} catch (Exception e) {
throw new RuntimeException("Failed to write to Elasticsearch", e);
}
}
private Map<String, Object> buildDocument(BaseSPGRecord record) {
Map<String, Object> document = new HashMap<>();
document.put("id", record.getId());
document.put("name", record.getName());
document.put("type", record.getRecordType().name());
// 添加属性
record.getProperties().forEach(property -> {
document.put(property.getName(), property.getValue());
});
return document;
}
@Override
public void close() throws Exception {
if (esClient != null) {
esClient.close();
}
}
}
/**
* Elasticsearch写入配置
*/
@Getter
@Setter
public class ElasticsearchSinkConfig extends BaseNodeConfig {
private String host;
private int port;
private String scheme; // "http" or "https"
private String indexName;
public ElasticsearchSinkConfig() {
super(NodeTypeEnum.CUSTOM_SINK);
}
}附录
A. 核心类路径索引
| 类名 | 完整路径 | 功能 |
|---|---|---|
BasePhysicalNode | com.antgroup.openspg.builder.core.physical.BasePhysicalNode | 物理节点基类 |
BaseSourceReader | com.antgroup.openspg.builder.runner.local.physical.source.BaseSourceReader | 数据源读取器基类 |
CsvFileSourceReader | com.antgroup.openspg.builder.runner.local.physical.source.impl.CsvFileSourceReader | CSV文件读取器 |
SourceReaderFactory | com.antgroup.openspg.builder.runner.local.physical.source.SourceReaderFactory | 数据源工厂 |
BaseProcessor | com.antgroup.openspg.builder.core.physical.process.BaseProcessor | 处理器基类 |
SPGTypeMappingProcessor | com.antgroup.openspg.builder.core.physical.process.SPGTypeMappingProcessor | 类型映射处理器 |
PythonProcessor | com.antgroup.openspg.builder.core.physical.process.PythonProcessor | Python处理器 |
BaseSinkWriter | com.antgroup.openspg.builder.runner.local.physical.sink.BaseSinkWriter | 写入器基类 |
GraphStoreSinkWriter | com.antgroup.openspg.builder.runner.local.physical.sink.impl.GraphStoreSinkWriter | 图存储写入器 |
SinkWriterFactory | com.antgroup.openspg.builder.runner.local.physical.sink.SinkWriterFactory | 写入器工厂 |
BaseRecord | com.antgroup.openspg.builder.model.record.BaseRecord | 记录基类 |
BuilderRecord | com.antgroup.openspg.builder.model.record.BuilderRecord | 构建记录 |
BaseSPGRecord | com.antgroup.openspg.builder.model.record.BaseSPGRecord | SPG记录基类 |
EntityRecord | com.antgroup.openspg.builder.model.record.EntityRecord | 实体记录 |
RelationRecord | com.antgroup.openspg.builder.model.record.RelationRecord | 关系记录 |
BuilderContext | com.antgroup.openspg.builder.core.runtime.BuilderContext | 构建上下文 |
B. 枚举类型
NodeTypeEnum - 节点类型枚举:
CSV_SOURCE- CSV数据源STRING_SOURCE- 字符串数据源SPG_TYPE_MAPPING- SPG类型映射PYTHON- Python处理器GRAPH_SINK- 图存储写入NEO4J_SINK- Neo4j写入
SPGRecordTypeEnum - SPG记录类型枚举:
ENTITY- 实体CONCEPT- 概念EVENT- 事件RELATION- 关系STANDARD- 标准类型
RecordAlterOperationEnum - 记录操作枚举:
INSERT- 插入UPDATE- 更新DELETE- 删除UPSERT- 插入或更新
C. 常见问题
Q1: 如何处理大文件?
A: 使用批量读取和分批处理:
java
context.setBatchSize(1000); // 设置批量大小
context.setParallelism(4); // 设置并行度Q2: 如何调试Pipeline?
A: 在每个节点的process/read/write方法中添加日志:
java
@Override
public List<BaseRecord> process(List<BaseRecord> inputs) {
log.info("Processing {} records", inputs.size());
// ... 处理逻辑
log.info("Processed {} records", outputs.size());
return outputs;
}Q3: 如何处理异常数据?
A: 在Processor中实现过滤和错误处理:
java
@Override
public List<BaseRecord> process(List<BaseRecord> inputs) {
return inputs.stream()
.filter(this::isValid)
.map(this::processRecord)
.filter(Objects::nonNull)
.collect(Collectors.toList());
}版本信息
- 文档版本: 1.0
- OpenSPG版本: 0.8
- 最后更新: 2025-12-13
许可证
本文档基于 Apache License 2.0 开源协议。