rdf

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jun 25, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package rdf is a small, fast, dependency-free RDF toolkit. It provides the RDF triple model (Term, Triple, Graph), parsers and serializers for the four common serializations — RDF/XML, JSON-LD, Turtle and N-Triples — and a streaming decoder for the line-based formats.

Two reading modes:

  • Whole document: ParseRDFXML, ParseJSONLD, ParseTurtle and ParseNTriples take a []byte and return a *Graph. Fast and convenient for inputs that fit in memory.
  • Streaming: NewDecoder reads N-Triples, N-Quads, RDF/XML or Turtle from an io.Reader one triple at a time in constant memory, for inputs too large to materialize (e.g. the multi-gigabyte Library of Congress authority dumps). JSON-LD is whole-document only.

The parsers target the constructs real-world RDF uses rather than the whole of each specification; see each parser's documentation for what is and isn't handled (notably, relative-IRI resolution against a document base is not performed). There are no third-party dependencies.

Index

Constants

View Source
const (
	NS       = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
	TypeIRI  = NS + "type"
	FirstIRI = NS + "first"
	RestIRI  = NS + "rest"
	NilIRI   = NS + "nil"

	XSDString = "http://www.w3.org/2001/XMLSchema#string"
)

Well-known IRIs.

Variables

This section is empty.

Functions

func LocalName

func LocalName(iri string) string

LocalName returns the fragment or last path segment of an IRI (the part after the final '#' or '/').

func TurtleHeader

func TurtleHeader(prefixes map[string]string) []byte

TurtleHeader returns the @prefix declaration block for the given prefixes, terminated by a blank line. Collection writers emit it once.

Types

type Decoder

type Decoder struct {
	// contains filtered or unexported fields
}

Decoder streams RDF statements from an io.Reader one triple at a time, in constant memory — for inputs far too large to materialize into a Graph (multi-gigabyte dumps such as the LC authority files). Each returned triple owns its strings, so it is safe to retain after the next call.

JSON-LD is not streamable here (its document must be materialized); use ParseJSONLD for that.

func NewDecoder

func NewDecoder(r io.Reader, format Format) *Decoder

NewDecoder returns a streaming Decoder reading the given format from r.

func (*Decoder) All

func (d *Decoder) All() iter.Seq[Triple]

All returns an iterator over the remaining triples, ending at the first error (io.EOF, the normal end, is not surfaced). Breaking out of the loop stops the producer:

for tr := range dec.All() { ... }

Use Decode directly when a non-EOF read error must be observed.

func (*Decoder) Close

func (d *Decoder) Close() error

Close stops a streaming decoder early, releasing its producer goroutine. It is a no-op for the line-based formats and after the stream is exhausted.

func (*Decoder) Decode

func (d *Decoder) Decode() (Triple, error)

Decode returns the next triple, or io.EOF when the input is exhausted. Blank, comment and malformed lines/statements are skipped, so a stray line never aborts a large stream.

type Format

type Format int

Format identifies a serialization the streaming Decoder reads.

const (
	// NTriples is the line-based N-Triples format.
	NTriples Format = iota
	// NQuads is N-Quads; the optional graph label on each line is ignored, so each
	// statement still yields a triple.
	NQuads
	// RDFXML is RDF/XML; triples stream as each node element is parsed.
	RDFXML
	// Turtle streams '.'-terminated statements; @prefix/@base carry forward.
	// SPARQL-style PREFIX/BASE directives (no '.') are not supported when streaming.
	Turtle
)

type Graph

type Graph struct {
	Triples []Triple
	// contains filtered or unexported fields
}

Graph is a set of triples with simple lookup helpers built on first use. Term is comparable, so it indexes by subject term directly — no key strings.

func ParseJSONLD

func ParseJSONLD(data []byte) (*Graph, error)

ParseJSONLD parses a JSON-LD document into a Graph. It expands compact IRIs and terms against an inline @context (prefix maps and term definitions, including "@type":"@id" coercion), and handles @graph, @id, @type, @value/@language/@type literals, @list, nested node objects, and arrays of any of these. It does not fetch remote @context documents or run full JSON-LD 1.1 framing.

func ParseNTriples

func ParseNTriples(data []byte) (*Graph, error)

