Pedro
Pedro

Reputation: 4160

Jena: How to add properties with numeric values?

How can I add numeric values like float, int or date to a Resource using Jena?

I assume I'd have to use resource.addProperty(Property, String, RDFDataType), but how do I instantiate the correct RDFDataType for the above mentioned data types?

Upvotes: 3

Views: 6564

Answers (2)

castagna
castagna

Reputation: 1359

The 'official' documentation on typed literals is here: http://incubator.apache.org/jena/documentation/notes/typed-literals.html

You can use the addLiteral and add methods of a Jena Model, for example:

    Model model = ...

    model.addLiteral (subject, predicate, 10);
    model.addLiteral (subject, predicate, 0.5);
    model.addLiteral (subject, predicate, (float)0.5);
    model.addLiteral (subject, predicate, ResourceFactory.createTypedLiteral(20));
    model.addLiteral (subject, predicate, ResourceFactory.createTypedLiteral(0.99));
    model.addLiteral (subject, predicate, true);
    model.add (subject, predicate, ResourceFactory.createTypedLiteral("2012-03-11", XSDDatatype.XSDdate));
    model.add (subject, predicate, ResourceFactory.createTypedLiteral("P2Y", XSDDatatype.XSDduration));

RDFDatatype is an interface so you cannot instantiate it directly. However, look at classes implementing that interface. You'll find XSDDatatype is one of those classes. There are others.

If you want to see a complete example, have a look here: https://github.com/castagna/jena-examples/blob/master/src/main/java/org/apache/jena/examples/ExampleDataTypes_01.java. The output of ExampleDataTypes_01.java is the following RDF (serialized using Turtle format):

@prefix xsd:     <http://www.w3.org/2001/XMLSchema#> .
@prefix example:  <http://example.org/> .

example:s
      example:p1 "10"^^xsd:int ;
      example:p2 "0.5"^^xsd:double ;
      example:p3 "0.5"^^xsd:float ;
      example:p4 "20"^^xsd:int ;
      example:p5 "0.99"^^xsd:double ;
      example:p6 "true"^^xsd:boolean ;
      example:p7 "2012-03-11"^^xsd:date ;
      example:p8 "P2Y"^^xsd:duration .

Upvotes: 15

zazi
zazi

Reputation: 696

These are literals in RDF. You can utilise, e.g., the rdf:value property to add numeric values as literals to your resource. You can specify datatypes on these literals, e.g., xsd:int.

Upvotes: 1

Related Questions