rdf2go

package module
v0.1.5 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2021 License: MIT Imports: 17 Imported by: 4

README

rdf2go

Build Status Coverage Status

Native golang parser/serializer from/to Turtle and JSON-LD.

Installation

Just go get it!

go get -u github.com/deiu/rdf2go

Example usage

Working with graphs

// Set a base URI
baseUri := "https://example.org/foo"

// Create a new graph
g, err := NewGraph(baseUri)
if err != nil {
	// deal with err
}

// Add a few triples to the graph
triple1 := NewTriple(NewResource("a"), NewResource("b"), NewResource("c"))
g.Add(triple1)
triple2 := NewTriple(NewResource("a"), NewResource("d"), NewResource("e"))
g.Add(triple2)

// Get length of Graph (nr of triples)
g.Len() // -> 2

// Dump graph contents to NTriples
out := g.String()
// <a> <b> <c> .
// <a> <d> <e> .

// Delete a triple
g.Remove(triple2)

Looking up triples from the graph

Returning a single match

The g.One() method returns the first triple that matches against any (or all) of Subject, Predicate, Object patterns.

// Create a new graph
g, _ := NewGraph("https://example.org")

// Add a few triples
g.Add(NewTriple(NewResource("a"), NewResource("b"), NewResource("c")))

// Look up one triple matching the given subject
triple := g.One(NewResource("a"), nil, nil) // -> <a> <b> <c> .

// Look up one triple matching the given predicate
triple = g.One(nil, NewResource("b"), nil) // -> <a> <b> <c> .

// Look up one triple matching the given object
triple = g.One(nil, nil, NewResource("c")) // -> <a> <b> <c> .

// Look up one triple matching the given subject and predicate
triple = g.One(NewResource("a"), NewResource("b"), nil) // -> <a> <b> <c> .

// Look up one triple matching the a bad predicate
triple = g.One(nil, NewResource("z"), nil) // -> nil
Returning a list of matches

Similar to g.One(), g.All() returns all triples that match the given pattern.

// Create a new graph
g, _ := NewGraph("https://example.org")

// Add a few triples
g.Add(NewTriple(NewResource("a"), NewResource("b"), NewResource("c")))
g.Add(NewTriple(NewResource("a"), NewResource("b"), NewResource("d")))

// Look up one triple matching the given subject
triples := g.All(nil, nil, NewResource("c")) //
for triple := range triples {
	triple.String()
}
// Returns a single triple that matches object <c>:
// <a> <b> <c> .

triples = g.All(nil, NewResource("b"), nil)
for triple := range triples {
	triple.String()
}
// Returns all triples that match subject <b>: 
// <a> <b> <c> .
// <a> <b> <d> .

Different types of terms (resources)

IRIs
// Create a new IRI
iri := NewResource("https://example.org")
iri.String() // -> <https://example.org>
Literals
// Create a new simple Literal
lit := NewLiteral("hello world")
lit.String() // -> "hello word"

// Create a new Literal with language tag
lit := NewLiteralWithLanguage("hello world", "en")
lit.String() // -> "hello word"@en

// Create a new Literal with a data type
lit := NewLiteralWithDatatype("newTypeVal", NewResource("https://datatype.com"))
lit.String() // -> "newTypeVal"^^<https://datatype.com>
Blank Nodes
// Create a new Blank Node with a given ID
bn := NewBlankNode(9)
bn.String() // -> "_:n9"

// Create an anonymous Blank Node with a random ID
abn := NewAnonNode()
abn.String() // -> "_:n192853"

Parsing data

The parser takes an io.Reader as first parameter, and the string containing the mime type as the second parameter.

Currently, the supported parsing formats are Turtle (with mime type text/turtle) and JSON-LD (with mime type application/ld+json).

Parsing Turtle from an io.Reader
// Set a base URI
baseUri := "https://example.org/foo"

// Create a new graph
g, _ := NewGraph(baseUri)

// r is of type io.Reader
g.Parse(r, "text/turtle")
Parsing JSON-LD from an io.Reader
// Set a base URI
baseUri := "https://example.org/foo"

// Create a new graph
g, _ := NewGraph(baseUri)

// r is an io.Reader
g.Parse(r, "application/ld+json")
Parsing either Turtle or JSON-LD from a URI on the Web

