export

package
v0.1.0-alpha.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 15, 2026 License: MIT Imports: 13 Imported by: 0

README

RDF Export

Serializes []message.Triple to standard RDF formats using the vocabulary registry for IRI resolution.

Supported Formats

Format Extension Description
Turtle .ttl Compact, human-readable with prefix declarations and subject grouping
NTriples .nt Line-based, one triple per line, fully expanded IRIs
JSONLD .jsonld JSON with @context and @graph for web APIs

Usage

import "github.com/c360studio/semengine/vocabulary/export"

triples := []message.Triple{
    {Subject: "acme.ops.robotics.gcs.drone.001", Predicate: "robotics.battery.level", Object: 85.5},
    {Subject: "acme.ops.robotics.gcs.drone.001", Predicate: "robotics.flight.armed", Object: true},
}

// Write Turtle to a writer
err := export.Serialize(os.Stdout, triples, export.Turtle)

// Get N-Triples as a string
s, err := export.SerializeToString(triples, export.NTriples)

IRI Resolution

The package resolves dotted-notation identifiers to IRIs automatically:

Subjects are converted based on entity ID structure (export.SubjectIRI(subject, base)):

  • Valid 6-part entity IDs: acme.ops.robotics.gcs.drone.001 becomes {base}/entities/acme/ops/robotics/gcs/drone/001
  • Blank-node labels matching W3C Turtle / N-Triples BLANK_NODE_LABEL (_:label) are emitted as RDF blank nodes
  • Other subjects: dots are converted to slashes under {base}/subjects/

Predicates resolve through the vocabulary registry:

  • Registered predicates use their StandardIRI (e.g., robotics.battery.level with a registered IRI maps to that IRI)
  • Unregistered predicates that are valid http:// or https:// IRIs pass through unchanged
  • Other unregistered predicates generate {base}/predicates/domain/category/property

