入门指南

此页面介绍如何开始使用此库,并设置首次 RDF 导入。

设置 Neo4j

要配置 Neo4j 图数据库,过程很简单:通过对资源的 URI 建立唯一性约束来初始化数据库。您可以通过执行以下 Cypher 片段来完成此操作

CREATE CONSTRAINT n10s_unique_uri FOR (r:Resource) REQUIRE r.uri IS UNIQUE;

此约束确保资源节点 URI 的唯一性,简化了集成过程。或者,您也可以在尝试在 Python 代码中打开存储时简单地设置 create=True,它将为您创建约束。

设置 Python 环境

可以使用 Python 的包管理工具 pip 安装 rdflib-neo4j

$ pip install rdflib-neo4j

加载数据

现在,通过建立 RDFLib 图并使用它解析您的 RDF 数据,可以将 RDF 数据无缝导入到您的 Neo4j 本地部署或 Aura 实例中。每个单独的三元组都会在您的 Neo4j 数据库(无论是在 Aura 上还是本地部署)中进行透明持久化。以下是实现此集成的分步指南

您可以从 RDF 文档导入数据(例如使用 N-Triples 序列化的此文档

from rdflib_neo4j import Neo4jStoreConfig, Neo4jStore, HANDLE_VOCAB_URI_STRATEGY
from rdflib import Graph

# set the configuration to connect to your Aura DB
AURA_DB_URI="your_db_uri"
AURA_DB_USERNAME="neo4j"
AURA_DB_PWD="your_db_pwd"

auth_data = {'uri': AURA_DB_URI,
             'database': "neo4j",
             'user': AURA_DB_USERNAME,
             'pwd': AURA_DB_PWD}

# Define your custom mappings & store config
config = Neo4jStoreConfig(auth_data=auth_data,
                          custom_prefixes=prefixes,
                          handle_vocab_uri_strategy=HANDLE_VOCAB_URI_STRATEGY.IGNORE,
                          batching=True)

file_path = 'https://github.com/jbarrasa/gc-2022/raw/main/search/onto/concept-scheme-skos.ttl'

# Create the RDF Graph, parse & ingest the data to Neo4j, and close the store(If the field batching is set to True in the Neo4jStoreConfig, remember to close the store to prevent the loss of any uncommitted records.)
neo4j_aura = Graph(store=Neo4jStore(config=config))
# Calling the parse method will implictly open the store
neo4j_aura.parse(file_path, format="ttl")
neo4j_aura.close(True)

导入的文件包含从 Wikidata 中提取并使用 SKOS 序列化的技术分类。运行前面的代码片段后,您的 Aura DB/Neo4j DB 将填充如下所示的图

graph view aura

您也可以像这样逐个三元组地写入图

import rdflib
from rdflib_neo4j import Neo4jStoreConfig, Neo4jStore, HANDLE_VOCAB_URI_STRATEGY
from rdflib import Graph, RDF, SKOS

# Set up your store config
config = Neo4jStoreConfig(auth_data=auth_data,
                          handle_vocab_uri_strategy=HANDLE_VOCAB_URI_STRATEGY.IGNORE,
                          batching=False)

# Create the graph and open the store
neo4j_aura = Graph(store=Neo4jStore(config=config))
neo4j_aura.open(config)

aura = rdflib.URIRef("https://neo4j.ac.cn/voc/tech#AuraDB")

neo4j_aura.add((aura, RDF.type, SKOS.Concept))
neo4j_aura.add((aura, SKOS.prefLabel, rdflib.Literal("AuraDB")))
neo4j_aura.add((aura, SKOS.broader, rdflib.URIRef("http://www.wikidata.org/entity/Q1628290")))

前面的片段将通过 skos:narrower 添加另一个节点到图中,该节点表示 AuraDB 是与 Neo4j 相关联的概念,在您的 AuraDB 图中看起来如下所示

graph view aura detail
© . All rights reserved.