简体   繁体   中英

Filtering data in SPARQL query using python script

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)*

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"))

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.

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