Recent from talks
Nothing was collected or created yet.
Turtle (syntax)
View on Wikipedia
| Terse RDF Triple Language | |
|---|---|
| Filename extension |
.ttl |
| Internet media type |
text/turtle |
| Developed by | Dave Beckett |
| Latest release | RDF 1.1 Turtle (REC) 25 February 2014 |
| Type of format | Semantic Web |
| Container for | RDF data |
| Extended from | N-Triples, Notation3 |
| Extended to | TriG |
| Website | www |
In computing, Terse RDF Triple Language (Turtle) is a syntax and file format for expressing data in the Resource Description Framework (RDF) data model. Turtle syntax is similar to that of SPARQL, an RDF query language. It is a common data format for storing RDF data, along with N-Triples, JSON-LD and RDF/XML.
RDF represents information using semantic triples, which comprise a subject, predicate, and object. Each item in the triple is expressed as a Web URI. Turtle provides a way to group three URIs to make a triple, and provides ways to abbreviate such information, for example by factoring out common portions of URIs. For example, information about Huckleberry Finn could be expressed as:
<http://example.org/books/Huckleberry_Finn> <http://example.org/relation/author> <http://example.org/person/Mark_Twain> .
History
[edit]Turtle was defined by Dave Beckett as a subset of Tim Berners-Lee and Dan Connolly's Notation3 (N3) language, and a superset of the minimal N-Triples format. Unlike full N3, which has an expressive power that goes much beyond RDF, Turtle can only serialize valid RDF graphs. Turtle is an alternative to RDF/XML, the original syntax and standard for writing RDF. As opposed to RDF/XML, Turtle does not rely on XML and is generally recognized as being more readable and easier to edit manually than its XML counterpart.
SPARQL, the query language for RDF, uses a syntax similar to Turtle for expressing query patterns.
In 2011, a working group of the World Wide Web Consortium (W3C) started working on an updated version of RDF, with the intention of publishing it along with a standardised version of Turtle. This Turtle specification was published as a W3C Recommendation on 25 February 2014.[1]
A significant proportion of RDF toolkits include Turtle parsing and serializing capability. Some examples of such toolkits are Redland, RDF4J, Jena, Python's RDFLib and JavaScript's N3.js.
Example
[edit]The following example defines 3 prefixes ("rdf", "dc", and "ex"), and uses them in expressing a statement about the editorship of the RDF/XML document:
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix dc: <http://purl.org/dc/elements/1.1/> .
@prefix ex: <http://example.org/stuff/1.0/> .
<http://www.w3.org/TR/rdf-syntax-grammar>
dc:title "RDF/XML Syntax Specification (Revised)" ;
ex:editor [
ex:fullname "Dave Beckett";
ex:homePage <http://purl.org/net/dajobe/>
] .
(Turtle examples are also valid Notation3).
The example encodes an RDF graph made of four triples, which express these facts:
- The W3C technical report on RDF syntax and grammar has the title RDF/XML Syntax Specification (Revised).
- That report's editor is a certain individual, who in turn
- Has full name Dave Beckett.
- Has a home page at a certain place.
Here are the triples made explicit in N-Triples notation:
<http://www.w3.org/TR/rdf-syntax-grammar> <http://purl.org/dc/elements/1.1/title> "RDF/XML Syntax Specification (Revised)" .
<http://www.w3.org/TR/rdf-syntax-grammar> <http://example.org/stuff/1.0/editor> _:bnode .
_:bnode <http://example.org/stuff/1.0/fullname> "Dave Beckett" .
_:bnode <http://example.org/stuff/1.0/homePage> <http://purl.org/net/dajobe/> .
The MIME type of Turtle is text/turtle. The character encoding of Turtle content is always UTF-8.[2]
Named graphs
[edit]TriG RDF syntax extends Turtle with support for named graphs.
See also
[edit]References
[edit]- ^ "RDF 1.1 Turtle - Terse RDF Triple LanguageTurtle". World Wide Web Consortium (W3C). 25 February 2014. Retrieved 16 December 2015.
- ^ "MIME Media Types: text/turtle". Internet Assigned Numbers Authority (IANA). 28 March 2011. Retrieved 27 November 2011.
External links
[edit]Turtle (syntax)
View on GrokipediaOverview
Definition and Purpose
Turtle, or Terse RDF Triple Language, is a textual syntax for representing Resource Description Framework (RDF) graphs in a compact and natural form. It extends the simpler N-Triples format by incorporating features such as prefix declarations, base URI specifications, and compact URI notations, enabling the serialization of RDF data without the verbosity of XML-based alternatives.[1] The primary purpose of Turtle is to offer a human-readable and concise method for expressing RDF triples—statements consisting of a subject, predicate, and object—facilitating easier authoring, debugging, and exchange of semantic web data across applications. Unlike RDF/XML, which prioritizes machine processing through structured markup, Turtle emphasizes brevity and intuitiveness, directly mapping to the RDF abstract syntax model while supporting interoperability in knowledge representation systems.[1] Key benefits include enhanced readability for developers and researchers, reduced file sizes compared to XML formats, and seamless compatibility with RDF tools like parsers and query engines. Developed through W3C's RDF Working Group as part of broader efforts to streamline semantic data exchange, Turtle originated from initiatives like the SWAD-Europe project (2002–2004) to address limitations in earlier RDF serializations.[1]Relation to RDF and Other Serializations
Turtle is a concrete syntax for serializing RDF graphs, fully conforming to the RDF 1.1 abstract syntax as defined in the RDF 1.1 Concepts and Abstract Syntax specification, with a Working Draft for RDF 1.2 Turtle published on November 7, 2025, introducing enhancements such as triple terms for reifying statements and support for directional language-tagged strings while maintaining backward compatibility.[4][3] Every valid Turtle document parses into an RDF graph consisting of subject-predicate-object triples, where the graph represents a set of such triples without inherent ordering.[5] This ensures that Turtle documents can be unambiguously mapped to the RDF data model, enabling interoperability across RDF-based tools and applications.[6] In terms of mapping rules, Turtle represents RDF triples such that subjects and predicates are restricted to IRIs or blank nodes, while objects can be IRIs, blank nodes, or literals.[7] This direct correspondence allows Turtle parsers to generate RDF graphs by resolving prefixed names to full IRIs and handling syntactic shortcuts like semicolons for repeated subjects or commas for repeated predicates, all while preserving the abstract triple structure.[8] Compared to other RDF serializations, Turtle offers a more compact and human-readable alternative to RDF/XML, which is based on XML and often verbose due to its tag-heavy structure for expressing triples and namespaces. Unlike N-Triples, a simpler line-oriented format that serializes each triple individually without support for prefixes or abbreviations, Turtle achieves greater compactness through namespace prefixes and shorthand notations. In contrast to JSON-LD, which embeds RDF data within JSON structures to facilitate integration with web APIs and JavaScript environments, Turtle uses a plain-text, triple-centric syntax optimized for direct RDF graph representation rather than JSON compatibility. Within the broader RDF ecosystem, Turtle plays a central role in data exchange and querying, serving as the basis for ontology files (such as those in OWL) and large-scale data dumps from knowledge bases. Its grammar forms a subset of the SPARQL 1.1 query language's triple patterns, allowing Turtle to embed directly into SPARQL queries for defining RDF data or graph patterns.[9] For handling RDF datasets—which extend graphs with named graphs—Turtle is extended by the TriG serialization, which adds syntax for labeling graphs with IRIs or blank nodes while reusing Turtle's triple notation.[10]Core Syntax
Prefix Declarations and IRIs
In Turtle, namespace prefixes are declared using the@prefix directive, which associates a short prefix identifier with an Internationalized Resource Identifier (IRI) to enable compact representation of resource names. The syntax is @prefix prefix: <IRI> ., where prefix is a valid prefix name consisting of one or more allowed characters (such as letters, digits, underscore, hyphen, and dot) followed by a colon, and <IRI> is the full IRI enclosed in angle brackets. This directive is case-sensitive for @prefix and can also be written as PREFIX prefix: <IRI> (case-insensitive) for compatibility with SPARQL. Multiple @prefix declarations can appear throughout a Turtle document, with later declarations overriding earlier ones for the same prefix.[11]
Once declared, prefixes are used to form prefixed names in the format prefix:localName, where localName is a sequence of characters representing the local portion of the IRI. This abbreviated form expands to the full IRI by concatenating the prefix IRI with the local name, facilitating readability in RDF triples without repeating long URIs. For instance, a declaration @prefix ex: <http://example.org/> . allows ex:resource to denote <http://example.org/resource>. Prefixed names must resolve to valid IRIs; an undefined prefix in a prefixed name results in a parsing error.[12][8]
Turtle also supports the @base directive to establish a base IRI for resolving relative IRIs, using the syntax @base <IRI> . or the case-insensitive BASE <IRI>. Relative IRIs, enclosed in angle brackets (e.g., <#fragment>), are resolved against this base IRI following the basic resolution algorithm in section 5.2 of RFC 3986, with IRI-specific handling for Unicode characters as defined in section 6.5 of RFC 3987. Absolute IRIs are written directly in angle brackets and do not require resolution, supporting Unicode characters, numeric escapes (e.g., \u0020 for space), and percent-encoding for non-ASCII characters. If no @base is specified, the base IRI may default from the document's retrieval URI or encapsulating context per RFC 3986 section 5.1. Invalid IRI syntax, such as malformed angle brackets or unescaped reserved characters, triggers a parsing failure.[13][14]
Triples and Graph Structure
In Turtle, the fundamental unit of data representation is the RDF triple, consisting of a subject, a predicate, and an object, which together assert a directed relationship in an RDF graph. The syntax for a basic triple is a sequence of these three components separated by whitespace and terminated by a period (.), such as <http://example.org/subject> <http://example.org/predicate> <http://example.org/object> . This format allows for a compact textual serialization of RDF data, where subjects and predicates are typically Internationalized Resource Identifiers (IRIs), and objects can be IRIs or literals. In RDF 1.2 Turtle, triple terms (e.g., <<subject predicate object>>) are introduced as a new object type for reifying statements, while maintaining backward compatibility with RDF 1.1 syntax.[7][3]
To express multiple triples sharing the same subject, Turtle uses a semicolon (;) after the object of the first triple, followed by additional predicate-object pairs without repeating the subject, as in <http://example.org/subject> <http://example.org/pred1> <http://example.org/obj1> ; <http://example.org/pred2> <http://example.org/obj2> . Similarly, for triples sharing both a subject and a predicate but differing in objects, a comma (,) separates the objects, enabling concise lists like <http://example.org/subject> <http://example.org/pred> <http://example.org/obj1> , <http://example.org/obj2> . These modifiers—semicolons for predicate-object lists and commas for object lists—streamline the notation for common patterns, such as properties with multiple values, while maintaining the underlying triple structure.[15][16]
A sequence of such triples within a Turtle document forms an RDF graph, where all statements contribute to a single default graph unless otherwise specified in extensions like TriG. Base Turtle does not include explicit delimiters for multiple graphs, implying that the entire document serializes one unnamed graph composed of the concatenated triples. For instance, the following forms a graph with three triples:
@prefix ex: <http://example.org/> .
ex:subject ex:pred "obj1" , "obj2" ;
ex:pred2 "obj3" .
@prefix ex: <http://example.org/> .
ex:subject ex:pred "obj1" , "obj2" ;
ex:pred2 "obj3" .
#) and extend to the end of the line, allowing inline annotations without affecting the parsed graph, as in ex:subject ex:pred "obj" . # This is a comment. Regarding parsing, directives such as @prefix must appear before any use of the defined prefix in the document, ensuring proper IRI resolution during processing. The document concludes at the end of the last triple (marked by a period) or directive, with no additional terminators required.[18][19][8]
Literals, Datatypes, and Language Tags
In Turtle, literals represent values that are not IRIs or blank nodes, serving as the object in RDF triples to denote simple data such as strings, numbers, or dates.[1] They are essential for expressing non-resource data in RDF graphs, allowing precise typing and internationalization. The syntax for literals is defined in the Turtle grammar, ensuring compatibility with RDF 1.1 concepts.[1] Turtle also supports unquoted numeric literals for common datatypes: integers (e.g., 42, equivalent to "42"^^xsd:integer), decimals (e.g., 3.14, equivalent to "3.14"^^xsd:decimal), and doubles (e.g., 1.2e3, equivalent to "1.2e3"^^xsd:double). Boolean literals are written as true or false (case-sensitive, equivalent to "true"^^xsd:boolean and "false"^^xsd:boolean).[20] Plain literals are untyped strings enclosed in double quotes, implicitly carrying the datatypexsd:string. For example, "example" denotes a simple string value.[1] Explicitly, they can be written as "string"^^xsd:string to affirm the datatype, though the plain form is more concise for strings.[1]
Typed literals extend this by associating a lexical form with a specific datatype IRI, using the syntax "lexical-form"^^<datatype-iri>. Common datatypes from the XML Schema namespace (xsd) include xsd:integer for integers (e.g., "42"^^xsd:integer) and xsd:dateTime for timestamps (e.g., "2023-01-01T00:00:00Z"^^xsd:dateTime).[1] The datatype IRI can be a full absolute IRI (e.g., <http://www.w3.org/2001/XMLSchema#integer>), a relative IRI, or a prefixed name like xsd:integer, resolved using prefix declarations or base IRI rules per RFC 3987.[1] This mechanism ensures literals conform to the lexical-to-value mapping defined in the datatype's specification, such as those in XML Schema Part 2.
Language-tagged literals specify strings with linguistic context, using the syntax "string"@language-tag. For instance, "hello"@en indicates an English string, while "bonjour"@fr-be tags a Belgian French variant.[1] Language tags follow BCP 47 conventions, allowing subtags like en-US for regional variants. These literals have no explicit datatype but are distinct from plain or typed strings in RDF semantics. In RDF 1.2 Turtle, language tags may include an optional directionality indicator (e.g., @en--rtl for right-to-left text direction), while maintaining backward compatibility.[1][3]
String content in literals supports escaping for special characters: backslashes escape double quotes (\"), single quotes (\'), backslashes (\\), newlines (\n), tabs (\t), and Unicode code points via \uXXXX or \UXXXXXXXX.[1] For multiline or complex strings, long literals use triple double quotes ("""content""") or triple single quotes ('''content'''), permitting unescaped newlines and quotes within (except the delimiter sequence). An example is """Line one\nLine two""", which preserves formatting without additional escapes.[1]
Literals are restricted to the object position in triples and cannot serve as subjects or predicates, aligning with RDF's abstract model where only IRIs or blank nodes can identify resources in those roles.[1] This positioning integrates literals into graph structures, such as in predicates like ex:name "Alice"@en ..[4]
Advanced Constructs
Blank Nodes and Node IDs
In Turtle, blank nodes represent anonymous resources within an RDF graph that lack a global identifier such as an IRI. These nodes are essential for expressing complex structures without assigning permanent names, allowing for temporary placeholders during serialization. Blank nodes are scoped to the document or graph in which they appear, ensuring they do not imply global uniqueness across different datasets.[21] Implicit blank nodes are introduced using empty square brackets[] when serving as the subject or object of a triple. For example, the statement [] ex:prop "value" . creates a fresh blank node as the subject, linked via the property ex:prop to the literal "value". Each instance of [] generates a unique blank node identifier, distinct from all others in the document, which supports nesting for hierarchical descriptions without label conflicts.[22]
A related syntactic convenience is the predicate-object list, where a blank node is implied as the subject followed by property-value pairs in brackets, such as [ ex:prop1 "value1" ; ex:prop2 "value2" ] .. This abbreviates multiple triples sharing the same anonymous subject, equivalent to separate statements like _:anon1 ex:prop1 "value1" . _:anon1 ex:prop2 "value2" ., where _:anon1 is an internal fresh identifier. Nesting within these lists is permitted, with each inner [] producing an additional distinct blank node.[23]
Explicit blank node labels provide a mechanism to reference the same anonymous node multiple times within a document, using the syntax _:label, where label adheres to production rules for local names (e.g., alphanumeric characters, underscores, and certain punctuation like dots or hyphens, but not starting or ending with a dot). For instance:
_:alice foaf:knows _:bob .
_:bob foaf:name "Bob" .
_:alice foaf:knows _:bob .
_:bob foaf:name "Bob" .
_:alice and _:bob denote two distinct blank nodes, reusable across statements but unique within the graph's scope—repeating _:alice would refer to the same node, while a different label like _:charlie introduces a new one. Labels must be unique per graph to avoid ambiguity, and their scope is limited to the containing document in base Turtle.[21]
For compatibility with N-Triples, Turtle's blank node syntax aligns closely, using _:nodeId where nodeId follows similar naming conventions to facilitate round-tripping between formats. Although not a core feature of Turtle, some parsers recognize N-Triples-style node IDs (e.g., _:genid1) to preserve exact blank node mappings during serialization and deserialization, ensuring structural fidelity without altering the RDF graph semantics.[24]
Blank nodes have specific limitations in Turtle: they cannot serve as predicates, which must always be IRIs, and in base Turtle, they are not reusable across multiple graphs—each graph treats labels and implicit nodes independently to prevent unintended merging. These constraints maintain the existential semantics of blank nodes, treating them as existentially quantified variables rather than named entities.[17]
Lists and Collections
In Turtle, RDF collections provide a mechanism for representing ordered sequences of RDF terms using the RDF vocabulary defined in RDF Schema. This vocabulary includes the propertiesrdf:first and rdf:rest, along with the resource rdf:nil, which together form a linked list structure where each node points to the first element of the list via rdf:first and to the subsequent node via rdf:rest, terminating with rdf:nil to denote the end of the list.[25] These constructs enable the modeling of finite, ordered collections in RDF graphs, distinct from unordered containers like bags or sequences.[26]
Turtle offers a compact syntax for these collections using parentheses, which automatically generates a chain of blank nodes connected by rdf:first and rdf:rest. A collection is written as ( term1 term2 ... termN ), where each term is a valid RDF term such as an IRI, literal, or nested collection. This syntax can appear in either the subject or object position of a triple. For instance, the notation ( "a" "b" ) ex:prop . expands to the following triples using anonymous blank nodes:
_:b0 rdf:first "a" .
_:b0 rdf:rest _:b1 .
_:b1 rdf:first "b" .
_:b1 rdf:rest rdf:nil .
ex:someSubject ex:prop _:b0 .
_:b0 rdf:first "a" .
_:b0 rdf:rest _:b1 .
_:b1 rdf:first "b" .
_:b1 rdf:rest rdf:nil .
ex:someSubject ex:prop _:b0 .
_:b0 serves as the head of the list, with the property ex:prop linking to it.[27][28]
Nested collections allow for more complex hierarchical structures, such as (( "a" ) "b" ), which represents a list whose first element is itself a list containing "a", followed by "b". This expands to additional blank nodes, with the inner ("a") forming its own rdf:first/rdf:rest chain ending in rdf:nil. Such nesting supports tree-like data representations within RDF.[27]
As an alternative to the compact syntax, authors can explicitly construct collections using blank node identifiers and predicate-object lists, for example:
_:b0 rdf:first "a" ;
rdf:rest _:b1 .
_:b1 rdf:first "b" ;
rdf:rest rdf:nil .
ex:someSubject ex:prop _:b0 .
_:b0 rdf:first "a" ;
rdf:rest _:b1 .
_:b1 rdf:first "b" ;
rdf:rest rdf:nil .
ex:someSubject ex:prop _:b0 .
() directly denotes rdf:nil, producing no additional blank nodes but serving as the list terminator in expansions.[17][29]
RDF collections in Turtle are particularly suited for use cases where the order of elements is semantically significant, such as enumerating arguments in functional descriptions or defining ordered sets in ontologies, ensuring that the sequence is preserved in the resulting RDF graph.[25]
Named Graphs and Datasets
Turtle, as defined in the RDF 1.1 specification, is limited to serializing a single default RDF graph and lacks native support for named graphs or RDF datasets.[1][30] This means that a standard Turtle document represents only one set of triples without the ability to associate subsets of those triples with specific graph names, which is essential for representing multi-graph structures in RDF.[4] To address this limitation, TriG serves as a direct extension of Turtle syntax, enabling the serialization of RDF datasets that include a default graph and multiple named graphs.[31] In TriG, named graphs are denoted by enclosing a block of triples within curly braces{} immediately following an IRI or blank node identifier that names the graph, as in the syntax ex:graphName { ex:subject ex:predicate ex:object . }.[31] This structure allows for the compact representation of datasets, where the default graph consists of all triples outside of any named graph blocks, and each named graph remains isolated within its braces.[31] TriG optionally permits the use of the GRAPH keyword borrowed from SPARQL syntax, such as GRAPH ex:graphName { ex:subject ex:predicate ex:object . }, though this is equivalent to the label-brace form and not required for core serialization.[31]
RDF datasets in this context are abstractly modeled as collections of quadruples—each consisting of a subject, predicate, object, and graph name—extending the triple-based structure of single graphs.[4] Turtle parsers often provide compatibility with TriG as an extension, allowing seamless handling of dataset serializations in tools that primarily expect Turtle input.[30] According to parsing rules in the TriG specification, triples within a named graph block are scoped exclusively to that graph and do not contribute to the default graph, while blank nodes may be shared across graphs if explicitly referenced.[31]
The TriG syntax was standardized by the W3C RDF Working Group as a Recommendation on 25 February 2014, alongside RDF 1.1, and is recommended for serializing multi-graph RDF datasets in a human-readable format compatible with Turtle.[31] Graph names in TriG follow the same IRI resolution mechanisms as in Turtle, leveraging prefix declarations for brevity.[31]
In SPARQL-Turtle, the GRAPH keyword is used within query patterns to specify operations against named graphs, such as GRAPH ?g { ?s ?p ?o }, but this applies to query construction rather than data serialization itself.[32]
RDF 1.2 Enhancements
The RDF 1.2 Turtle working draft, published on November 7, 2025, introduces new advanced constructs while maintaining backward compatibility with RDF 1.1.[3] Triple terms represent entire RDF statements as terms, using the syntax<< subject predicate object >>, which can be used as objects in triples. This enables native reification of statements without relying on blank nodes or additional resources. For example, ex:statement << ex:s ex:p ex:o >> . reifies the triple ex:s ex:p ex:o as an object. The property rdf:reifies links the triple term to the reified statement.[33]
Additionally, annotation syntax allows attaching metadata to triples, such as :a :p :o ~ :t {| :q :r |} ., where ~ :t quotes the triple and {| :q :r |} adds annotations. These features enhance expressive power for semantic annotations and graph structures, optional in parsers via a VERSION "1.2" declaration.[34] No changes were made to blank nodes, collections, or named graphs/datasets syntax.[3]
Examples and Usage
Basic Turtle Document
A basic Turtle document consists of a sequence of directives followed by triples that form an RDF graph, using a compact textual syntax for readability.[1] The following is a simple, complete example of a Turtle document describing a person named Alice who knows Bob and is 30 years old:@base <http://example.org/> .
@prefix ex: <http://example.org/> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
ex:Alice
ex:knows ex:Bob ;
ex:age "30"^^xsd:integer .
@base <http://example.org/> .
@prefix ex: <http://example.org/> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
ex:Alice
ex:knows ex:Bob ;
ex:age "30"^^xsd:integer .
@base and @prefix directives to establish IRI resolution and namespace abbreviations, respectively, each terminated by a period.[35] The triples follow, where ex:Alice is the subject, sharing predicates with a semicolon for multiple objects or properties, and the entire statement ends with a period.[7] This shorthand avoids repeating the subject, promoting conciseness.[15]
Turtle files conventionally use the .ttl extension and the text/turtle MIME type, with UTF-8 encoding.[36]
Such documents can be validated by parsing them into an RDF graph using libraries like RDFLib in Python or Apache Jena in Java, which confirm syntactic correctness and produce the corresponding triples.[37]
Common pitfalls include omitting the required period after directives or triples, which causes parsing failures, and unbalanced quotation marks in literals, leading to invalid strings.[17][20]
Complex Example with Named Graphs
To illustrate the integration of Turtle's core and advanced features within a multi-graph context, consider a TriG document that combines prefix declarations, IRI subjects and predicates, blank nodes, typed literals, language-tagged literals, RDF lists, and named graphs. This example models a social network scenario where personal data is partitioned into a default graph for general relationships and named graphs for contextual details, such as age information and interests represented as lists. The syntax adheres to the TriG recommendation, which extends Turtle to serialize RDF datasets comprising a default graph and zero or more named graphs.@prefix ex: <http://example.org/> .
@prefix foaf: <http://xmlns.com/foaf/0.1/> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
# Default graph: Basic relationships
ex:Alice ex:knows ex:Bob .
ex:Bob ex:knows ex:Charlie .
# Named graph for personal details
ex:personalContext {
ex:Alice a foaf:Person ;
foaf:name "[Alice Smith](/page/Alice_Smith)"@en ;
ex:age "25"^^[xsd:integer](/page/Integer) .
_:bob a foaf:Person ;
foaf:name "Bob Johnson"@en ;
ex:age "30"^^[xsd:integer](/page/Integer) ;
ex:interests ( ex:reading ex:hiking ex:programming ) .
}
# Named graph for group affiliations using a blank node list
ex:groupContext {
ex:Alice ex:memberOf _:group1 .
_:group1 rdf:first ex:Alice ;
rdf:rest _:group2 ;
rdf:type rdf:List .
_:group2 rdf:first ex:Bob ;
rdf:rest rdf:nil ;
rdf:type rdf:List .
}
@prefix ex: <http://example.org/> .
@prefix foaf: <http://xmlns.com/foaf/0.1/> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
# Default graph: Basic relationships
ex:Alice ex:knows ex:Bob .
ex:Bob ex:knows ex:Charlie .
# Named graph for personal details
ex:personalContext {
ex:Alice a foaf:Person ;
foaf:name "[Alice Smith](/page/Alice_Smith)"@en ;
ex:age "25"^^[xsd:integer](/page/Integer) .
_:bob a foaf:Person ;
foaf:name "Bob Johnson"@en ;
ex:age "30"^^[xsd:integer](/page/Integer) ;
ex:interests ( ex:reading ex:hiking ex:programming ) .
}
# Named graph for group affiliations using a blank node list
ex:groupContext {
ex:Alice ex:memberOf _:group1 .
_:group1 rdf:first ex:Alice ;
rdf:rest _:group2 ;
rdf:type rdf:List .
_:group2 rdf:first ex:Bob ;
rdf:rest rdf:nil ;
rdf:type rdf:List .
}
ex:personalContext named graph incorporates a typed literal ("25"^^xsd:integer) for age, a language-tagged literal ("Alice Smith"@en) for the name, a blank node (_:bob) as the subject for Bob's details to avoid global identifiers, and an RDF list ( ex:reading ex:hiking ex:programming ) to denote multiple interests concisely. The ex:groupContext named graph demonstrates explicit list construction using blank nodes and RDF vocabulary, where _:group1 and _:group2 form a linked list terminating in rdf:nil, representing a collection of group members. Prefixes like ex:, foaf:, xsd:, and rdf: are declared at the document level and scoped to the entire TriG serialization, enabling compact IRI references throughout.[38][39]
When parsed, this TriG document yields an RDF dataset consisting of one default graph with two triples and two named graphs: ex:personalContext with 13 triples (including the expansion of the interests list, which generates 6 additional triples for the RDF list structure using rdf:first and rdf:rest) and ex:groupContext with 7 triples (from the explicit list construction using rdf:first, rdf:rest, and type assertions). The default graph remains unnamed, while the named graphs are identified by their respective IRIs (<http://example.org/personalContext> and <http://example.org/groupContext>), allowing queries to target specific contexts, such as retrieving age data only from the personal graph. This structure supports provenance tracking and modular data management in RDF applications, as defined in the RDF 1.2 Concepts specification.[40]
To verify and load such a TriG document programmatically, libraries like Apache Jena provide robust support. For instance, in Java, the RDFDataMgr class can read the file into a Dataset object, preserving the graph structure:
import org.apache.jena.rdf.model.Dataset;
import org.apache.jena.riot.RDFDataMgr;
Dataset dataset = RDFDataMgr.loadDataset("example.trig");
Model defaultGraph = dataset.getDefaultModel();
Model personalGraph = dataset.getNamedModel("http://example.org/personalContext");
import org.apache.jena.rdf.model.Dataset;
import org.apache.jena.riot.RDFDataMgr;
Dataset dataset = RDFDataMgr.loadDataset("example.trig");
Model defaultGraph = dataset.getDefaultModel();
Model personalGraph = dataset.getNamedModel("http://example.org/personalContext");
example.trig into memory, where the default model contains the unnamed graph triples, and named models are accessible by their graph name IRIs for further querying or inference. Jena's RIOT (RDF Interchange Toolkit) parser handles TriG natively, validating syntax and expanding abbreviations like lists during ingestion.[37]
A real-world application of this syntax appears in extensions of the Friend of a Friend (FOAF) vocabulary, where personal profiles are often serialized in Turtle and embedded within named graphs for privacy or versioning. For example, a FOAF snippet describing a person's online presence can be isolated in a named graph:
@prefix foaf: <http://xmlns.com/foaf/0.1/> .
GRAPH <http://example.org/profile> {
_:me a foaf:Person ;
foaf:name "Jane Doe" ;
foaf:mbox <mailto:[email protected]> ;
foaf:homepage <http://example.org/jane> ;
foaf:depiction <http://example.org/jane/photo.jpg> .
}
@prefix foaf: <http://xmlns.com/foaf/0.1/> .
GRAPH <http://example.org/profile> {
_:me a foaf:Person ;
foaf:name "Jane Doe" ;
foaf:mbox <mailto:[email protected]> ;
foaf:homepage <http://example.org/jane> ;
foaf:depiction <http://example.org/jane/photo.jpg> .
}
<http://example.org/profile>, facilitating integration into larger datasets while maintaining FOAF's semantic interoperability for social networking data. The FOAF specification endorses Turtle as a preferred serialization, and such named graph usage aligns with best practices for RDF datasets in linked data publishing.[41][42]
RDF 1.2 Turtle Example
RDF 1.2 Turtle, as a working draft published on November 7, 2025, introduces triple terms (also known as quoted triples) to allow RDF triples to be used as subjects or objects in other triples, enabling direct reification without additional blank nodes or vocabulary. This enhances expressivity for annotating statements, such as adding provenance or confidence levels to edges in RDF graphs.[3] The following is a simple example using a triple term to reify a "knows" relationship with an additional annotation:@prefix ex: <http://example.org/> .
@prefix prov: <http://www.w3.org/ns/prov#> .
# Basic triple
ex:Alice ex:knows ex:Bob .
# Reify the above triple as a term and annotate it
<< ex:Alice ex:knows ex:Bob >> ex:[confidence](/page/Confidence) "0.9"^^xsd:float ;
prov:wasGeneratedAt <2025-11-17T12:00:00Z> .
@prefix ex: <http://example.org/> .
@prefix prov: <http://www.w3.org/ns/prov#> .
# Basic triple
ex:Alice ex:knows ex:Bob .
# Reify the above triple as a term and annotate it
<< ex:Alice ex:knows ex:Bob >> ex:[confidence](/page/Confidence) "0.9"^^xsd:float ;
prov:wasGeneratedAt <2025-11-17T12:00:00Z> .
<< ex:Alice ex:knows ex:Bob >> denotes the triple as a term (a proposition), which serves as the subject for further triples asserting a confidence value (a typed literal) and a generation timestamp (an IRI). This syntax is backward-compatible with RDF 1.1 Turtle but extends it for advanced modeling, such as in knowledge graphs requiring statement-level metadata. Triple terms can be nested and are parsed according to the RDF 1.2 Turtle grammar.[43]
Development and Standardization
Origins and Evolution
Turtle's development originated during the Semantic Web Advanced Development Europe (SWAD-Europe) project from 2002 to 2004, as a simplification of Notation3 (N3), a readable RDF syntax developed by Tim Berners-Lee in 1998 to provide a compact alternative to RDF/XML with extended expressiveness beyond standard RDF.[44] In 2004, Dave Beckett introduced Turtle, formally known as Terse RDF Triple Language, as a subset of N3 focused strictly on RDF serialization, extending the N-Triples format for greater human readability while maintaining machine parsability.[45] This design drew direct influence from N-Triples, a line-based RDF format standardized by the W3C in the RDF Test Cases Recommendation of February 2004. Early adoption of Turtle occurred within the Redland RDF Application Framework, where Beckett integrated it via the Raptor parser library, enabling practical use in RDF processing tools from the mid-2000s onward.[46] The syntax gained traction in the semantic web community due to feedback emphasizing its superior readability compared to RDF/XML, which was often criticized for verbosity and complexity in manual editing and debugging.[30] Key milestones in Turtle's development came through the W3C RDF Working Group, chartered from 2011 to 2014, which formalized RDF 1.1 specifications including Turtle.[47] The group advanced Turtle to Candidate Recommendation status on February 19, 2013, addressing compatibility and feature alignment, before its elevation to W3C Recommendation on February 25, 2014.[1] Paralleling this, the TriG syntax was developed concurrently for RDF datasets, extending Turtle to handle named graphs while preserving its terse structure.[31]Current Status and Implementations
Turtle, as defined in the RDF 1.1 specification, achieved W3C Recommendation status on February 25, 2014, establishing it as a stable textual syntax for serializing RDF graphs.[1] Since then, no major revisions have been issued to the RDF 1.1 Turtle specification, though editorial errata have addressed minor issues, such as IRI terminology clarifications reported in 2018 and missing elements in examples.[48] As of November 2025, work on RDF 1.2 Turtle remains in the Working Draft stage, published on November 7, 2025, introducing enhancements like support for triple terms, annotation syntax, and directional language-tagged strings to improve handling of bidirectional text.[3] Key implementations of Turtle parsing and serialization are available across programming languages. In Python, RDFLib provides comprehensive support for reading and writing Turtle files as part of its RDF processing toolkit. Apache Jena, a Java framework for Semantic Web applications, includes RIOT for efficient Turtle I/O operations, supporting formats like Turtle and TriG.[37] For JavaScript environments, rdflib.js enables Turtle handling in browsers and Node.js, facilitating client-side RDF manipulation.[49] SPARQL endpoints such as OpenLink Virtuoso integrate Turtle parsers for loading RDF data via SQL APIs and query services.[50] Tooling for Turtle development includes editors and validators integrated into Linked Data platforms. GraphDB Workbench offers a user interface for importing, editing, and visualizing Turtle documents within RDF repositories.[51] The W3C maintains test suites and errata for validation, while community tools like the Node.js-based Turtle Validator provide syntax checking.[48] These tools are commonly embedded in platforms for schema management and data publishing, enhancing Turtle's role in RDF workflows. Turtle sees widespread adoption in major Linked Data initiatives. Schema.org conducts its vocabulary development and publishes definitions in Turtle format, serving as the canonical RDF representation for structured data markup.[52] Wikidata provides full entity dumps in Turtle, enabling bulk RDF exports for research and integration, with recent releases maintaining compatibility through 2025.[53] Updates in 2025, aligned with RDF 1.2 drafts, emphasize improved Unicode support, such as excluding surrogate code points in UTF-8 encoding to align with modern text processing standards.[3] Despite its maturity, Turtle faces implementation gaps, particularly in web environments. Browsers lack native support for parsing or rendering Turtle, requiring JavaScript libraries like rdflib.js as polyfills for web applications.[49] This reliance on external libraries can introduce performance overhead in client-side scenarios, though server-side and hybrid tools mitigate these limitations effectively.References
- https://www.wikidata.org/wiki/Wikidata:Database_download
