Filtering data in SPARQL query using python script
Question
I am trying to get uri against firstname literal of the user using following query in RDFlib Python.
plugin.register(
'sparql', rdflib.query.Processor,
'rdfextras.sparql.processor', 'Processor')
plugin.register(
'sparql', rdflib.query.Result,
'rdfextras.sparql.query', 'SPARQLQueryResult')
f1Str="Thomas"
ecsuri= GraphS.query("""
PREFIX akt: <http://www.aktors.org/ontology/portal#>
SELECT ?akturi WHERE{
?akturi akt:family-name ?fname.
FILTER (?fname = """+f1Str+""")
}""")
It gives following error and it seems to be due to f1Str, how can we filter data in SPARQL using value stored in some variable. Please help.
*Exception Type: ParseException
Exception Value: Expected "}" (at char 481), (line:10, col:29)*
Solution
Just try to cast your SPARQL variable to string with the str()
filter
FILTER (str(?fname) = """+f1Str+""")
If you need a case insensitive search, you can also do a regex query like this :
FILTER (regex(str(?fname),"""+f1Str+""","i"))
OTHER TIPS
Make sure f1Str
is in SPARQL syntax:
f1Str="'Thomas'" # SPARQL quoted string.
or
f1Str="Thomas"
FILTER (?fname = '"""+f1Str+"""') # Add SPARQL quotes
Also, put some newlines in the query string - the error messages will be more useful to you.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow