入门
本页介绍如何开始使用此库,并设置您的首次 RDF 导入。
设置 Neo4j
要配置您的 Neo4j 图数据库,过程已简化:通过在资源的 URI 上建立唯一约束来初始化数据库。您可以通过执行以下 Cypher 片段来实现此操作
CREATE CONSTRAINT n10s_unique_uri FOR (r:Resource) REQUIRE r.uri IS UNIQUE;
此约束确保资源节点的 URI 唯一,从而简化集成过程。或者,您只需在 Python 代码中尝试打开存储时设置 create=True,系统会为您创建该约束。
加载数据
现在,您可以通过创建 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 应该会被填充为如下所示的图。
您也可以像这样逐个三元组写入图中
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("/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")))
前面的片段会在图中添加另一个节点,将 AuraDB 表示为通过 skos:narrower 与 Neo4j 相关的概念,在您的 AuraDB 图中将如下所示