← 返回 Semantica 专题首页 🌱 SEMANTICA · COOKBOOK · 入门系列

三元组存储入门

Semantica 官方 Cookbook 中文翻译 · 第 20 / 37 篇

📦 semantica 🕸️ 知识图谱 🔎 GraphRAG

本 notebook 介绍 Semantica 三元组存储模块,该模块允许你使用行业标准的 RDF 三元组存储来存储和查询知识图谱数据。

1什么是三元组存储?

三元组存储(或 RDF 存储)是一种针对存储和检索三元组而优化的数据库:主语 - 谓词 - 宾语。 例如:Alice(主语)knows(谓词)Bob(宾语)。

Semantica 支持: - Blazegraph(默认,高性能) - Apache Jena(擅长推断) - RDF4J(标准 Java 框架)

import sys
import os

# 将项目根目录添加到路径,以便导入本地版本的 semantica
sys.path.append(os.path.abspath('../../'))

# 如果在 Google Colab 中运行,取消注释以下行以安装依赖
# !pip install -q semantica
# 导入 TripletStore 类
from semantica.triplet_store import TripletStore
from semantica.semantic_extract.triplet_extractor import Triplet

21. 连接到存储

要使用三元组存储,你需要一个正在运行的后端。在此示例中,我们假设一个 Blazegraph 实例正在本地运行。

注意: 如果你没有正在运行的存储,下面的代码展示了你会如何连接。

# 连接到 Blazegraph 实例
# 你也可以使用 backend="jena" 或 backend="rdf4j"
store = TripletStore(
    backend="blazegraph",
    endpoint="http://localhost:9999/blazegraph"
)

# 检查连接状态
if hasattr(store._store_backend, 'connected') and store._store_backend.connected:
    print(f"Successfully connected to {store.backend_type} store at {store.endpoint}")
else:
    print(f"Warning: Could not connect to {store.backend_type} at {store.endpoint}")
    print("Operations requiring a live store connection will be skipped or fail.")

32. 创建三元组

我们使用 Triplet 类来定义我们的数据。

# 定义单个三元组
triplet1 = Triplet(
    subject="http://example.org/Alice",
    predicate="http://xmlns.com/foaf/0.1/knows",
    object="http://example.org/Bob"
)

print(f"Created triplet: {triplet1.subject} -> {triplet1.predicate} -> {triplet1.object}")

43. 添加数据

你可以逐个或批量添加三元组。

from semantica.utils.exceptions import ProcessingError

try:
    # 添加单个三元组
    store.add_triplet(triplet1)
    print("Added single triplet successfully.")

    # 创建更多三元组
    triplets = [
        Triplet(
            subject="http://example.org/Bob",
            predicate="http://xmlns.com/foaf/0.1/knows",
            object="http://example.org/Charlie"
        ),
        Triplet(
            subject="http://example.org/Charlie",
            predicate="http://xmlns.com/foaf/0.1/knows",
            object="http://example.org/David"
        )
    ]

    # 批量添加
    store.add_triplets(triplets)
    print("Added bulk triplets successfully.")

except ProcessingError as e:
    print(f"Operation skipped: {e}")
except Exception as e:
    print(f"An error occurred: {e}")

54. 查询数据(SPARQL)

使用 SPARQL 查询从存储中检索数据。

# 简单查询以获取所有三元组(限制为 10 条)
query = """
SELECT ?s ?p ?o
WHERE {
  ?s ?p ?o
}
LIMIT 10
"""

try:
    results = store.execute_query(query)
    print("Query Results:", results)
except ProcessingError as e:
    print(f"Query skipped: {e}")
except Exception as e:
    print(f"An error occurred: {e}")

65. 删除数据

当不再需要三元组时将其删除。

# 从存储中删除单个三元组
store.delete_triplet(triplet1)
print("Deleted triplet1")

7下一步

查看 cookbook/advanced 文件夹中的高级三元组存储指南,了解更复杂的操作,如批量加载优化、事务和高级 SPARQL 特性。