Mappings are pre-defined and declarative rules that encode the logic on how to transform a specific data source into Resources that eventually conform to targeted schemas supported by the configured Model.
This notebook specifically demonstrates the DictionaryMapping
wich is based on a JSON structure that represent a targeted structure along with Python code that will apply desired transformations on the data source.
from kgforge.core import KnowledgeGraphForge
A configuration file is needed in order to create a KnowledgeGraphForge session. A configuration can be generated using the notebook 00-Initialization.ipynb.
forge = KnowledgeGraphForge("../../configurations/forge.yml")
from kgforge.core import Resource
from kgforge.specializations.mappings import DictionaryMapping
scientists = [
{
"id": 123,
"name": "Marie Curie",
"gender": "female",
"middle_name": "Salomea",
},
{
"id": 456,
"name": "Albert Einstein",
"gender": "male",
"middle_name": "(missing)",
},
]
Note: DemoModel and RdfModel schemas have not been synchronized yet. The following cell is to be run with DemoModel.
forge.types()
Managed entity types: - Activity - Contribution - Dataset - Entity - Ontology - Person
forge.template("Contribution")
{ id: "" agent: { id: "" type: Agent } hadPlan: { id: "" type: Plan label: "" } hadRole: { id: "" type: Role label: "" } }
mapping_simple = DictionaryMapping("""
type: Contribution
agent:
{
type: Person
name: x.name
}
""")
resources_simple = forge.map(scientists, mapping_simple)
print(*resources_simple, sep="\n")
{ type: Contribution agent: { type: Person name: Marie Curie } } { type: Contribution agent: { type: Person name: Albert Einstein } }
mapping_na = DictionaryMapping("""
type: Contribution
agent:
{
type: Person
name: x.name
additionalName: x.middle_name
}
""")
print(forge.map(scientists[1], mapping_na))
{ type: Contribution agent: { type: Person additionalName: (missing) name: Albert Einstein } }
print(forge.map(scientists[1], mapping_na, na="(missing)"))
{ type: Contribution agent: { type: Person name: Albert Einstein } }
mapping_person = DictionaryMapping("""
id: forge.format("identifier", "persons", x.id)
type: Person
name: x.name
""")
mapping_association = DictionaryMapping("""
type: Contribution
agent: forge.format("identifier", "persons", x.id)
""")
resources_mapped = forge.map(scientists, [mapping_person, mapping_association])
len(resources_mapped) == 4
True
print(*resources_mapped, sep="\n")
{ id: https://kg.example.ch/persons/123 type: Person name: Marie Curie } { type: Contribution agent: https://kg.example.ch/persons/123 } { id: https://kg.example.ch/persons/456 type: Person name: Albert Einstein } { type: Contribution agent: https://kg.example.ch/persons/456 }
filepath = "mappings/scientists-database/DictionaryMapping/Contribution.hjson"
loaded = DictionaryMapping.load(filepath)
loaded.save(filepath)