> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-docs-zh.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# SAP HANA Cloud Knowledge Graph Engine

> SAP HANA Cloud Knowledge Graph 是 SAP HANA Cloud 数据库中集成的完整知识图谱解决方案。

[SAP HANA Cloud Knowledge Graph](https://help.sap.com/docs/hana-cloud-database/sap-hana-cloud-sap-hana-database-knowledge-graph-guide/sap-hana-cloud-sap-hana-database-knowledge-graph-engine-guide) 是 `SAP HANA Cloud` 数据库中集成的完整知识图谱解决方案。

## 设置与安装

您必须拥有已启用 **triple store** 功能的 SAP HANA Cloud 实例。
对于详细操作步骤，请参考：[Enable Triple Store](https://help.sap.com/docs/hana-cloud-database/sap-hana-cloud-sap-hana-database-knowledge-graph-guide/enable-triple-store/)

要使用 SAP HANA 知识图谱引擎与 LangChain 结合，请安装 `langchain-hana` 包：

```python theme={null}
pip install langchain_hana
```

首先，创建与您的 SAP HANA Cloud 实例的连接。

```python theme={null}
import os

from dotenv import load_dotenv
from hdbcli import dbapi

# Load environment variables if needed
load_dotenv()

# Establish connection to SAP HANA Cloud
connection = dbapi.connect(
    address=os.environ.get("HANA_DB_ADDRESS"),
    port=os.environ.get("HANA_DB_PORT"),
    user=os.environ.get("HANA_DB_USER"),
    password=os.environ.get("HANA_DB_PASSWORD")
)
```

然后，导入 `HanaRdfGraph` 类

```python theme={null}
from langchain_hana import HanaRdfGraph
```

## 创建 `HanaRdfGraph` 实例

构造函数需要以下参数：

* **`connection`**: 一个活跃的 `hdbcli.dbapi.connect(...)` 实例
* **`graph_uri`**: 您的 RDF 数据所在的命名图（或 `"DEFAULT"`）
* **任选以下之一**：
  1. **`ontology_query`**: 用于提取模式三元组的 SPARQL CONSTRUCT 查询
  2. **`ontology_uri`**: 托管本体图 URI
  3. **`ontology_local_file`** + **`ontology_local_file_format`**: 本地 Turtle/RDF 文件
  4. **`auto_extract_ontology=True`**（不推荐用于生产环境——见注）

`graph_uri` vs. Ontology

* **`graph_uri`**:
  您 SAP HANA Cloud 实例中包含实例数据（有时超过 100k 个三元组）的命名图。
  如果提供 `None`、`""` 或 `"DEFAULT"`，则使用默认图。
* **Ontology**: 描述类、属性、域、范围、标签、注释和子类关系的精简模式（通常 50-100 个三元组）。本体指导 SPARQL 生成和结果解析。

### 使用 **DEFAULT** 图创建实例

关于 DEFAULT 图的更多信息，请参考 [DEFAULT Graph and Named Graphs](https://help.sap.com/docs/hana-cloud-database/sap-hana-cloud-sap-hana-database-knowledge-graph-guide/default-graph-and-named-graphs)。

```python theme={null}

graph = HanaRdfGraph(
    connection=connection,
    auto_extract_ontology=True,
)

# graph = HanaRdfGraph(
#     connection=connection,
#     graph_uri="DEFAULT",
#     auto_extract_ontology=True,
# )

# graph = HanaRdfGraph(
#     connection=connection,
#     graph_uri="",
#     auto_extract_ontology=True,
# )
```

### 使用 `graph_uri` 创建实例

```python theme={null}
graph = HanaRdfGraph(
    connection=connection,
    graph_uri="http://example.org/movies",
    auto_extract_ontology=True,
)
```

### 使用远程 `ontology_uri` 创建实例

从托管图 URI 加载模式。

```python theme={null}
graph = HanaRdfGraph(
    connection=connection,
    ontology_uri="<your_ontology_graph_uri>",
)
```

### 使用自定义 `ontology_query` 创建实例

使用自定义 `CONSTRUCT` 查询选择性提取模式三元组。

```python theme={null}
ontology_query = """
    PREFIX owl: <http://www.w3.org/2002/07/owl#>
    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
    CONSTRUCT {?cls rdf:type owl:Class . ?cls rdfs:label ?clsLabel . ?rel rdf:type ?propertyType . ?rel rdfs:label ?relLabel . ?rel rdfs:domain ?domain . ?rel rdfs:range ?range .}
    FROM <kgdocu_movies>
    WHERE { # get properties
        {SELECT DISTINCT ?domain ?rel ?relLabel ?propertyType ?range
        WHERE {
            ?subj ?rel ?obj .
            ?subj a ?domain .
            OPTIONAL{?obj a ?rangeClass .}
            FILTER(?rel != rdf:type)
            BIND(IF(isIRI(?obj) = true, owl:ObjectProperty, owl:DatatypeProperty) AS ?propertyType)
            BIND(COALESCE(?rangeClass, DATATYPE(?obj)) AS ?range)
            BIND(STR(?rel) AS ?uriStr)       # Convert URI to string
            BIND(REPLACE(?uriStr, "^.*[/#]", "") AS ?relLabel)
        }}
        UNION { # get classes
            SELECT DISTINCT ?cls ?clsLabel
            WHERE {
                ?instance a/rdfs:subClassOf* ?cls .
                FILTER (isIRI(?cls)) .
                BIND(STR(?cls) AS ?uriStr)       # Convert URI to string
                BIND(REPLACE(?uriStr, "^.*[/#]", "") AS ?clsLabel)
            }
        }
    }
"""

# can provide the graph_uri param as well if needed
graph = HanaRdfGraph(
    connection=connection,
    ontology_query=ontology_query,
)
```

### 使用本地 RDF 文件创建实例

(`ontology_local_file` + `ontology_local_file_format`): 从本地 RDF 本体文件加载模式。

支持的 RDF 格式包括 `Turtle`、`RDF/XML`、`JSON-LD`、`N-Triples`、`Notation-3`、`Trig`、`Trix`、`N-Quads`。

```python theme={null}
graph = HanaRdfGraph(
    connection=connection,
    ontology_local_file="<your_ontology_file_path>", # e.g., "ontology.ttl"
    ontology_local_file_format="<your_ontology_file_format>",  # e.g., "Turtle", "RDF/XML", "JSON-LD", "N-Triples", "Notation-3", "Trig", "Trix", "N-Quads"
)
```

### 自动提取本体

(`auto_extract_ontology=True`): 从实例数据直接推导本体信息。

```python theme={null}
graph = HanaRdfGraph(
    connection=connection,
    graph_uri="<your_graph_uri>",
    auto_extract_ontology=True,
)
```

> **注意**: 自动提取不推荐用于生产环境——它通常会遗漏 `rdfs:label`、`rdfs:comment` 和 `rdfs:subClassOf` 等重要三元组。

## 执行 SPARQL 查询

您可以使用 `query()` 方法执行任意 SPARQL 查询（`SELECT`、`ASK`、`CONSTRUCT` 等）。

该函数具有以下参数：

* **query**: SPARQL 查询字符串
* **content\_type**: 输出格式（默认 CSV）

请使用以下字符串对应相应格式：

* CSV: `"sparql-results+xml"`
* JSON: `"sparql-results+json"`
* XML: `"sparql-results+csv"`
* TSV: `"sparql-results+tsv"`

> **注意**: CONSTRUCT 和 ASK 查询分别返回 `turtle` 和 `boolean` 格式。

让我们向 `Puppets` 图插入数据。

```python theme={null}
cursor = connection.cursor()
try:
    result = cursor.callproc(
        "SYS.SPARQL_EXECUTE", (
        """
        INSERT DATA {
        GRAPH <Puppets> {
            <P1> a <Puppet>; <name> "Ernie"; <show> "Sesame Street".
            <P2> a <Puppet>; <name> "Bert"; <show> "Sesame Street" .
            }
        }
        """, "", "?", "?"
        )
    )
    response = result[2]
except dbapi.Error as db_error:
    raise RuntimeError(
        f'The database query failed: '
        f'{db_error.errortext.split("; Server Connection")[0]}'
    )
finally:
    cursor.close()
```

然后，我们为 `Puppets` 图创建实例。

```python theme={null}
puppets_graph = HanaRdfGraph(
    connection=connection,
    graph_uri="Puppets",
    auto_extract_ontology=True,
)
```

给定的查询列出 `Puppets` 图中的所有三元组。

```python theme={null}
query = """
SELECT ?s ?p ?o
WHERE {
    GRAPH <Puppets> {
        ?s ?p ?o .
    }
}
ORDER BY ?s
"""

result = puppets_graph.query(query)
print(result)
```

```output theme={null}
s,p,o
P1,name,Ernie
P1,show,Sesame Street
P1,http://www.w3.org/1999/02/22-rdf-syntax-ns#type,Puppet
P2,name,Bert
P2,show,Sesame Street
P2,http://www.w3.org/1999/02/22-rdf-syntax-ns#type,Puppet
```

***

> 官方原文：[src/oss/python/integrations/graphs/sap\_hana\_rdf\_graph.mdx](https://github.com/langchain-ai/docs/blob/main/src/oss/python/integrations/graphs/sap_hana_rdf_graph.mdx) · 非官方翻译，译文由 AI 生成，以英文原文为准。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.