ParseNTriples parses an N-Triples document (one "subject predicate object ." statement per line) into a Graph. It also accepts N-Quads, ignoring any fourth (graph) term. Blank, comment and malformed lines are skipped, so it is robust to the trailing noise real-world dumps carry.

func ParseRDFXML

func ParseRDFXML(data []byte) (*Graph, error)

ParseRDFXML parses an RDF/XML document into a Graph. It supports the striped syntax real bibliographic RDF uses: typed node elements and rdf:Description, rdf:about / rdf:nodeID / rdf:ID subjects, rdf:resource and rdf:nodeID object references, nested node elements, literal property values with rdf:datatype and xml:lang, property attributes, and rdf:parseType="Resource". It does not handle RDF containers, reification, or rdf:parseType="Literal"/"Collection".

func ParseTurtle

func ParseTurtle(data []byte) (*Graph, error)

ParseTurtle parses a Turtle document into a Graph. It supports the constructs real RDF uses: @prefix/@base and SPARQL-style PREFIX/BASE, prefixed names and IRIs, the `a` keyword, predicate-object lists (`;`) and object lists (`,`), blank-node labels, `[ … ]` blank-node property lists, `( … )` collections, and string (including triple-quoted), language-tagged, datatyped, numeric and boolean literals. Local names are read as the common identifier subset.

func (*Graph) Add

func (g *Graph) Add(s, p, o Term)

Add appends a triple.

func (*Graph) HasType

func (g *Graph) HasType(subject Term, typeIRI string) bool

HasType reports whether the subject has rdf:type typeIRI. It scans the index without allocating.

func (*Graph) Literal

func (g *Graph) Literal(subject Term, predicate string) (string, bool)

Literal returns the value of the subject's first literal object for the predicate, or false. It scans the index without allocating an intermediate slice, serving the frequent single-value field reads.

func (*Graph) NTriples

func (g *Graph) NTriples() []byte

NTriples serializes the graph as N-Triples.

func (*Graph) Object

func (g *Graph) Object(subject Term, predicate string) (Term, bool)

Object returns the first object for (subject, predicate), or false. It scans the index without allocating an intermediate slice.

func (*Graph) Objects

func (g *Graph) Objects(subject Term, predicate string) []Term

Objects returns the objects of every triple with the given subject and predicate IRI, in document order.

func (*Graph) SubjectsOfType

func (g *Graph) SubjectsOfType(typeIRI string) []Term

SubjectsOfType returns every subject with rdf:type typeIRI, in document order (deduplicated).

func (*Graph) Turtle

func (g *Graph) Turtle(prefixes map[string]string) []byte

Turtle serializes the graph as Turtle, declaring the given namespace prefixes (prefix label -> namespace IRI) and compacting IRIs against them. Triples are grouped by subject in first-seen order, using `a` for rdf:type.

func (*Graph) TurtleBody

func (g *Graph) TurtleBody(prefixes map[string]string) []byte

TurtleBody serializes the triples grouped by subject, without a prefix header. It groups without a per-subject map: subjects are ranked by first appearance, then a stable sort of triple indices by that rank makes each subject's triples contiguous in document order — turning thousands of small allocations into a handful.

type Kind

type Kind uint8

Kind distinguishes the three RDF term types.

const (
	IRI Kind = iota
	Blank
	Literal
)

type Term

type Term struct {
	Kind     Kind
	Value    string // IRI, blank-node identifier, or a literal's lexical form
	Lang     string // literal language tag (Literal only)
	Datatype string // literal datatype IRI (Literal only)
}

Term is an RDF term: an IRI, a blank node, or a literal.

func NewBlank

func NewBlank(id string) Term

func NewIRI

func NewIRI(s string) Term

NewIRI, NewBlank and NewLiteral construct the three term kinds.

func NewLiteral

func NewLiteral(value, lang, datatype string) Term

NewLiteral makes a literal; an empty datatype defaults per RDF (xsd:string, or rdf:langString when a language tag is present).

func (Term) IsBlank

func (t Term) IsBlank() bool

func (Term) IsIRI

func (t Term) IsIRI() bool

IsIRI, IsBlank and IsLiteral report the term kind.

func (Term) IsLiteral

func (t Term) IsLiteral() bool

type Triple

type Triple struct {
	S, P, O Term
}

Triple is an RDF statement.

Jump to

Keyboard shortcuts

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