5

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)*
imran
  • 199
  • 3
  • 11

2 Answers2

3

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

Dominique Guardiola
  • 3,431
  • 2
  • 22
  • 22
  • Updated query looks like this but gives error **TypeError bad operand type for unary +: 'str' at statement FILTER** f1Str="Thomas" ecsuri= GraphS.query(' " PREFIX foaf: "' + + '" PREFIX akt: "' + + '" PREFIX owl: "' + + '" SELECT ?uri WHERE{ "' + + '" ?akturi akt:family-name ?fname "' + + '" FILTER (regex(str(?fname),'"+f1Str+"', "i")). "' + + '" }"') – imran Oct 11 '12 at 13:58
  • Andy is right, you're missing a quote before and after python triple quotes – Dominique Guardiola Oct 11 '12 at 19:08
0

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.

AndyS
  • 16,345
  • 17
  • 21