Appearance
OpenSPG 非结构化数据知识抽取教程
目录
1. 概述
1.1 什么是非结构化数据知识抽取?
非结构化数据知识抽取是指从文本、Markdown、PDF等非结构化数据源中,识别和提取实体、属性和关系,并将它们映射到预定义的SPG Schema中,最终构建知识图谱。
1.2 应用场景
- 📄 文档知识库构建:从技术文档、产品手册中抽取知识
- 📰 新闻事件抽取:识别新闻中的人物、组织、事件及其关系
- 📚 学术论文分析:抽取论文中的作者、机构、研究主题
- 💼 企业知识管理:从内部文档中构建企业知识图谱
- 🏥 医疗病历分析:提取病历中的症状、诊断、治疗关系
1.3 OpenSPG抽取能力
非结构化文本
↓
文档读取 & 分割 (ParagraphSplitProcessor)
↓
文本块 (ChunkRecord)
↓
LLM/NLP抽取 (LLMNlExtractProcessor)
↓
子图记录 (SubGraphRecord: Nodes + Edges)
↓
SPG类型映射
↓
知识图谱 (Neo4j/TuGraph)2. 核心概念
2.1 Chunk(文本块)
Chunk 是文档分割后的最小处理单元。
java
public class ChunkRecord extends BaseRecord {
private final Chunk chunk;
public static class Chunk {
private String header; // 标题/章节
private String name; // 块名称
private String id; // 唯一标识
private String content; // 文本内容
private String type; // 类型(paragraph, section等)
private String summary; // 摘要
private String textIndex; // 文本索引
private String vecIndex; // 向量索引
}
}2.2 SubGraphRecord(子图记录)
SubGraphRecord 是抽取结果,包含实体节点和关系边。
java
public class SubGraphRecord extends BaseRecord {
private List<Node> resultNodes; // 实体节点列表
private List<Edge> resultEdges; // 关系边列表
public static class Node {
private String id; // 节点ID
private String bizId; // 业务ID
private String name; // 节点名称
private String label; // SPG类型标签
private Map<String, Object> properties; // 属性
}
public static class Edge {
private String id; // 边ID
private String from; // 源节点名称
private String fromId; // 源节点ID
private String fromType; // 源节点类型
private String to; // 目标节点名称
private String toId; // 目标节点ID
private String toType; // 目标节点类型
private String label; // 关系类型
private Map<String, Object> properties; // 关系属性
}
}2.3 处理器类型
| 处理器 | 功能 | 使用场景 |
|---|---|---|
ParagraphSplitProcessor | 文档分割 | 将长文档分割成段落或章节 |
LLMNlExtractProcessor | LLM自然语言抽取 | 使用大语言模型进行schema-free抽取 |
LLMBasedExtractProcessor | LLM结构化抽取 | 基于Schema的结构化抽取 |
UserDefinedExtractProcessor | 自定义抽取 | 使用自定义Python算子 |
3. 抽取流程
3.1 完整流程图
┌─────────────────┐
│ Markdown文档 │
│ (*.md, *.txt) │
└────────┬────────┘
│
▼
┌─────────────────┐
│ 文档读取 │ StringSourceReader
│ 读取文档内容 │
└────────┬────────┘
│
▼
┌─────────────────┐
│ 段落分割 │ ParagraphSplitProcessor
│ 分割成Chunk │ - 按段落分割
└────────┬────────┘ - 按章节分割
│ - 按语义分割
▼
┌─────────────────┐
│ Chunk列表 │ ChunkRecord[]
│ [Chunk1,...] │
└────────┬────────┘
│
▼
┌─────────────────┐
│ 实体关系抽取 │ LLMNlExtractProcessor
│ 提取Nodes+Edges│ - 实体识别 (NER)
└────────┬────────┘ - 关系抽取 (RE)
│ - 属性提取
▼
┌─────────────────┐
│ 子图记录 │ SubGraphRecord[]
│ (Nodes+Edges) │
└────────┬────────┘
│
▼
┌─────────────────┐
│ 类型映射 │ SPGTypeMappingProcessor
│ 映射到Schema │ - Entity → EntityRecord
└────────┬────────┘ - Relation → RelationRecord
│
▼
┌─────────────────┐
│ 图存储写入 │ GraphStoreSinkWriter
│ 保存到图数据库 │
└─────────────────┘3.2 数据流转示例
输入 Markdown文档:
markdown
# 阿里巴巴集团
阿里巴巴集团成立于1999年,由马云创立。公司总部位于杭州,
主要从事电子商务业务。马云担任董事局主席。
## 主要业务
- 淘宝网
- 天猫
- 阿里云步骤1:文档分割 → Chunk
json
[
{
"id": "chunk_001",
"name": "阿里巴巴集团",
"content": "阿里巴巴集团成立于1999年,由马云创立。公司总部位于杭州...",
"type": "paragraph"
},
{
"id": "chunk_002",
"name": "主要业务",
"content": "淘宝网、天猫、阿里云",
"type": "list"
}
]步骤2:实体关系抽取 → SubGraphRecord
json
{
"resultNodes": [
{
"id": "N1",
"name": "阿里巴巴集团",
"label": "Company",
"properties": {
"foundYear": "1999",
"location": "杭州",
"industry": "电子商务"
}
},
{
"id": "N2",
"name": "马云",
"label": "Person",
"properties": {}
}
],
"resultEdges": [
{
"from": "马云",
"fromType": "Person",
"to": "阿里巴巴集团",
"toType": "Company",
"label": "foundedBy",
"properties": {
"year": "1999"
}
},
{
"from": "马云",
"fromType": "Person",
"to": "阿里巴巴集团",
"toType": "Company",
"label": "worksAt",
"properties": {
"position": "董事局主席"
}
}
]
}4. Schema定义
4.1 定义实体类型
抽取前需要先定义SPG Schema,明确要抽取哪些实体和关系。
java
// 定义Person实体类型
EntityType personType = new EntityType(
new BasicInfo(
new SPGTypeIdentifier("default", "Person"),
"人物",
"自然人实体"
),
ParentTypeInfo.THING,
Arrays.asList(
createProperty("name", "姓名", BasicType.TEXT),
createProperty("age", "年龄", BasicType.INTEGER),
createProperty("nationality", "国籍", BasicType.TEXT),
createProperty("occupation", "职业", BasicType.TEXT)
),
null,
null
);
// 定义Company实体类型
EntityType companyType = new EntityType(
new BasicInfo(
new SPGTypeIdentifier("default", "Company"),
"公司",
"企业组织实体"
),
ParentTypeInfo.THING,
Arrays.asList(
createProperty("name", "公司名称", BasicType.TEXT),
createProperty("foundYear", "成立年份", BasicType.TEXT),
createProperty("location", "总部位置", BasicType.TEXT),
createProperty("industry", "所属行业", BasicType.TEXT)
),
null,
null
);4.2 定义关系类型
java
// 定义"创立"关系
Relation foundedByRelation = new Relation(
new BasicInfo(
new PredicateIdentifier("foundedBy"),
"创立",
"人物创立公司"
),
personType.toRef(), // 主体:Person
companyType.toRef(), // 客体:Company
false,
new RelationAdvancedConfig()
);
// 定义"工作于"关系
Relation worksAtRelation = new Relation(
new BasicInfo(
new PredicateIdentifier("worksAt"),
"工作于",
"人物在公司工作"
),
personType.toRef(),
companyType.toRef(),
false,
new RelationAdvancedConfig()
);
// 将关系添加到Person类型
personType.setRelations(Arrays.asList(foundedByRelation, worksAtRelation));4.3 提交Schema
java
SchemaAlterRequest request = new SchemaAlterRequest();
request.setProjectId(1L);
SchemaDraft draft = new SchemaDraft();
draft.setAlterSpgTypes(Arrays.asList(personType, companyType));
request.setSchemaDraft(draft);
schemaManager.alterSchema(request);5. 数据准备
5.1 准备Markdown文档
示例文档:company_intro.md
markdown
# 科技公司介绍
## 阿里巴巴集团
阿里巴巴集团控股有限公司(简称:阿里巴巴集团)成立于1999年,
由马云带领的18人团队在杭州创立。公司主要从事电子商务业务。
**创始人**:马云
**成立时间**:1999年
**总部地点**:中国杭州
**主要业务**:电子商务、云计算、数字媒体
马云曾担任阿里巴巴集团董事局主席,2019年卸任。现任CEO为张勇。
## 腾讯控股
腾讯控股有限公司成立于1998年11月,由马化腾、张志东等五位创始人共同创立。
公司总部位于深圳,主要产品包括微信、QQ等。
**创始人**:马化腾
**成立时间**:1998年
**总部地点**:中国深圳
**主要产品**:微信、QQ、王者荣耀
马化腾现任腾讯公司董事会主席兼首席执行官。5.2 支持的文档格式
| 格式 | 扩展名 | 说明 |
|---|---|---|
| Markdown | .md | 支持标题、列表、表格等 |
| 纯文本 | .txt | 普通文本文件 |
| Word | .docx | 需要预处理转换 |
| 需要PDF解析库 | ||
| HTML | .html | 需要HTML解析 |
6. 文档分割
6.1 为什么需要分割?
- 🔍 提高抽取精度:小块文本更容易提取准确的实体和关系
- 💰 降低LLM成本:减少单次调用的token数量
- ⚡ 加快处理速度:支持并行处理多个chunk
- 📊 便于溯源:记录每个知识来源于哪个文本片段
6.2 分割策略
策略1:按段落分割
python
# paragraph_splitter.py
def split_by_paragraph(chunk):
"""
按段落分割文档
Args:
chunk: 输入的文档chunk
Returns:
list[Chunk]: 分割后的chunk列表
"""
content = chunk['content']
paragraphs = content.split('\n\n') # 双换行符分割段落
chunks = []
for i, para in enumerate(paragraphs):
if para.strip():
chunks.append({
'id': f"{chunk['id']}_p{i}",
'name': f"{chunk['name']}_段落{i+1}",
'content': para.strip(),
'type': 'paragraph',
'header': chunk.get('header', '')
})
return chunks策略2:按章节分割
python
def split_by_section(chunk):
"""
按Markdown标题分割章节
"""
import re
content = chunk['content']
# 匹配Markdown标题(# 标题)
pattern = r'^(#{1,6})\s+(.+)$'
sections = []
current_section = None
current_content = []
for line in content.split('\n'):
match = re.match(pattern, line)
if match:
# 保存上一个章节
if current_section:
sections.append({
'id': f"{chunk['id']}_s{len(sections)}",
'name': current_section,
'content': '\n'.join(current_content).strip(),
'type': 'section',
'header': current_section
})
# 开始新章节
level = len(match.group(1))
current_section = match.group(2)
current_content = []
else:
current_content.append(line)
# 保存最后一个章节
if current_section:
sections.append({
'id': f"{chunk['id']}_s{len(sections)}",
'name': current_section,
'content': '\n'.join(current_content).strip(),
'type': 'section',
'header': current_section
})
return sections策略3:按Token大小分割
python
def split_by_token_size(chunk, max_tokens=500):
"""
按Token大小分割(适用于LLM处理)
"""
import tiktoken # OpenAI的tokenizer
encoding = tiktoken.get_encoding("cl100k_base")
content = chunk['content']
tokens = encoding.encode(content)
chunks = []
for i in range(0, len(tokens), max_tokens):
chunk_tokens = tokens[i:i + max_tokens]
chunk_text = encoding.decode(chunk_tokens)
chunks.append({
'id': f"{chunk['id']}_t{i//max_tokens}",
'name': f"{chunk['name']}_块{i//max_tokens + 1}",
'content': chunk_text,
'type': 'token_chunk',
'header': chunk.get('header', '')
})
return chunks6.3 Java端配置
java
// 创建段落分割配置
ParagraphSplitNodeConfig splitConfig = new ParagraphSplitNodeConfig();
// 配置Python算子
OperatorConfig operatorConfig = new OperatorConfig();
operatorConfig.setClassName("paragraph_splitter");
operatorConfig.setMethodName("split_by_section"); // 使用章节分割
splitConfig.setOperatorConfig(operatorConfig);
// 创建分割处理器
ParagraphSplitProcessor splitProcessor = new ParagraphSplitProcessor(
"split_1",
"Document Splitter",
splitConfig
);
// 初始化
splitProcessor.init(context);
// 处理文档
List<BaseRecord> chunks = splitProcessor.process(documents);7. 实体和关系抽取
7.1 基于LLM的Schema-Free抽取
Schema-Free抽取:不需要预先定义Schema,LLM自动识别实体和关系。
7.1.1 Python抽取算子
python
# llm_extractor.py
from typing import List, Dict, Any
import json
def extract_entities_and_relations(chunk: Dict[str, Any], config: str) -> List[Dict]:
"""
使用LLM从文本中抽取实体和关系
Args:
chunk: 文本块
config: JSON配置(包含LLM配置)
Returns:
List[SubGraphRecord]: 子图记录列表
"""
import openai
# 解析配置
cfg = json.loads(config)
llm_config = cfg.get('llm', {})
# 配置OpenAI
openai.api_key = llm_config.get('api_key')
openai.api_base = llm_config.get('base_url', 'https://api.openai.com/v1')
# 构建Prompt
prompt = f"""
请从以下文本中抽取实体和关系。
文本:
{chunk['content']}
要求:
1. 识别所有重要实体(人物、组织、地点、时间等)
2. 识别实体之间的关系
3. 提取实体的属性
请按以下JSON格式返回结果:
{{
"nodes": [
{{
"id": "N1",
"name": "实体名称",
"label": "实体类型(Person/Company/Location等)",
"properties": {{"属性名": "属性值"}}
}}
],
"edges": [
{{
"from": "源实体名称",
"fromType": "源实体类型",
"to": "目标实体名称",
"toType": "目标实体类型",
"label": "关系类型",
"properties": {{"属性名": "属性值"}}
}}
]
}}
"""
# 调用LLM
response = openai.ChatCompletion.create(
model=llm_config.get('model', 'gpt-4'),
messages=[
{"role": "system", "content": "你是一个知识抽取专家。"},
{"role": "user", "content": prompt}
],
temperature=0.1
)
# 解析结果
result_text = response.choices[0].message.content
# 提取JSON(可能被markdown包裹)
if "```json" in result_text:
result_text = result_text.split("```json")[1].split("```")[0]
result = json.loads(result_text)
# 转换为SubGraphRecord格式
subgraph = {
'resultNodes': result['nodes'],
'resultEdges': result['edges']
}
return [subgraph]7.1.2 Java端配置
java
// 创建LLM抽取配置
LLMNlExtractNodeConfig extractConfig = new LLMNlExtractNodeConfig(
new OperatorConfig(
"llm_extractor", // Python模块名
"extract_entities_and_relations" // Python函数名
)
);
// 创建抽取处理器
LLMNlExtractProcessor extractProcessor = new LLMNlExtractProcessor(
"extract_1",
"LLM Entity Relation Extractor",
extractConfig
);
// 初始化(需要LLM配置)
BuilderContext context = new BuilderContext();
context.setProjectId(1L);
// 项目配置中包含LLM配置
Project project = new Project();
JSONObject projectConfig = new JSONObject();
JSONObject llmConfig = new JSONObject();
llmConfig.put("api_key", "your-api-key");
llmConfig.put("base_url", "https://api.openai.com/v1");
llmConfig.put("model", "gpt-4");
projectConfig.put("llm", llmConfig);
project.setConfig(projectConfig.toJSONString());
context.setProject(JSON.toJSONString(project));
extractProcessor.init(context);
// 处理chunks
List<BaseRecord> chunks = splitProcessor.process(documents);
List<BaseRecord> subgraphs = extractProcessor.process(chunks);7.2 基于Schema的结构化抽取
Schema-Based抽取:基于预定义的Schema进行结构化抽取,抽取结果严格符合Schema定义。
7.2.1 Python抽取算子
python
# schema_based_extractor.py
def extract_with_schema(chunk: Dict[str, Any], schema_config: str) -> List[Dict]:
"""
基于Schema的结构化抽取
Args:
chunk: 文本块
schema_config: Schema配置
Returns:
List[SubGraphRecord]: 子图记录列表
"""
import openai
import json
# 解析Schema配置
schema = json.loads(schema_config)
# 构建Schema描述
entity_types = schema.get('entityTypes', [])
relation_types = schema.get('relationTypes', [])
schema_desc = "实体类型:\n"
for entity in entity_types:
schema_desc += f"- {entity['name']}: {entity['description']}\n"
schema_desc += f" 属性: {', '.join(entity['properties'])}\n"
schema_desc += "\n关系类型:\n"
for relation in relation_types:
schema_desc += f"- {relation['name']}: {relation['from']} -> {relation['to']}\n"
schema_desc += f" 描述: {relation['description']}\n"
# 构建Prompt
prompt = f"""
请严格按照以下Schema从文本中抽取实体和关系。
Schema定义:
{schema_desc}
文本:
{chunk['content']}
要求:
1. 只抽取Schema中定义的实体类型和关系类型
2. 实体必须包含Schema中定义的属性
3. 关系必须符合Schema中定义的from和to类型约束
请按JSON格式返回结果。
"""
# 调用LLM
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[
{"role": "system", "content": "你是一个结构化知识抽取专家。"},
{"role": "user", "content": prompt}
],
temperature=0.0 # 使用0温度以获得更确定的结果
)
# 解析结果
result_text = response.choices[0].message.content
if "```json" in result_text:
result_text = result_text.split("```json")[1].split("```")[0]
result = json.loads(result_text)
# 验证结果是否符合Schema
validated_result = validate_against_schema(result, schema)
return [validated_result]
def validate_against_schema(result: Dict, schema: Dict) -> Dict:
"""
验证抽取结果是否符合Schema
"""
valid_entity_types = {e['name'] for e in schema['entityTypes']}
valid_relation_types = {r['name'] for r in schema['relationTypes']}
# 过滤无效的实体
valid_nodes = [
node for node in result.get('nodes', [])
if node['label'] in valid_entity_types
]
# 过滤无效的关系
valid_edges = [
edge for edge in result.get('edges', [])
if edge['label'] in valid_relation_types
]
return {
'resultNodes': valid_nodes,
'resultEdges': valid_edges
}7.2.2 Schema配置
json
{
"entityTypes": [
{
"name": "Person",
"description": "自然人",
"properties": ["name", "age", "nationality", "occupation"]
},
{
"name": "Company",
"description": "公司组织",
"properties": ["name", "foundYear", "location", "industry"]
},
{
"name": "Product",
"description": "产品",
"properties": ["name", "category", "releaseDate"]
}
],
"relationTypes": [
{
"name": "foundedBy",
"from": "Person",
"to": "Company",
"description": "人物创立公司"
},
{
"name": "worksAt",
"from": "Person",
"to": "Company",
"description": "人物在公司工作"
},
{
"name": "produces",
"from": "Company",
"to": "Product",
"description": "公司生产产品"
}
]
}7.3 自定义NLP抽取
对于中文或特定领域,可以使用NER和RE模型进行抽取。
python
# nlp_extractor.py
def extract_with_nlp(chunk: Dict[str, Any], config: str) -> List[Dict]:
"""
使用NLP模型进行实体和关系抽取
"""
import spacy
# 加载NLP模型
nlp = spacy.load("zh_core_web_lg") # 中文模型
content = chunk['content']
doc = nlp(content)
nodes = []
edges = []
# 实体识别
entity_map = {}
for ent in doc.ents:
entity_id = f"E_{len(nodes)}"
entity_map[ent.text] = entity_id
nodes.append({
'id': entity_id,
'name': ent.text,
'label': map_spacy_label_to_spg(ent.label_),
'properties': {
'start': ent.start_char,
'end': ent.end_char
}
})
# 关系抽取(基于依存句法分析)
for sent in doc.sents:
for token in sent:
# 识别动词作为潜在关系
if token.pos_ == 'VERB':
# 查找主语和宾语
subject = None
obj = None
for child in token.children:
if child.dep_ in ['nsubj', 'nsubjpass']:
subject = child.text
elif child.dep_ in ['dobj', 'pobj']:
obj = child.text
if subject and obj:
if subject in entity_map and obj in entity_map:
edges.append({
'from': subject,
'fromId': entity_map[subject],
'fromType': get_entity_type(nodes, entity_map[subject]),
'to': obj,
'toId': entity_map[obj],
'toType': get_entity_type(nodes, entity_map[obj]),
'label': token.text, # 使用动词作为关系类型
'properties': {}
})
return [{
'resultNodes': nodes,
'resultEdges': edges
}]
def map_spacy_label_to_spg(spacy_label: str) -> str:
"""
映射Spacy实体标签到SPG类型
"""
mapping = {
'PERSON': 'Person',
'ORG': 'Company',
'GPE': 'Location',
'DATE': 'Date',
'PRODUCT': 'Product',
'MONEY': 'Money',
'LOC': 'Location'
}
return mapping.get(spacy_label, 'Entity')
def get_entity_type(nodes: List[Dict], entity_id: str) -> str:
"""
获取实体类型
"""
for node in nodes:
if node['id'] == entity_id:
return node['label']
return 'Entity'8. 完整示例
8.1 端到端示例代码
java
package com.example.openspg.extraction;
import com.antgroup.openspg.builder.core.runtime.BuilderContext;
import com.antgroup.openspg.builder.core.physical.process.*;
import com.antgroup.openspg.builder.runner.local.physical.source.impl.StringSourceReader;
import com.antgroup.openspg.builder.runner.local.physical.sink.impl.GraphStoreSinkWriter;
import com.antgroup.openspg.builder.model.pipeline.config.*;
import com.antgroup.openspg.builder.model.record.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
/**
* 从Markdown文档中抽取知识的完整示例
*/
public class MarkdownExtractionExample {
public static void main(String[] args) throws Exception {
// ========== 1. 读取Markdown文档 ==========
String markdownContent = Files.readString(
Paths.get("/data/company_intro.md")
);
// ========== 2. 创建构建上下文 ==========
BuilderContext context = createContext();
// ========== 3. 创建文档源 ==========
StringRecord document = new StringRecord(markdownContent);
List<BaseRecord> documents = Arrays.asList(document);
// ========== 4. 文档分割 ==========
System.out.println("开始分割文档...");
ParagraphSplitProcessor splitter = createSplitter();
splitter.init(context);
List<BaseRecord> chunks = splitter.process(documents);
System.out.println("文档分割完成,生成 " + chunks.size() + " 个chunk");
// ========== 5. 实体关系抽取 ==========
System.out.println("开始抽取实体和关系...");
LLMNlExtractProcessor extractor = createExtractor();
extractor.init(context);
List<BaseRecord> subgraphs = extractor.process(chunks);
System.out.println("抽取完成,生成 " + subgraphs.size() + " 个子图");
// 打印抽取结果
printExtractionResults(subgraphs);
// ========== 6. 转换为SPG记录 ==========
System.out.println("转换为SPG记录...");
List<BaseRecord> spgRecords = convertToSPGRecords(subgraphs);
System.out.println("转换完成,生成 " + spgRecords.size() + " 条SPG记录");
// ========== 7. 写入图存储 ==========
System.out.println("写入图数据库...");
GraphStoreSinkWriter writer = createGraphWriter();
writer.init(context);
writer.write(spgRecords);
System.out.println("写入完成!");
// ========== 8. 清理资源 ==========
splitter.close();
extractor.close();
writer.close();
System.out.println("知识抽取流程执行完毕!");
}
/**
* 创建构建上下文
*/
private static BuilderContext createContext() {
BuilderContext context = new BuilderContext();
context.setProjectId(1L);
context.setTaskId(100L);
context.setBatchSize(10);
context.setParallelism(1);
context.setModelExecuteNum(4); // LLM并发数
// 图存储配置
context.setGraphStoreUrl(
"neo4j://localhost:7687?user=neo4j&password=password&database=neo4j"
);
// Python环境配置
context.setPythonExec("/usr/bin/python3");
context.setPythonPaths("/opt/extractors");
// LLM配置
Project project = new Project();
project.setId(1L);
project.setNamespace("default");
JSONObject projectConfig = new JSONObject();
JSONObject llmConfig = new JSONObject();
llmConfig.put("api_key", System.getenv("OPENAI_API_KEY"));
llmConfig.put("base_url", "https://api.openai.com/v1");
llmConfig.put("model", "gpt-4");
projectConfig.put("llm", llmConfig);
project.setConfig(projectConfig.toJSONString());
context.setProject(JSON.toJSONString(project));
return context;
}
/**
* 创建文档分割器
*/
private static ParagraphSplitProcessor createSplitter() {
// 配置Python算子
OperatorConfig operatorConfig = new OperatorConfig();
operatorConfig.setClassName("paragraph_splitter");
operatorConfig.setMethodName("split_by_section");
ParagraphSplitNodeConfig config = new ParagraphSplitNodeConfig();
config.setOperatorConfig(operatorConfig);
return new ParagraphSplitProcessor(
"splitter_1",
"Markdown Splitter",
config
);
}
/**
* 创建实体关系抽取器
*/
private static LLMNlExtractProcessor createExtractor() {
// 配置Python算子
OperatorConfig operatorConfig = new OperatorConfig();
operatorConfig.setClassName("llm_extractor");
operatorConfig.setMethodName("extract_entities_and_relations");
LLMNlExtractNodeConfig config = new LLMNlExtractNodeConfig(operatorConfig);
return new LLMNlExtractProcessor(
"extractor_1",
"LLM Entity Relation Extractor",
config
);
}
/**
* 创建图存储写入器
*/
private static GraphStoreSinkWriter createGraphWriter() {
GraphStoreSinkNodeConfig config = new GraphStoreSinkNodeConfig();
config.setIsWriter(true);
return new GraphStoreSinkWriter(
"writer_1",
"Graph Store Writer",
config
);
}
/**
* 打印抽取结果
*/
private static void printExtractionResults(List<BaseRecord> subgraphs) {
System.out.println("\n========== 抽取结果 ==========");
for (int i = 0; i < subgraphs.size(); i++) {
SubGraphRecord subgraph = (SubGraphRecord) subgraphs.get(i);
System.out.println("\n子图 " + (i + 1) + ":");
// 打印节点
System.out.println(" 实体节点:");
for (SubGraphRecord.Node node : subgraph.getResultNodes()) {
System.out.println(" - " + node.getName() +
" (类型: " + node.getLabel() + ")");
if (!node.getProperties().isEmpty()) {
System.out.println(" 属性: " + node.getProperties());
}
}
// 打印边
System.out.println(" 关系边:");
for (SubGraphRecord.Edge edge : subgraph.getResultEdges()) {
System.out.println(" - " + edge.getFrom() +
" -[" + edge.getLabel() + "]-> " + edge.getTo());
if (!edge.getProperties().isEmpty()) {
System.out.println(" 属性: " + edge.getProperties());
}
}
}
System.out.println("\n==============================\n");
}
/**
* 转换SubGraphRecord为SPG记录
*/
private static List<BaseRecord> convertToSPGRecords(List<BaseRecord> subgraphs) {
List<BaseRecord> spgRecords = new ArrayList<>();
for (BaseRecord record : subgraphs) {
SubGraphRecord subgraph = (SubGraphRecord) record;
// 转换节点为EntityRecord
for (SubGraphRecord.Node node : subgraph.getResultNodes()) {
EntityRecord entityRecord = new EntityRecord(
node.getId(),
node.getName(),
new SPGTypeIdentifier("default", node.getLabel())
);
// 添加属性
for (Map.Entry<String, Object> prop : node.getProperties().entrySet()) {
SPGPropertyRecord property = new SPGPropertyRecord(
prop.getKey(),
String.valueOf(prop.getValue())
);
entityRecord.addProperty(property);
}
spgRecords.add(entityRecord);
}
// 转换边为RelationRecord
for (SubGraphRecord.Edge edge : subgraph.getResultEdges()) {
RelationRecord relationRecord = new RelationRecord(
edge.getId(),
edge.getFromId(),
edge.getToId(),
edge.getLabel(),
new SPGTypeIdentifier("default", edge.getFromType()),
new SPGTypeIdentifier("default", edge.getToType())
);
// 添加关系属性
for (Map.Entry<String, Object> prop : edge.getProperties().entrySet()) {
SPGPropertyRecord property = new SPGPropertyRecord(
prop.getKey(),
String.valueOf(prop.getValue())
);
relationRecord.addProperty(property);
}
spgRecords.add(relationRecord);
}
}
return spgRecords;
}
}8.2 运行结果
开始分割文档...
文档分割完成,生成 2 个chunk
开始抽取实体和关系...
抽取完成,生成 2 个子图
========== 抽取结果 ==========
子图 1:
实体节点:
- 阿里巴巴集团 (类型: Company)
属性: {foundYear=1999, location=杭州, industry=电子商务}
- 马云 (类型: Person)
属性: {}
- 张勇 (类型: Person)
属性: {position=CEO}
关系边:
- 马云 -[foundedBy]-> 阿里巴巴集团
属性: {year=1999}
- 马云 -[worksAt]-> 阿里巴巴集团
属性: {position=董事局主席, endYear=2019}
- 张勇 -[worksAt]-> 阿里巴巴集团
属性: {position=CEO}
子图 2:
实体节点:
- 腾讯控股 (类型: Company)
属性: {foundYear=1998, location=深圳}
- 马化腾 (类型: Person)
属性: {}
关系边:
- 马化腾 -[foundedBy]-> 腾讯控股
属性: {year=1998}
- 马化腾 -[worksAt]-> 腾讯控股
属性: {position=董事会主席兼CEO}
==============================
转换为SPG记录...
转换完成,生成 10 条SPG记录
写入图数据库...
写入完成!
知识抽取流程执行完毕!9. 高级技巧
9.1 提示词工程(Prompt Engineering)
优化LLM抽取效果的关键是设计好的Prompt。
技巧1:Few-Shot Learning
python
def build_few_shot_prompt(chunk_content: str) -> str:
"""
使用Few-Shot示例提升抽取效果
"""
examples = """
示例1:
文本:阿里巴巴集团成立于1999年,由马云创立。
结果:
{
"nodes": [
{"id": "N1", "name": "阿里巴巴集团", "label": "Company", "properties": {"foundYear": "1999"}},
{"id": "N2", "name": "马云", "label": "Person", "properties": {}}
],
"edges": [
{"from": "马云", "fromType": "Person", "to": "阿里巴巴集团", "toType": "Company", "label": "foundedBy"}
]
}
示例2:
文本:马化腾在深圳创立了腾讯公司,现任CEO。
结果:
{
"nodes": [
{"id": "N1", "name": "腾讯公司", "label": "Company", "properties": {"location": "深圳"}},
{"id": "N2", "name": "马化腾", "label": "Person", "properties": {}}
],
"edges": [
{"from": "马化腾", "fromType": "Person", "to": "腾讯公司", "toType": "Company", "label": "foundedBy"},
{"from": "马化腾", "fromType": "Person", "to": "腾讯公司", "toType": "Company", "label": "worksAt", "properties": {"position": "CEO"}}
]
}
"""
prompt = f"""
请参考以下示例,从文本中抽取实体和关系。
{examples}
现在请处理以下文本:
文本:{chunk_content}
结果:
"""
return prompt技巧2:Chain-of-Thought
python
def build_cot_prompt(chunk_content: str) -> str:
"""
使用思维链提升推理能力
"""
prompt = f"""
请按照以下步骤从文本中抽取知识:
文本:{chunk_content}
步骤1:识别所有实体
- 列出文本中提到的所有人物、组织、地点等实体
步骤2:提取实体属性
- 为每个实体提取相关的属性信息
步骤3:识别实体间关系
- 分析实体之间的关系(创建、工作、拥有等)
步骤4:组织为结构化输出
- 将识别的实体和关系组织为JSON格式
请开始分析:
"""
return prompt9.2 实体链接与消歧
python
# entity_linking.py
def link_entities(subgraph: Dict, knowledge_base_url: str) -> Dict:
"""
将抽取的实体链接到知识库中的标准实体
Args:
subgraph: 抽取的子图
knowledge_base_url: 知识库URL
Returns:
链接后的子图
"""
import requests
for node in subgraph['resultNodes']:
entity_name = node['name']
entity_type = node['label']
# 查询知识库
response = requests.get(
f"{knowledge_base_url}/search",
params={
'name': entity_name,
'type': entity_type
}
)
if response.status_code == 200:
results = response.json()
if results and len(results) > 0:
# 找到匹配的标准实体
matched_entity = results[0]
# 更新节点ID为标准ID
node['bizId'] = node['id'] # 保存原始ID
node['id'] = matched_entity['id']
# 合并属性
node['properties'].update(matched_entity.get('properties', {}))
return subgraph9.3 关系验证与过滤
python
def validate_relations(subgraph: Dict, schema: Dict) -> Dict:
"""
验证关系是否符合Schema约束
"""
valid_edges = []
# 构建节点索引
node_index = {node['id']: node for node in subgraph['resultNodes']}
# 获取Schema中的关系约束
relation_constraints = {}
for relation in schema.get('relationTypes', []):
key = relation['name']
relation_constraints[key] = {
'from': relation['from'],
'to': relation['to']
}
# 验证每条边
for edge in subgraph['resultEdges']:
relation_name = edge['label']
# 检查关系是否在Schema中定义
if relation_name not in relation_constraints:
print(f"警告:关系 {relation_name} 未在Schema中定义,已忽略")
continue
# 检查类型约束
constraint = relation_constraints[relation_name]
from_node = node_index.get(edge['fromId'])
to_node = node_index.get(edge['toId'])
if not from_node or not to_node:
print(f"警告:关系的节点不存在,已忽略")
continue
if (from_node['label'] == constraint['from'] and
to_node['label'] == constraint['to']):
valid_edges.append(edge)
else:
print(f"警告:关系 {relation_name} 的类型约束不匹配,已忽略")
subgraph['resultEdges'] = valid_edges
return subgraph9.4 增量抽取与更新
python
def incremental_extraction(new_documents: List[str],
existing_graph_url: str) -> List[Dict]:
"""
增量抽取:只处理新增文档,避免重复处理
"""
import hashlib
import requests
new_subgraphs = []
for doc in new_documents:
# 计算文档哈希
doc_hash = hashlib.md5(doc.encode()).hexdigest()
# 检查是否已处理
response = requests.get(
f"{existing_graph_url}/check_processed",
params={'doc_hash': doc_hash}
)
if response.json().get('processed', False):
print(f"文档 {doc_hash[:8]} 已处理,跳过")
continue
# 处理新文档
subgraph = extract_entities_and_relations({'content': doc}, {})
subgraph['doc_hash'] = doc_hash
new_subgraphs.append(subgraph)
return new_subgraphs10. 最佳实践
10.1 性能优化
1. 批量处理
java
// 批量处理chunks,提高吞吐量
context.setBatchSize(50); // 一次处理50个chunks
context.setModelExecuteNum(10); // 10个并发LLM调用2. 缓存LLM结果
python
import hashlib
import json
from functools import lru_cache
@lru_cache(maxsize=1000)
def cached_llm_extract(content_hash: str, config_str: str) -> str:
"""
缓存LLM抽取结果,避免重复调用
"""
# 实际的LLM调用
result = call_llm(content_hash, config_str)
return json.dumps(result)
def extract_with_cache(chunk: Dict, config: str) -> List[Dict]:
content = chunk['content']
content_hash = hashlib.md5(content.encode()).hexdigest()
# 从缓存获取或调用LLM
result_str = cached_llm_extract(content_hash, config)
return json.loads(result_str)3. 异步并发处理
java
// 使用线程池并发处理
ThreadPoolExecutor executor = new ThreadPoolExecutor(
10, // 核心线程数
20, // 最大线程数
60, // 空闲时间
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(100)
);
List<Future<SubGraphRecord>> futures = new ArrayList<>();
for (ChunkRecord chunk : chunks) {
Future<SubGraphRecord> future = executor.submit(() ->
extractProcessor.process(Arrays.asList(chunk)).get(0)
);
futures.add(future);
}
// 收集结果
List<SubGraphRecord> results = new ArrayList<>();
for (Future<SubGraphRecord> future : futures) {
results.add(future.get());
}10.2 质量保证
1. 多轮验证
python
def multi_pass_extraction(chunk: Dict, config: str) -> Dict:
"""
多轮抽取和验证,提高准确性
"""
# 第一轮:快速抽取
first_pass = extract_entities_and_relations(chunk, config)
# 第二轮:验证和补充
validation_prompt = f"""
请验证以下抽取结果是否准确,并补充遗漏的信息:
原文:{chunk['content']}
抽取结果:
{json.dumps(first_pass, ensure_ascii=False, indent=2)}
请返回修正后的结果。
"""
second_pass = call_llm_with_prompt(validation_prompt)
return second_pass2. 人工审核接口
java
public class HumanReviewService {
/**
* 标记需要人工审核的抽取结果
*/
public void markForReview(SubGraphRecord subgraph, String reason) {
ReviewTask task = new ReviewTask();
task.setSubgraph(subgraph);
task.setReason(reason);
task.setStatus("PENDING");
task.setCreatedTime(new Date());
reviewTaskRepository.save(task);
}
/**
* 检查是否需要人工审核
*/
public boolean needsReview(SubGraphRecord subgraph) {
// 规则1:实体数量异常
if (subgraph.getResultNodes().size() > 20) {
return true;
}
// 规则2:关系数量异常
if (subgraph.getResultEdges().size() > 50) {
return true;
}
// 规则3:置信度低
// ... 更多规则
return false;
}
}10.3 错误处理
java
public class RobustExtractionPipeline {
public List<BaseRecord> extractWithRetry(List<BaseRecord> chunks) {
List<BaseRecord> results = new ArrayList<>();
List<BaseRecord> failedChunks = new ArrayList<>();
for (BaseRecord chunk : chunks) {
try {
// 尝试抽取
List<BaseRecord> extracted = extractProcessor.process(
Arrays.asList(chunk)
);
results.addAll(extracted);
} catch (Exception e) {
log.error("抽取失败: " + chunk, e);
failedChunks.add(chunk);
}
}
// 重试失败的chunks
if (!failedChunks.isEmpty()) {
log.info("重试 " + failedChunks.size() + " 个失败的chunks");
for (BaseRecord chunk : failedChunks) {
try {
Thread.sleep(1000); // 等待1秒
List<BaseRecord> extracted = extractProcessor.process(
Arrays.asList(chunk)
);
results.addAll(extracted);
} catch (Exception e) {
log.error("重试仍然失败: " + chunk, e);
// 保存到失败队列,供后续人工处理
saveToFailureQueue(chunk, e);
}
}
}
return results;
}
}10.4 监控与日志
java
public class ExtractionMonitor {
private MetricsRegistry metrics = new MetricsRegistry();
public void recordExtraction(SubGraphRecord subgraph, long duration) {
// 记录指标
metrics.counter("extraction.total").inc();
metrics.timer("extraction.duration").update(duration, TimeUnit.MILLISECONDS);
metrics.histogram("extraction.entities").update(subgraph.getResultNodes().size());
metrics.histogram("extraction.relations").update(subgraph.getResultEdges().size());
// 详细日志
log.info("抽取完成 - " +
"实体数: " + subgraph.getResultNodes().size() + ", " +
"关系数: " + subgraph.getResultEdges().size() + ", " +
"耗时: " + duration + "ms"
);
}
public void recordError(Throwable error, String context) {
metrics.counter("extraction.errors").inc();
log.error("抽取错误 [" + context + "]: " + error.getMessage(), error);
}
}附录
A. 常见问题
Q1: LLM抽取效果不好怎么办?
A:
- 优化Prompt,使用Few-Shot示例
- 调整temperature参数(降低到0.1)
- 使用更强大的模型(GPT-4)
- 对结果进行多轮验证
Q2: 如何处理中文文本?
A:
- 使用支持中文的LLM(GPT-4、文心一言等)
- 或使用中文NER模型(如spaCy的中文模型)
- Prompt使用中文描述
Q3: 抽取速度太慢怎么办?
A:
- 增加并发数(
modelExecuteNum) - 使用更快的模型(GPT-3.5-turbo)
- 启用结果缓存
- 优化文档分割策略,减少chunk数量
Q4: 如何保证抽取的一致性?
A:
- 使用Schema-Based抽取
- 实施实体链接和消歧
- 建立标准的实体和关系字典
- 定期人工审核样本
B. 参考资源
- OpenSPG官方文档: https://openspg.yuque.com/ndx6g9/docs
- KAG论文: https://arxiv.org/abs/2409.13731
- Prompt Engineering指南: https://www.promptingguide.ai/
C. Python依赖安装
bash
# 基础依赖
pip install openai tiktoken spacy
# 中文NLP模型
python -m spacy download zh_core_web_lg
# 其他工具
pip install requests hashlib版本信息
- 文档版本: 1.0
- OpenSPG版本: 0.8
- 最后更新: 2025-12-13
许可证
本文档基于 Apache License 2.0 开源协议。