SwissDataScienceCenter / calamus

A JSON-LD Serialization Libary for Python
Apache License 2.0
29 stars 12 forks source link

feat: add local db support with neo4j #47

Open rokroskar opened 3 years ago

rokroskar commented 3 years ago

This adds simple support for retrieving missing data from a neo4j instance.

Given this setup:

class Author:
    def __init__(self, _id, name, organization):
        self._id = _id
        self.name = name

class Book:
    def __init__(self, _id, name, author):
        self._id = _id
        self.name = name
        self.author = author

class AuthorSchema(JsonLDSchema):
    """Author schema."""
    name = fields.String(schema.name)
    _id = fields.Id()

    class Meta:
        """Meta class."""
        rdf_type = schema.Person
        model = Author

class BookSchema(JsonLDSchema):
    _id = fields.Id()
    name = fields.String(schema.name)
    author = fields.Nested(schema.author, AuthorSchema, missing=None)

    class Meta:
        rdf_type = schema.Book
        model = Book

One can retrieve the data for a single book with

from calamus.backends.neo4j import CalamusNeo4JBackend
neo = CalamusNeo4JBackend()
neo.initialize()

data = neo.fetch_by_id('http://example.com/books/1')

The full data, including the author information can then be obtained with

book = BookSchema(session=neo).load(data)

A full example

addresses #10