Objects are classified by a total order, most specific first (gh#1267):

  1. the triple's own Datatype hint — a statement about THIS value;
  2. the predicate's declared DataType — a statement about the PREDICATE, and the only place a fact the authoritative JSON round trip erased can come from;
  3. observation of the Go type — what the serializer can see for itself.

Observation is strictly the fallback, never a competing authority — but a declaration the observed value cannot carry is ignored for that triple rather than applied. This package is a serializer: it renders what is there, and never emits a lexical form the observed value does not support.

Declared datatype → RDF. This table is the whole semantic-web surface of the declaration vocabulary; ADR-107 keeps it here, at the edge, and out of the registry:

Declared (vocabulary.DataType*) RDF Datatype Output
entity_id Resource / Blank node <iri> or _:label
string xsd:string "text" (datatype omitted) — a confirmation, not an override: the classifier falls through to observation, so an entity-ID-shaped, blank-node, or absolute-IRI value under a string declaration still emits as a resource/blank node
int xsd:integer 5
float xsd:double "85.5"^^xsd:double
bool xsd:boolean true
datetime xsd:dateTime "2024-01-15T10:30:00Z"^^xsd:dateTime
json rdf:JSON "{\"k\":1}"^^rdf:JSON

Go type → RDF, for a predicate that declares nothing:

Go Type RDF Datatype Output
string (entity ID) Resource <iri>
string (blank node _:label) Blank node _:label
string (absolute IRI: http://, https://, urn:) Resource <iri>
string (other) xsd:string "text"
int, int64, etc. xsd:integer 42
float64 xsd:double "85.5"^^xsd:double
bool xsd:boolean true
time.Time xsd:dateTime "2024-01-15T10:30:00Z"^^xsd:dateTime

A per-triple message.EntityReferenceDatatype ("@id") marks an object as an entity reference or blank node and serializes as an IRI or blank node, exactly as a predicate declared entity_id does. Prefixed datatypes are expanded for xsd: and rdf:; any other prefix reaches the output unexpanded.

Options

WithBaseIRI

Override the default base IRI used for generated subject and predicate URIs:

err := export.Serialize(w, triples, export.Turtle,
    export.WithBaseIRI("https://example.org"))
WithSubjectIRIFunc

Provide a custom function to map entity ID strings to IRIs. When set, this replaces the default subject IRI generation entirely (WithBaseIRI has no effect on subjects):

err := export.Serialize(w, triples, export.JSONLD,
    export.WithSubjectIRIFunc(func(subject string) string {
        return "https://example.org/entities/" + subject
    }))

Prefix Management

Turtle and JSON-LD output automatically compact IRIs using well-known prefixes (OWL, SKOS, Dublin Core, PROV-O, Schema.org, FOAF, SSN/SOSA, XSD) and any prefixes registered via export.Register(prefix, namespace) or export.RegisterPrefixes(prefixes). Only prefixes that appear in the output are declared.

API

Function Description
Serialize(w, triples, format, ...opts) Write triples to an io.Writer
SerializeToString(triples, format, ...opts) Return serialized output as a string
SubjectIRI(subject, base) Convert a 6-part entity ID or fallback subject string to its canonical IRI
Register(prefix, namespace) Register a prefix → namespace binding for Turtle and JSON-LD compaction
RegisterPrefixes(prefixes) Atomically validate and register a batch of vocabulary.PrefixSpec bindings
  • Vocabulary Package - Registry API, predicate registration, IRI mappings
  • ADR-107 - Semantic Web vocabulary at the export edge

Documentation

Overview

Package export serializes []message.Triple to standard RDF formats.

Supported formats:

  • Turtle (.ttl) — compact, human-readable with prefix declarations and subject grouping
  • N-Triples (.nt) — line-based, one triple per line, no abbreviations
  • JSON-LD (.jsonld) — JSON with @context and @graph for web APIs

The package uses the existing vocabulary infrastructure for IRI resolution:

  • Registered predicates map to their StandardIRI via vocabulary.GetPredicateMetadata; unregistered valid http:// and https:// predicate IRIs pass through unchanged
  • Entity ID subjects are parsed via message.ParseEntityID and converted to hierarchical IRIs via SubjectIRI; W3C Turtle / N-Triples blank-node labels (_:label) are preserved in both subject and object positions
  • Object values are typed using XSD datatypes based on Go type inference

Basic usage:

triples := []message.Triple{
    {Subject: "acme.ops.robotics.gcs.drone.001", Predicate: "robotics.battery.level", Object: 85.5},
    {Subject: "acme.ops.robotics.gcs.drone.001", Predicate: "robotics.flight.armed", Object: true},
}

// Write Turtle to stdout
err := export.Serialize(os.Stdout, triples, export.Turtle)

// Get N-Triples as a string
s, err := export.SerializeToString(triples, export.NTriples)

// Custom base IRI
err = export.Serialize(w, triples, export.JSONLD, export.WithBaseIRI("https://example.org"))

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Register

func Register(prefix, namespace string) error

Register adds a prefix → namespace binding to the export prefix table. It is idempotent: registering the same prefix with the same namespace twice is a no-op. Registering the same prefix with a different namespace returns an error so collisions surface loudly rather than silently shadowing.

Intended use is from a package init() in a downstream vocabulary package, so registrations land before any exporter runs. The function is safe to call at runtime as well, but mid-export registrations will only affect prefix maps constructed after the call returns.

func RegisterPrefixes

func RegisterPrefixes(prefixes []vocabulary.PrefixSpec) error

RegisterPrefixes atomically validates and registers a batch of prefix → namespace bindings. Every entry is validated against vocabulary.PrefixSpec.Validate (Turtle PN_PREFIX grammar and non-empty namespace IRI), intra-batch consistency, and existing bindings before any binding is committed. If any entry is invalid or conflicts with an existing binding, the prefix table is left unchanged.

func Serialize

func Serialize(w io.Writer, triples []message.Triple, format Format, opts ...Option) error

Serialize writes triples in the specified format to the writer. Invalid triples (empty subject or predicate) are silently skipped.

func SerializeToString

func SerializeToString(triples []message.Triple, format Format, opts ...Option) (string, error)

SerializeToString returns the serialized output as a string.

func SubjectIRI

func SubjectIRI(subject, base string) string

SubjectIRI converts a canonical 6-part entity ID or arbitrary subject string to a full IRI using base. Trailing '/' characters on base are trimmed, and an empty base defaults to vocabulary.SemEngineBase.

For valid 6-part entity IDs, it produces:

{base}/entities/{org}/{platform}/{system}/{domain}/{type}/{instance}

The path follows the canonical entity-ID order from the named fields (ADR-102, owner item O-10 on #1095): the exporter is not a second interpreter of position order.

For other non-empty subjects, it falls back to dot-to-slash conversion:

{base}/subjects/{dots→slashes}

SubjectIRI returns "" when subject is empty.

Types

type Format

type Format int

Format identifies an RDF serialization format.

const (
	// Turtle is the Terse RDF Triple Language format (.ttl).
	// Compact and human-readable with prefix declarations and subject grouping.
	Turtle Format = iota

	// NTriples is the N-Triples format (.nt).
	// Line-based, one triple per line, fully expanded IRIs.
	NTriples

	// JSONLD is the JSON-LD format (.jsonld).
	// JSON with @context and @graph for web API consumption.
	JSONLD
)

func (Format) String

func (f Format) String() string

String returns the format name.

type Option

type Option func(*options)

Option configures serialization behavior.

func WithBaseIRI

func WithBaseIRI(base string) Option

WithBaseIRI overrides the default SemEngineBase IRI used for generated URIs.

func WithSubjectIRIFunc

func WithSubjectIRIFunc(fn func(string) string) Option

WithSubjectIRIFunc provides a custom function to map entity ID strings to IRIs. When set, this replaces the default subject IRI generation logic entirely; WithBaseIRI has no effect on subjects when a custom function is provided.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL