node-rdf

ECMAScript libraries for handling RDF data (based off of the current RDF APIs and webr3's js3)

UNLICENSE License

Downloads
973
Stars
93
Committers
1

{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# RDF for ECMAScript\n", "\n", "This package is a set of utilities aimed at making it simple to represent RDF data. It is targeted at Node.js, but should work cross-environment.\n", "\n", "RDF can be considered a superset of typical links found on the Web: It allows a collection of directional relationships from some subject, with a relationship predicate, to some object.\n", "\n", "On the Web, normally all three are documents. In RDF, the object may also be a literal string containing data; and the subject or object may be an existential quantifier called a blank node.\n", "\n", "The NamedNode, BlankNode, and Literal objects represent the fundamental types of data that can be found in an RDF Statement. Statements are represented as Triple.\n", "\n", "RDF doesn't define any representation of a blank nodes, except for the fact it is possible to compare two blank nodes to see if they are the same. In RDF Interfaces, a bnode is uniquely represented as an instance of BlankNode. This interface optionally allows a label, this is primarily for debugging, and two instances of BlankNodes with the same label may still represent different blank nodes.\n", "\n", "The library also exposes a function to decorate the builtin ECMAScript protoypes with methods.\n", "\n", "## Features\n", "\n", "### Represent RDF nodes\n", "\n", "NamedNode, BlankNode, and Literal instances represent nodes in an RDF graph." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'http://example.com/'" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "var rdf = require('rdf');\n", "var { NamedNode, BlankNode, Literal } = rdf;\n", "\n", "var namednode = new NamedNode('http://example.com/');\n", "namednode.toNT()" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "':b1'" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "var blanknode = new BlankNode();\n", "blanknode.toNT()" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'"plain string"'" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "var literal = new Literal('plain string');\n", "literal.toNT()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A factory-style interface is also available:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "BlankNode { nominalValue: 'b2' }" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "var rdfjs = rdf.factory;\n", "rdfjs.blankNode()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As well as the RDF Interfaces environment:" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'true'" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "var rdfenv = rdf.environment;\n", "rdfenv.createLiteral("true", null, rdf.xsdns("boolean")).toTurtle()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Represent RDF statements\n", "\n", "A Triple instance represents an edge in an RDF graph (also known as a Statement)." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "':b1 http://example.com/ "plain string" .'" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "var statement1 = rdfjs.triple(blanknode, namednode, literal);\n", "statement1.toString()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Represent RDF graphs\n", "\n", "A Graph instance stores and queries for Triples:" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "var graph = new rdf.Graph();\n", "graph.add(new rdf.Triple(\n", "\tnew BlankNode(),\n", "\trdf.rdfsns('label'),\n", "\tnew Literal('Book', '@en'))\n", "\t);\n", "graph.add(new rdf.Triple(\n", "\tnew BlankNode(),\n", "\trdf.rdfns('value'),\n", "\tnew Literal('10.0', rdf.xsdns('decimal')))\n", "\t);\n", "graph.add(new rdf.Triple(\n", "\tnew BlankNode(),\n", "\trdf.rdfns('value'),\n", "\tnew Literal('10.1', rdf.xsdns('decimal')))\n", "\t);\n", "graph.length" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ ":b4 http://www.w3.org/1999/02/22-rdf-syntax-ns#value "10.0"^^http://www.w3.org/2001/XMLSchema#decimal .\n", ":b5 http://www.w3.org/1999/02/22-rdf-syntax-ns#value "10.1"^^http://www.w3.org/2001/XMLSchema#decimal .\n" ] } ], "source": [ "graph\n", "\t.match(null, rdf.rdfns('value'), null)\n", "\t.forEach(function(triple){ console.log(triple.toString()); });" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Simplify RDF namespaces\n", "\n", "Use the ns function to create a URI factory." ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "'http://xmlns.com/foaf/0.1/knows'" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "var foaf = rdf.ns('http://xmlns.com/foaf/0.1/');\n", "foaf('knows')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Use the builtin rdfns, rdfsns, and xsdns functions too:" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "'http://www.w3.org/2000/01/rdf-schema#label'" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "rdf.rdfsns('label')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Compare nodes, triples, and graphs for equality\n", "\n", "Use the NamedNode#equals, BlankNode#equals, Literal#equals, Triple#equals, and Graph#isomorphic methods to compare equality.\n", "\n", "Literals verify codepoint, datatype, and language tag equality. Triples verify equality of each three nodes.\n", "\n", "Graphs test for isomorphism, that there's a mapping that can map the blank nodes in one graph to the blank nodes in the other one-to-one. If so isomorphic, it returns the mapping." ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [], "source": [ "var graph2 = new rdf.Graph();\n", "var bn2 = rdf.factory.blankNode();\n", "\n", "graph2.add(rdf.factory.triple(\n", "\tbn2,\n", "\tnamednode,\n", "\tliteral\n", "\t));\n", "graph2.add(rdf.factory.triple(\n", "\tbn2,\n", "\trdf.rdfsns('label'),\n", "\trdfjs.literal('Price')\n", "\t));\n", "graph2.add(rdf.factory.triple(\n", "\tbn2,\n", "\trdf.rdfns('value'),\n", "\trdfjs.literal('10.0', rdf.xsdns('decimal'))\n", "\t));\n", "\n", "graph.isomorphic(graph2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Compose RDF graphs as native Objects\n", "\n", "Use the rdf.parse function to cast a native object into a graph:" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[\n", "\tfoaf:givenname "Alice";\n", "\tfoaf:age 26;\n", "\tfoaf:knows [\n", "\t\tfoaf:givenname "Bob";\n", "\t\tfoaf:age 36;\n", "\t\tfoaf:knows person:a\n", "\t\t], [\n", "\t\tfoaf:givenname "Carol";\n", "\t\tfoaf:age 46;\n", "\t\tfoaf:knows person:a\n", "\t\t], [\n", "\t\tfoaf:givenname "Dan";\n", "\t\tfoaf:age 56;\n", "\t\tfoaf:knows person:a, person:b\n", "\t\t]\n", "\t]\n" ] } ], "source": [ "var person = rdf.ns('http://example.com/');\n", "var partyDocument = rdf.parse({\n", "\t"@context": {\n", "\t\t"@vocab": "http://xmlns.com/foaf/0.1/",\n", "\t\t"foaf": "http://xmlns.com/foaf/0.1/",\n", "\t\t"person": "http://example.com/",\n", "\t},\n", "\t"@id": person('a'),\n", "\tgivenname: rdfjs.literal("Alice"),\n", "\tage: 26,\n", "\tknows: [\n", "\t\t{\n", "\t\t\t"@id": person('b'),\n", "\t\t\tgivenname: rdfjs.literal("Bob"),\n", "\t\t\tage: 36,\n", "\t\t\tknows: person('a'),\n", "\t\t},\n", "\t\t{\n", "\t\t\t"@id": person('c'),\n", "\t\t\tgivenname: rdfjs.literal("Carol"),\n", "\t\t\tage: 46,\n", "\t\t\tknows: person('a'),\n", "\t\t},\n", "\t\t{\n", "\t\t\t"@id": person('d'),\n", "\t\t\tgivenname: rdfjs.literal("Dan"),\n", "\t\t\tage: 56,\n", "\t\t\tknows: [person('a'), person('b')],\n", "\t\t}\n", "\t]\n", "})\n", "console.log(partyDocument.n3());" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Use the graphify method to produce an rdf.Graph from the data:" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "http://example.com/a http://xmlns.com/foaf/0.1/age "26"^^http://www.w3.org/2001/XMLSchema#integer .\n", "http://example.com/a http://xmlns.com/foaf/0.1/givenname "Alice" .\n", "http://example.com/a http://xmlns.com/foaf/0.1/knows http://example.com/b .\n", "http://example.com/a http://xmlns.com/foaf/0.1/knows http://example.com/c .\n", "http://example.com/a http://xmlns.com/foaf/0.1/knows http://example.com/d .\n", "http://example.com/b http://xmlns.com/foaf/0.1/age "36"^^http://www.w3.org/2001/XMLSchema#integer .\n", "http://example.com/b http://xmlns.com/foaf/0.1/givenname "Bob" .\n", "http://example.com/b http://xmlns.com/foaf/0.1/knows http://example.com/a .\n", "http://example.com/c http://xmlns.com/foaf/0.1/age "46"^^http://www.w3.org/2001/XMLSchema#integer .\n", "http://example.com/c http://xmlns.com/foaf/0.1/givenname "Carol" .\n", "http://example.com/c http://xmlns.com/foaf/0.1/knows http://example.com/a .\n", "http://example.com/d http://xmlns.com/foaf/0.1/age "56"^^http://www.w3.org/2001/XMLSchema#integer .\n", "http://example.com/d http://xmlns.com/foaf/0.1/givenname "Dan" .\n", "http://example.com/d http://xmlns.com/foaf/0.1/knows http://example.com/a .\n", "http://example.com/d http://xmlns.com/foaf/0.1/knows http://example.com/b .\n" ] } ], "source": [ "var partyGraph = partyDocument.graphify();\n", "\n", "partyGraph\n", "\t.toArray()\n", "\t.sort(function(a,b){ return a.compare(b); })\n", "\t.forEach(function(triple){ console.log(triple.toString()); });" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Query information from RDF sources\n", "\n", "Use the ResultSet interface to quickly drill into the specific data you want:" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Alice'" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "// Get the name of Alice\n", "partyGraph.reference(person('a'))\n", "\t.rel(foaf('givenname'))\n", "\t.one()\n", "\t.toString()" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Bob, Carol, Dan'" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "// Get all the names of everyone who Alice knows\n", "partyGraph.reference(person('a'))\n", "\t.rel(foaf('knows'))\n", "\t.rel(foaf('givenname'))\n", "\t.toArray()\n", "\t.sort()\n", "\t.join(', ')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Read RDF data sources as native data types\n", "\n", "Use Literal#valueOf to convert from lexical data space to native value space:" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2018-06-04T23:11:25.000Z" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "rdfjs.literal('2018-06-04T23:11:25Z', rdf.xsdns('date')).valueOf()" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "24.44" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "rdfjs.literal('24.4400', rdf.xsdns('decimal')).valueOf()" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "false" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "rdfjs.literal('0', rdf.xsdns('boolean')).valueOf()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Read the ages of everyone that Alice knows as a native number, and sum them:" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "138" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "// sum the ages of everyone that Alice knows\n", "partyGraph.reference(person('a'))\n", "\t.rel(foaf('knows'))\n", "\t.rel(foaf('age'))\n", "\t.reduce(function(a, b){ return a.valueOf() + b; }, 0);" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Manage documents with RDF data\n", "\n", "Use the RDFEnvironment, Profile, TermMap, and ProfileMap interfaces to work with RDF documents that think in terms of CURIEs and Terms.\n", "\n", "Here's an example to take an RDF graph, and output a Turtle document with the prefixes applied:" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ ":a ff:age 26 .\n", ":a ff:givenname "Alice" .\n", ":a ff:knows :b .\n", ":a ff:knows :c .\n", ":a ff:knows :d .\n", ":b ff:age 36 .\n", ":b ff:givenname "Bob" .\n", ":b ff:knows :a .\n", ":c ff:age 46 .\n", ":c ff:givenname "Carol" .\n", ":c ff:knows :a .\n", ":d ff:age 56 .\n", ":d ff:givenname "Dan" .\n", ":d ff:knows :a .\n", ":d ff:knows :b .\n" ] } ], "source": [ "var profile = rdf.environment.createProfile();\n", "profile.setDefaultPrefix('http://example.com/');\n", "profile.setPrefix('ff', 'http://xmlns.com/foaf/0.1/');\n", "var turtle = partyGraph\n", "\t.toArray()\n", "\t.sort(function(a,b){ return a.compare(b); })\n", "\t.map(function(stmt){\n", "\t\treturn stmt.toTurtle(profile);\n", "\t});\n", "//console.log(profile.n3());\n", "console.log(turtle.join('\n'));" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Treat native data types as RDF data\n", "\n", "If you think creating RDF Term is too verbose, enable builtins mode with setBuiltins(). This amends the prototype of primitives:\n", "* Strings are treated as a NamedNode\n", "* String#l(langtag) produces a language Literal\n", "* String#tl(datatype) produces a typed Literal\n", "* Date, Boolean, Number are treated as a Literal" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[ 'http://example.com/',\n", " '"12"^^http://www.w3.org/2001/XMLSchema#integer',\n", " '"true"^^http://www.w3.org/2001/XMLSchema#boolean',\n", " '"2112-06-06T00:00:00Z"^^http://www.w3.org/2001/XMLSchema#dateTime',\n", " '"The Hobbit"@en-GB',\n", " '"4.0"^^http://www.w3.org/2001/XMLSchema#decimal' ]" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "rdf.setBuiltins();\n", "\n", "[\n", " "http://example.com/".toNT(),\n", " (3 * 4).toNT(),\n", " true.toNT(),\n", " new Date('2112-06-06').toNT(),\n", " "The Hobbit".l('en-GB').toNT(),\n", " "4.0".tl(rdf.xsdns('decimal')).toNT(),\n", "]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Change your mind? Use unsetBuiltins to remove them:" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [], "source": [ "rdf.unsetBuiltins();" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Native support for RDF 1.1 semantics\n", "\n", "The domains of the functions ensure consistency with all the other applications found in the RDF universe.\n", "\n", "Literal treats xsd:string as no datatype, and treats any language literal as rdf:langString. The RDF1.1 datatype is available through the Literal#datatype property. The RDF1.0 datatype, which null for plain literals and language strings, is available through Literal#type." ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "'http://www.w3.org/2001/XMLSchema#string'\n", "null\n", "null\n" ] } ], "source": [ "var literal = new Literal('Foo');\n", "console.dir(literal.datatype.toNT());\n", "console.dir(literal.type);\n", "console.dir(literal.language);" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "'http://www.w3.org/1999/02/22-rdf-syntax-ns#langString'\n", "null\n", "'en'\n" ] } ], "source": [ "var langLiteral = new Literal('Foo', '@en');\n", "console.dir(langLiteral.datatype.toNT());\n", "console.dir(langLiteral.type);\n", "console.dir(langLiteral.language);" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "'http://www.w3.org/2001/XMLSchema#string'\n", "null\n", "null\n" ] } ], "source": [ "var typedLiteral = new Literal('Foo', rdf.xsdns('string'));\n", "console.dir(typedLiteral.datatype.toNT());\n", "console.dir(typedLiteral.type);\n", "console.dir(typedLiteral.language);" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The data model is enforced in the domain of each of the functions; Triple doesn't allow bnodes as predicates, for example:" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Error: predicate must be a NamedNode\n" ] } ], "source": [ "try {\n", " rdfjs.triple(rdfjs.blankNode(), rdfjs.blankNode(), rdfjs.blankNode());\n", "}catch(e){\n", " console.log(e.toString());\n", "}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Parse Turtle data\n", "\n", "Use the TurtleParser.parse(document, base) function to parse Turtle data into a Graph object:" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'http://example.com/ http://www.w3.org/1999/02/22-rdf-syntax-ns#type http://example.com/Page .'" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "var parse = rdf.TurtleParser.parse('<> a .', 'http://example.com/');\n", "parse.graph.toArray().join("\n")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Public Domain unlicensed\n", "\n", "Use this library in whatever application you want! Give credit when you do so, or don't (but preferably the former). Use it to take over the world, or don't (but preferably the latter)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## About\n", "\n", "This implements:\n", "\n", "* http://www.w3.org/TR/2012/NOTE-rdf-interfaces-20120705/ (Working Group Note)\n", "* http://www.w3.org/TR/2014/REC-turtle-20140225/ (Recommendation)\n", "* http://www.w3.org/TR/2014/REC-n-triples-20140225/ (Recommendation)\n", "\n", "See also:\n", "\n", "* http://www.w3.org/TR/2012/NOTE-rdfa-api-20120705/ (Working Group Note)\n", "* http://www.w3.org/TR/2012/NOTE-rdf-api-20120705/ (Working Group Note)\n", "* http://www.w3.org/TR/2014/NOTE-rdf11-primer-20140225/ (Working Group Note)\n", "\n", "Implementation largely adapted from webr3's js3, rdfa-api, and rdf-api implementations:\n", "\n", "* https://github.com/webr3/rdfa-api\n", "* https://github.com/webr3/js3\n", "\n", "This is free and unencumbered software released into the public domain. For information, see http://unlicense.org/.\n", "\n", "\n", "## Usage\n", "\n", "\n", "### RDFNode\n", "\n", "rdf.Triple, rdf.RDFNode, rdf.NamedNode, rdf.BlankNode, rdf.Literal are implemented as defined under RDF Interfaces: Basic Node Types.\n", "\n", "For parsing the IRI and converting to a URI that can be used in an HTTP request, see the IRI package.\n", "\n", "\n", "### Triple\n", "\n", "Represents an edge in an RDF Graph, also known as a Statement or a Triple.\n", "\n", "Create an instance of a triple with rdf.environment.createTriple(subject, predicate, object).\n", "\n", "Use the Triple#subject, Triple#predicate, and Triple#object properties to access the respective RDF nodes in the Triple.\n", "\n", "#### Triple#toString()\n", "\n", "Returns the triple encoded as N-Triples. Same as Triple#toNT().\n", "\n", "#### Triple#toNT()\n", "\n", "Returns the triple encoded as N-Triples.\n", "\n", "#### Triple#toTurtle(profile)\n", "\n", "Returns the triple encoded as a statement in Turtle, optionally with the given prefix map applied.\n", "\n", "\n", "### RDFNode\n", "\n", "Also exposed as Term, this is the abstract superclass of things that can be found in an RDF Triple.\n", "\n", "#### RDFNode#equals(other)\n", "\n", "Returns true if the given node other would be considered the same node as itself in an RDF graph.\n", "\n", "Literals and NamedNodes always compare by their contents. BlankNodes sometimes compare by their label, but sometimes may only be equal if they're the same instance.\n", "\n", "If you're managing a single RDF graph, you should keep a mapping of labels to BlankNode instances, and use the instances from this mapping, instead of creating a new BlankNode and setting the label.\n", "\n", "\n", "### NamedNode\n", "\n", "Represents an IRI node in an RDF graph. Instances are uniquely identified by their contents, so two different contents will still be considered equal if the inner IRIs are the same.\n", "\n", "Create an instance of a triple with rdf.environment.createTriple(subject, predicate, object).\n", "\n", "#### NamedNode#equals(other)\n", "\n", "Returns true if the given NamedNode other is the same IRI, otherwise false. See RDFNode#equals for details\n", "\n", "#### NamedNode#toString()\n", "\n", "Returns the inner IRI as a string.\n", "\n", "#### NamedNode#toNT()\n", "\n", "Serializes the node as an IRI for N-Triples, inside angle brackets.\n", "\n", "#### NamedNode#toTurtle(profile)\n", "\n", "Serializes the node as an IRI for N-Triples inside angle brackets, or the shrunken CURIE form if provided in the optional profile.\n", "\n", "\n", "### BlankNode\n", "\n", "Represents a blank node in an RDF graph. BlankNode instances are typically identified by their instance, so two instances may be considered different even if they have the same label.\n", "\n", "Create an instance of a triple with rdf.environment.createBlankNode().\n", "\n", "#### BlankNode#equals(other)\n", "\n", "Returns true if the given NamedNode other is the same IRI, otherwise false. See RDFNode#equals for details\n", "\n", "#### BlankNode#toString()\n", "\n", "Serializes the node as a Turtle-style BlankNode. See toTurtle for information.\n", "\n", "#### BlankNode#toNT()\n", "\n", "Serializes the node as a Turtle-style BlankNode. See toTurtle for information.\n", "\n", "#### BlankNode#toTurtle()\n", "\n", "Serializes the BlankNode as a Turtle-style blank node, e.g.:\n", "\n", "* _:bn0\n", "* _:label\n", "\n", "\n", "### Literal\n", "\n", "Represents a content literal in an RDF graph. Literals may have edges pointing only towards them (i.e. they're only found in the object position of a triple). Literals are Unicode strings with a datatype IRI, and optional associated language tag.\n", "\n", "* Literal#value - the string contents of the literal (note that ECMAScript/JavaScript uses UTF-16 to encode Unicode strings)\n", "* Literal#datatype - NamedNode that identifies the datatype of the literal.\n", "* Literal#type - getter that returns null if the datatype is an xsd:string, or a language literal, as seen in RDF1.0 semantics.\n", "* Literal#language - stores the language tag, if any, or null otherwise.\n", "\n", "#### Literal#valueOf()\n", "\n", "Returns a native representation of the literal, based on its datatype.\n", "\n", "* The numeric datatypes will produce a number: xsd:float, xsd:integer, xsd:long, xsd:double, xsd:decimal, xsd:nonPositiveInteger, xsd:nonNegativeInteger, xsd:negativeInteger, xsd:int, xsd:unsignedLong, xsd:positiveInteger, xsd:short, xsd:unsignedInt, xsd:byte, xsd:unsignedShort, xsd:unsignedByte\n", "* The datetime datatypes will produce a Date object: xsd:date, xsd:time, xsd:dateTime\n", "* The boolean datatype will produce a boolean: xsd:boolean\n", "* The string datatypes will produce a string: xsd:string rdf:langString\n", "\n", "#### Literal#equals(other)\n", "\n", "Returns true if the given Literal other has the same contents, datatype, and language tag. See RDFNode#equals for details.\n", "\n", "#### Literal#toString()\n", "\n", "Returns the literal contents as a string, discarding the other type/tags.\n", "\n", "#### Literal#toNT()\n", "\n", "Serializes the node as a string with datatype for N-Triples, inside double-quotes followed by language tag or datatype IRI (if not xsd:string).\n", "\n", "#### Literal#toTurtle(profile)\n", "\n", "Serializes the node as a string. For datatypes of xsd:integer, xsd:decimal, xsd:double, xsd:boolean, and xsd:string, the literal is printed without the datatype IRI.\n", "\n", "If the datatype IRI can be shrunk with the given profile, it is printed as a CURIE, otherwise it prints the full brackted IRI.\n", "\n", "\n", "### Graph\n", "\n", "Represents a set of RDF Triple instances. Since a graph in RDF is a set of edges, nodes are only known to exist in the graph if there is an edge (a Triple) containing them.\n", "\n", "This implements RDF Interfaces: Graph with three indexes for fast querying.\n", "\n", "Instances of Graph are uniquely identified by their instance (however, Graph#equals tests isomorphism). Graphs are mutable. Methods with a return value are pure, non-pure (mutating) methods always return undefined.\n", "\n", "#### new Graph\n", "\n", "Creates an empty in-memory RDF graph.\n", "\n", "#### Graph#add(Triple triple)\n", "\n", "Adds a triple to the Graph, if it doesn't already exist.\n", "\n", "#### Graph#addAll(graph)\n", "\n", "Adds the given graph or array of Triple instances to the Graph.\n", "\n", "#### Graph#remove(Triple triple)\n", "\n", "Removes the given triple from the Graph, if it exists.\n", "\n", "#### Graph#removeMatches(subject, predicate, object)\n", "\n", "Removes the given triple from the Graph, if it exists.\n", "\n", "#### Graph#toArray()\n", "\n", "Returns an array of Triples currently in the Graph.\n", "\n", "#### Graph#some(function callback)\n", "\n", "Same behavior as Array#some: Evaluates callback over each Triple in the Graph, and returns true if the callback returns truthy for any of them.\n", "\n", "#### Graph#every(function callback)\n", "\n", "Same behavior as Array#every: Evaluates callback over each Triple in the Graph, and returns true if the callback returns truthy for all of them.\n", "\n", "#### Graph#filter(function callback)\n", "\n", "Same behavior as Array#filter: Evaluates callback over each Triple in the Graph, and returns a Graph with the triples that evaluated truthy.\n", "\n", "#### Graph#forEach(function callback)\n", "\n", "Same behavior as Array#forEach: Evaluates callback over each Triple in the Graph.\n", "\n", "#### Graph#isomorphic(graph)\n", "\n", "Determines if the provided graph is isomorphic with the current one: Determines if all the Literal and NamedNode instances equal, and is there a one-to-one mapping of bnodes between the two graphs. If so, it returns the mapping, the toString blanknode as the key, the graph argument's BlankNode instance as value. If there's no match, it returns null.\n", "\n", "#### Graph#union(graph)\n", "\n", "Returns a new Graph that's the concatenation of this graph with the argument.\n", "\n", "#### Graph#reference(resource)\n", "\n", "Returns a ResultSet, a pointer to a node in a graph that can be walked to query for data.\n", "\n", "The provided resource does not necessarily have to exist in the graph, however, any operations on it will produce an empty set.\n", "\n", "\n", "### Dataset\n", "\n", "Represents a set of RDF Quad instances.\n", "\n", "This implements most of the RDF/JS: Dataset specification, using six indexes for fast querying.\n", "\n", "Instances of Dataset are uniquely identified by their instance. Datasets are mutable. Methods with a return value are pure, non-pure (mutating) methods always return undefined.\n", "\n", "\n", "### Variable\n", "\n", "Represents a variable for subgraph matching, in e.g. SPARQL queries. This is also an instance of RDFNode.\n", "\n", "A Variable instance may be used in a TriplePattern instance. Instances are not allowed in Triple statements, since they're for subgraph matching, and not actual graph data.\n", "\n", "\n", "### ResultSet\n", "\n", "Represents a node in an instance of a graph, whose relationships inside the graph can be walked and then queried. This is called ResultSet instead of NodeSet because it also contains a pointer to the graph of data and other nodes that can be walked.\n", "\n", "Properties:\n", "\n", "* ResultSet#length - provides the size of the set\n", "\n", "#### ResultSet#rel(predicate)\n", "\n", "Walks the predicate relationship over each node in the set, returning a new ResultSet with the destination nodes, and a reference to the same graph.\n", "\n", "If the current set is an empty set, the return value will also be an empty set.\n", "\n", "If any nodes in the current set are literals, they will be ignored and will not produce any destination nodes.\n", "\n", "#### ResultSet#rev(predicate)\n", "\n", "Walks the predicate relationship backwards from each node in the set, returning a new ResultSet with the destination nodes, and a reference to the same graph.\n", "\n", "If the current set is an empty set, the return value will also be an empty set.\n", "\n", "This method will walk backwards from Literal, destination nodes will be BlankNode or NamedNode.\n", "\n", "#### ResultSet#toArray()\n", "\n", "Return the nodes in the set as an Array.\n", "\n", "#### ResultSet#some(function callback)\n", "\n", "Same behavior as Array#some: Evaluates callback over each RDFNode in the ResultSet, and returns true if the callback returns truthy for any of them.\n", "\n", "#### ResultSet#every(function callback)\n", "\n", "Same behavior as Array#every: Evaluates callback over each RDFNode in the ResultSet, and returns true if the callback returns truthy for all of them.\n", "\n", "#### ResultSet#filter(function callback)\n", "\n", "Same behavior as Array#filter: Evaluates callback over each RDFNode in the ResultSet, and returns a new ResultSet with the triples that evaluated truthy.\n", "\n", "#### ResultSet#forEach(function callback)\n", "\n", "Same behavior as Array#forEach: Evaluates callback over each RDFNode in the ResultSet.\n", "\n", "#### ResultSet#map(function callback)\n", "\n", "Same behavior as Array#map: Evaluates callback over each RDFNode in the ResultSet, and returns a new ResultSet of each of the returned triples.\n", "\n", "#### ResultSet#reduce(function callback, any initial)\n", "\n", "Same behavior as Array#reduce: Evaluates callback over each RDFNode in the ResultSet with the current node and the previous return value, or initial if the first item.\n", "\n", "#### ResultSet#one()\n", "\n", "Returns the only item in the set if there is one, or null otherwise. Or else if there is more than one item in the set, throws an Error.\n", "\n", "\n", "### TriplePattern\n", "\n", "A variant of Triple that allows Variable instances in the subject, predicate, or object.\n", "\n", "\n", "### TurtleParser\n", "\n", "An implementation of the Data parser API of RDF Interfaces.\n", "\n", "To synchronously parse a Turtle document, use TurtleParser.parse()\n", "\n", "\n", "### TurtleParser.parse(document, base)\n", "\n", "Returns a TurtleParser that has processed document with given base.\n", "\n", "The parsed Graph instance is available at TurtleParser#graph:\n", "\n", "javascript\n", "var parse = rdf.TurtleParser.parse('<http://example.com/> a <http://example.com/Page> .');\n", "console.log(parse.graph.toArray().join(\"\\n\"));\n", "\n", "\n", "### parse(object, id)\n", "\n", "Returns an object generated by parsing the properties of object to create Triples about id. These can later be serialized to a Turtle document or a Graph.\n", "\n", "The format is similar to JSON-LD, except strings are assumed to be IRIs or CURIEs by default. The @context, @vocab, @set, @list, and @id properties work as in JSON-LD.\n", "\n", "The id argument, if provided, must be a fully qualified IRI, and should be a NamedNode or BlankNode.\n", "\n", "\n", "#### parse(object, id).n3()\n", "\n", "Returns a string that's a Turtle document parsed out of object.\n", "\n", "\n", "#### parse(object, id).graphify()\n", "\n", "Returns a Graph of the triples parsed out of object.\n", "\n", "\n", "### RDFEnvironment\n", "\n", "RDFEnvironment is the data factory that generates RDF nodes, graphs, and stores process-level prefix mappings.\n", "\n", "It implements the RDF Environment API of RDF Interfaces.\n", "\n", "The rdf module creates one such global environment by default, accessible at rdf.environment. Others are created where necessary, e.g. when parsing a Turtle document, and may be created using new rdf.RDFEnvironment.\n", "\n", "\n", "### environment\n", "\n", "The environment export is the default instance of RDFEnvironment.\n", "\n", "Generally, you'll want to alias this to something:\n", "\n", "javascript\n", "var rdfenv = require('rdf').environment;\n", "\n", "\n", "\n", "### Prefixes\n", "\n", "#### ns(prefix)\n", "\n", "Returns an IRI factory, a function that produces an IRI of prefix plus the provided argument. It's a simple wrapper around string concatenation:\n", "\n", "javascript\n", "var foaf = rdf.ns('http://xmlns.com/foaf/0.1/');\n", "foaf('knows')\n", "\n", "\n", "#### rdfns(name)\n", "\n", "Returns an IRI produced by appending name to the rdf: namespace, http://www.w3.org/1999/02/22-rdf-syntax-ns#.\n", "\n", "#### rdfsns(name)\n", "\n", "Returns an IRI produced by appending name to the rdfs: namespace, http://www.w3.org/2000/01/rdf-schema#.\n", "\n", "#### xsdns(name)\n", "\n", "Returns an IRI produced by appending name to the xsd: namespace, http://www.w3.org/2001/XMLSchema#.\n", "\n", "\n", "### Builtins\n", "\n", "Instead of using NamedNode, URIs by default are represented as plain strings. The RDFNode interface may be overloaded onto the standard String object using rdf.setBuiltins() or onto a particular prototype by using:\n", "\n", "\trdf.builtins.setObjectProperties(Object.prototype);\n", "\trdf.builtins.setStringProperties(String.prototype);\n", "\trdf.builtins.setArrayProperties(Array.prototype);\n", "\trdf.builtins.setBooleanProperties(Boolean.prototype);\n", "\trdf.builtins.setDateProperties(Date.prototype);\n", "\trdf.builtins.setNumberProperties(Number.prototype);\n", "\n", "as done in the setBuiltins function call in lib/Builtins.js.\n", "\n", "This extends the prototype definitions to act as native RDF types as well, for example:\n", "\n", "\ttrue.toNT(); // "true"^^http://www.w3.org/2001/XMLSchema#boolean\n", "\t(12 * 1.4).toNT(); // "12.3"^^http://www.w3.org/2001/XMLSchema#decimal\n", "\n", "#### Object Builtins\n", "\n", "Any two values may be compared with each other using the equals method:\n", "\n", "\t(true).equals(rdf.environment.createLiteral('true', null, 'xsd:boolean'.resolve()) // true\n", "\n", "The node type may be queried with the nodeType method:\n", "\n", "\t"_:bnode".nodeType()\n", "\t"http://example.com/\".nodeType()\n", "\n", "An object may be assigned a URI and parsed for triples with the ref method:\n", "\n", "\tvar structure =\n", "\t\t{ 'dbp:dateOfBirth': '1879-03-14'.tl('xsd:date')\n", "\t\t, 'foaf:depictation': 'http://en.wikipedia.org/wiki/Image:Albert_Einstein_Head.jpg'\n", "\t\t}.ref('dbr:Albert_Einstein');\n", "\n", "ref may be called without any argument to create a BlankNode.\n", "\n", "The resulting object has a number of methods:\n", "\n", "* structure.n3() returns a Turtle/N3 document close to the original structure.\n", "* structure.toNT() returns an N-Triples formatted list of triples.\n", "* structure.graphify() returns an IndexedGraph of triples.\n", "\n", "If multiple properties with the same predicate need to be added, put the multiple values in an Array:\n", "\n", "\t{a: ['foaf:Person']}.ref()\n", "\n", "An Array may also be used to make an RDF Collection (linked list), with the toList method:\n", "\n", "\t['rdfs:Class', 'rdfs:Resource'].toList()\n", "\n", "#### String Builtins\n", "\n", "Strings may be used in place of a NamedNode and BlankNode, and have the same properties. There are the following methods:\n", "\n", "* tl(type) creates a typed literal out of the given value.\n", "* l(lang) creates a standard literal, with an optional language value.\n", "* resolve() resolves a CURIE/term to an IRI. Unlike the environment/profile method, this returns the original string if unsuccessful (for instance, if the string is already a URI).\n", "\n", "URIs passed to these functions may be CURIEs and are resolved with the global rdf.environment.\n", "\n", "\n", "## Tests\n", "\n", "A Mocha test suite is found in the tests directory. Run make test to evaluate the tests.\n", "\n", "\n", "## Index of Files\n", "\n", "* bin/turtle-equal.js - executable that determines of two Turtle files encode the same graph\n", "* bin/turtle-nt.js - executable that prints an N-Triples document of the triples found in the listed Turtle files\n", "* index.js - exposed module entry point\n", "* lib/ - additional library files imported by index.js\n", "* Makefile - Downloads and runs test suite\n", "* package.json - some metadata about this package\n", "* README.md - You're looking at it\n", "* README.ipynb - Sources for execution results in README.md\n", "* test/.test.js - Mocha test suite files\n", " test/graph-test-lib.js - A generic test for a Graph interface\n", "* test/TurtleTests/ - Tests from the Turtle test suite are extracted here\n", "* UNLICENSE - Public Domain dedication" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Javascript (Node.js)", "language": "javascript", "name": "javascript" }, "language_info": { "file_extension": ".js", "mimetype": "application/javascript", "name": "javascript", "version": "11.13.0" } }, "nbformat": 4, "nbformat_minor": 2 }