Jena - How do I know if a particular resource is in a model?

I am trying to find out if I have a specific resource in the model. For this, I use:

model.getResource("example") 

Validating a document, this method behaves exactly like createResource. Then, even if it is not in the model, I will get a new resource.

How can I verify that I have a resource that avoids creating it when it is not?

Thanks in advance!

+6
source share
2 answers

In Yen, Resource objects themselves are not part of the model. The model contains only triples - Statement objects containing the object, predicate and object (usually abbreviated as SPO). Any of S, P, or O can be a resource (noting that a Property is a subtype of Resource in Yen and the RDF standard). Therefore, you need to clarify your question: "Does this model contain this resource":

  • Does model M really contain resource R as an object?

  • Does model M really contain resource R as a subject, predicate, or object?

This can be achieved as:

 Resource r = ... ; Model m = ... ; // does m contain r as a subject? if (m.contains( r, null, (RDFNode) null )) { .. } // does m contain r as s, p or o? if (m.containsResource( r )) { .. } 

By the way, in your sample code you have

 model.getResource("example") 

Returns a Resource object corresponding to the given URI, but does not affect triples in the model. This is because Model has both getResource and createResource - get is potentially a bit more efficient as it reuses resource objects, but the semantics are essentially identical. However, the argument you pass to getResource or createResource must be a URI . You borrow problems from the future if you start using tokens like "example" instead of full URIs, so I would advise you to stop this bad habit before you feel comfortable!

+12
source

After a little research, I found the following path. I don't know if this is really the best way to achieve it, but it works:

 Resource toSearch = ResourceFactory.createResource("example"); if(!model.containsResource(toSearch))...; 
+2
source

All Articles