In this case you don't have to specify the mime type, as the internal http client will try to content negotiate to either Turtle or JSON-LD. An error will be returned if it fails.

Note: The NewGraph() function accepts an optional parameter called skipVerify that is used to tell the internal http client whether or not to ignore bad/self-signed server side certificates. By default, it will not check if you omit this parameter, or if you set it to true.

// Set a base URI
uri := "https://example.org/foo"

// Check remote server certificate to see if it's valid 
// (don't skip verification)
skipVerify := false

// Create a new graph. You can also omit the skipVerify parameter
// and accept invalid certificates (e.g. self-signed)
g, _ := NewGraph(uri, skipVerify)

err := g.LoadURI(uri)
if err != nil {
	// deal with the error
}

Serializing data

The serializer takes an io.Writer as first parameter, and the string containing the mime type as the second parameter.

Currently, the supported serialization formats are Turtle (with mime type text/turtle) and JSON-LD (with mime type application/ld+json).

Serializing to Turtle
// Set a base URI
baseUri := "https://example.org/foo"

// Create a new graph
g, _ := NewGraph(baseUri)

triple := NewTriple(NewResource("a"), NewResource("b"), NewResource("c"))
g.Add(triple)

// w is of type io.Writer
g.Serialize(w, "text/turtle")
Serializing to JSON-LD
// Set a base URI
baseUri := "https://example.org/foo"

// Create a new graph
g, _ := NewGraph(baseUri)

triple := NewTriple(NewResource("a"), NewResource("b"), NewResource("c"))
g.Add(triple)

// w is of type io.Writer
g.Serialize(w, "application/ld+json")

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AppendTriple

func AppendTriple(subjects map[string]*LdEntry, t *Triple) error

AppendTriple appends a triple to a subject map

func GetResourceID

func GetResourceID(t Term) string

func NewHttpClient

func NewHttpClient(skip bool) *http.Client

NewHttpClient creates an http.Client to be used for parsing resources directly from the Web

func RandStringBytesMask added in v0.1.1

func RandStringBytesMask(n int) string

Types

type BlankNode

type BlankNode struct {
	ID string
}

BlankNode is an RDF blank node i.e. an unqualified URI/IRI.

func (BlankNode) Equal

func (term BlankNode) Equal(other Term) bool

Equal returns whether this blank node is equivalent to another.

func (BlankNode) RawValue

func (term BlankNode) RawValue() string

func (BlankNode) String

func (term BlankNode) String() string

String returns the NTriples representation of the blank node.

type Graph

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

Graph structure

func NewGraph

func NewGraph(uri string, skipVerify ...bool) *Graph

NewGraph creates a Graph object

func (*Graph) Add

func (g *Graph) Add(t *Triple)

Add is used to add a Triple object to the graph

func (*Graph) AddTriple

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

AddTriple is used to add a triple made of individual S, P, O objects

func (*Graph) All

func (g *Graph) All(s Term, p Term, o Term) []*Triple

All is used to return all triples that match a given pattern of S, P, O objects

func (*Graph) GenerateJSONLD

func (g *Graph) GenerateJSONLD() ([]map[string]interface{}, error)

GenerateJSONLD creates a interface based model of the RDF Graph. This can be used to create various JSON-LD output formats, e.g. expand, flatten, compacted, etc.

func (*Graph) IterTriples

func (g *Graph) IterTriples() (ch chan *Triple)

IterTriples iterates through all the triples in a graph

func (*Graph) IterTriplesOrdered added in v0.1.4

func (g *Graph) IterTriplesOrdered() (ch chan *Triple)

IterTriples iterates through all the triples in a graph by insertion order

func (*Graph) Len

func (g *Graph) Len() int

Len returns the length of the graph as number of triples in the graph

func (*Graph) LoadURI

func (g *Graph) LoadURI(uri string) error

LoadURI is used to load RDF data from a specific URI

func (*Graph) Merge

func (g *Graph) Merge(toMerge *Graph)

Merge is used to add all the triples form another graph to this one

func (*Graph) One

func (g *Graph) One(s Term, p Term, o Term) *Triple

One returns one triple based on a triple pattern of S, P, O objects

func (*Graph) Parse

func (g *Graph) Parse(reader io.Reader, mime string) error

Parse is used to parse RDF data from a reader, using the provided mime type

func (*Graph) Remove

func (g *Graph) Remove(t *Triple)

Remove is used to remove a Triple object

func (*Graph) Serialize

func (g *Graph) Serialize(w io.Writer, mime string) error

Serialize is used to serialize a graph based on a given mime type

func (*Graph) SerializeFlatJSONLD

func (g *Graph) SerializeFlatJSONLD(w io.Writer) error

func (*Graph) String

func (g *Graph) String() string

String is used to serialize the graph object using NTriples

func (*Graph) Term

func (g *Graph) Term() Term

Term returns a Graph Term object

func (*Graph) URI

func (g *Graph) URI() string

URI returns a Graph URI object

type LdEntry

type LdEntry struct {
	ID         string                 `json:"@id"`
	Types      []string               `json:"@type,omitempty"`
	Predicates map[string][]*LdObject `json:""`
}

func (*LdEntry) AsEntry

func (lde *LdEntry) AsEntry() map[string]interface{}

type LdObject

type LdObject struct {
	ID       string `json:"@id,omitempty"`
	Value    string `json:"@value,omitempty"`
	Language string `json:"@language,omitempty"`
	Datatype string `json:"@type,omitempty"`
}

type Literal

type Literal struct {
	Value    string
	Language string
	Datatype Term
}

Literal is a textual value, with an associated language or datatype.

func (Literal) Equal

func (term Literal) Equal(other Term) bool

Equal returns whether this literal is equivalent to another.

func (Literal) RawValue

func (term Literal) RawValue() string

func (Literal) String

func (term Literal) String() string

String returns the NTriples representation of this literal.

type Resource

type Resource struct {
	URI string
}

Resource is an URI / IRI reference.

func (Resource) Equal

func (term Resource) Equal(other Term) bool

Equal returns whether this resource is equal to another.

func (Resource) RawValue

func (term Resource) RawValue() (str string)

RawValue returns the string value of the a resource without brackets.

func (Resource) String

func (term Resource) String() (str string)

String returns the NTriples representation of this resource.

type Term

type Term interface {
	// Method String should return the NTriples representation of this term.
	String() string

	// Method RawValue should return the raw value of this term.
	RawValue() string

	// Method Equal should return whether this term is equal to another.
	Equal(Term) bool
}

A Term is the value of a subject, predicate or object i.e. a IRI reference, blank node or literal.

func NewAnonNode

func NewAnonNode() (term Term)

NewAnonNode returns a new blank node with a pseudo-randomly generated ID.

func NewBlankNode

func NewBlankNode(id string) (term Term)

NewBlankNode returns a new blank node with the given ID.

func NewLiteral

func NewLiteral(value string) (term Term)

NewLiteral returns a new literal with the given value.

func NewLiteralWithDatatype

func NewLiteralWithDatatype(value string, datatype Term) (term Term)

NewLiteralWithDatatype returns a new literal with the given value and datatype.

func NewLiteralWithLanguage

func NewLiteralWithLanguage(value string, language string) (term Term)

NewLiteralWithLanguage returns a new literal with the given value and language.

func NewResource

func NewResource(uri string) (term Term)

NewResource returns a new resource object.

type Triple

type Triple struct {
	Subject   Term
	Predicate Term
	Object    Term
	// contains filtered or unexported fields
}

Triple contains a subject, a predicate and an object term.

func NewTriple

func NewTriple(subject Term, predicate Term, object Term) (triple *Triple)

NewTriple returns a new triple with the given subject, predicate and object.

func (Triple) Equal

func (triple Triple) Equal(other *Triple) bool

Equal returns this triple is equivalent to the argument.

func (*Triple) GetRDFType

func (t *Triple) GetRDFType() (string, bool)

func (*Triple) GetSubjectID

func (t *Triple) GetSubjectID() string

func (Triple) Hash added in v0.1.5

func (triple Triple) Hash() string

func (Triple) Order added in v0.1.4

func (triple Triple) Order() int

Order returns the order in which the triple was inserted in the Graph

func (Triple) String

func (triple Triple) String() (str string)

String returns the NTriples representation of this triple.

Jump to

Keyboard shortcuts

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