简体   繁体   中英

How can you predefine a variable in a SPARQL query

I have created a SPARQL query to retrieve a lot of information about workflow elements. The query talks to a database and is called from Python. The query is in a form like this:

"""SELECT ?input ?value1 ?value2 ?value3 ....
WHERE {?input rdf:type InputVar.
?input property1 ?value1.
?input property2 ?value2.
?input property3 ?value3.
.... etc....
}"""

This query will then return to me all of the values corresponding to the property I want to know.

What I now want my query to be able to do is I want it to be able to both look for ALL input variables (like it does now) and I want it to be able to collect the information for ONE, specified input. This would be possible doing something like this:

%s property1 ?value1
%s property2 ?value2

Where I would let %s, depending on if there is a name specified, be ?input or inputname (the name specified).

However, if I do it like this I will need lots of %s's, as I am extracting quite some properties.

In SPARQL, would it be possible to define the name of the variable you want to look for? So would it be possible to do something like this?

    """SELECT ?input ?value1 ?value2 ?value3 ....
    WHERE {(?input=inputname)
    ?input rdf:type InputVar.
    ?input property1 ?value1.
    ?input property2 ?value2.
    ?input property3 ?value3.
    .... etc....
    }"""

So add something like (?input=inputname) at the beginning, so it only looks for this value?

In the general case you can try using the VALUES clause for this eg

SELECT *
WHERE 
{
  VALUES ?input { <http://myConstant> }
  ?input rdf:type InputVar.
  ?input property1 ?value1.
  ?input property2 ?value2.
  ?input property3 ?value3.
  # etc.
}

However it is important to understand that this doesn't actually do what you want directly. Semantically what it does is join the constant into the matches for the graph pattern thus eliminating matches where ?input does not match your constant. Some query engines may be smart enough to simplify this to a substitution but not all of them will and that will only be applicable for relatively simple queries.

It sounds like you are really after some kind of prepared/parameterized query support as found in most SQL APIs?

Take a look at What's the best way to parameterise SPARQL queries which discusses how to do this in various APIs.

Since you mention Python the answer using Python may be of particular interest which is based off an example of prepared queries from the RDFLib docs

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