简体   繁体   中英

SPARQL select based on the content of the subject

I'm new to SPARQL, and I am trying to select a property based on the content of the subject. For example, using the RDF data below, I want to return the result containing "var2_1":

<rdf:Description rdf:about="http://www.ontologydesignpatterns.org/ont/fred/domain.owl#var0">
    <rdf:type rdf:resource="http://www.ontologydesignpatterns.org/ont/fred/domain.owl#var2_0"/>
</rdf:Description>
<rdf:Description rdf:about="http://www.ontologydesignpatterns.org/ont/fred/domain.owl#var1">
    <rdf:type rdf:resource="http://www.ontologydesignpatterns.org/ont/fred/domain.owl#var2_1"/>
</rdf:Description>

This is the query I am writing, but it returns nothing, and I can't seem to find a way to specify that the subject should contain "var1":

SELECT ?t 
WHERE {
   ?s rdf:type ?t
   FILTER regex(?s, "var1")
}

I would appreciate help on the right way to do this.

The subject is not a string literal value, but an IRI: http://www.ontologydesignpatterns.org/ont/fred/domain.owl#var1 . To match this, you should not be using a regular expression, but instead use the actual IRI itself:

SELECT ?t 
WHERE {
  ?s rdf:type ?t
  FILTER(?s =  <http://www.ontologydesignpatterns.org/ont/fred/domain.owl#var1>)
}

or more succinct:

SELECT ?t 
WHERE {
   <http://www.ontologydesignpatterns.org/ont/fred/domain.owl#var1> rdf:type ?t
}

The other answer has already pointed out that your ?s is a URI, and should be matched directly instead of using a regular expression. In addition, it is worth keeping in mind that matching specific URIs becomes much simpler if you have the right prefixes defined. If we define a prefix for the file's URI, then the actual query pattern becomes much simpler:

PREFIX fred: <http://www.ontologydesignpatterns.org/ont/fred/domain.owl#>
SELECT ?t 
WHERE {
   fred:var1 rdf:type ?t
}

The query can become even simpler: rdf:type has a built-in abbreviation “ a ”, and the WHERE keyword is optional:

PREFIX fred: <http://www.ontologydesignpatterns.org/ont/fred/domain.owl#>
SELECT ?t {
   fred:var1 a ?t
}

Finally, if you really want to use a regular expression to match the URI, you can do that by converting the URI to a string using str :

SELECT ?t {
   ?s a ?t
   FILTER regex(str(?s), "var1")
}

But compared to the other options, this will be extremely slow on larger datasets.

Finally finally, to support AKSW's comment, here is the file converted from RDF/XML to Turtle:

PREFIX fred: <http://www.ontologydesignpatterns.org/ont/fred/domain.owl#>

fred:var0 a fred:var2_0.
fred:var1 a fred:var2_1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM