问题
Good day! I apply rdflib for python. I have a question. How can I put variable into SPARQL's query ? Instead of 'OSPF' in course:OSPF!
qres = g.query(
"""SELECT ?x ?z ?y
WHERE {
course:OSPF course:termName ?x.
course:OSPF ?s ?t.
?s ?d ?z.
?t course:termName ?y.
FILTER (regex(?z,"[^a-z]","i") && isLiteral(?z) )
}"""
,initNs=dict(course=Namespace.....
@msalvadores I want enter my Variable by console. --->python parse.py OSPF A value of variable(OSPF) may be another one. How can I initialize it into query(WHERE)? I have resolved my question by interpolation of variable several days ago. Like this:
qtest = "OSPF","OSPF"
q =( """SELECT ?x ?z ?y\
WHERE {\
course:%s course:termName ?x.\
course:%s ?s ?t.\
?s ?d ?z.\
?t course:termName ?y.\
FILTER (regex(?z,'[^a-z0-9]','i') && isLiteral(?z) )\
}ORDER BY ASC(?s)\
""")% qtest
qres = g.query(q, initNs=dict(course=Namespace
But I suppose it could be done another way. Because on my opinion the solution is not quite right presented by me.
回答1:
If you mean a Python variable in the query you could do just ...
qres = g.query(
"""SELECT ?x ?z ?y
WHERE {
"""+some_uri+""" course:termName ?x.
"""+some_uri+""" ?s ?t.
?s ?d ?z.
?t course:termName ?y.
FILTER (regex(?z,"[^a-z]","i") && isLiteral(?z) )
}"""
,initNs=dict(course=Namespace.....
If you want to transform course:OSPF into a variable in SPARQL then ...
qres = g.query(
"""SELECT ?newVar ?x ?z ?y
WHERE {
?newVar course:termName ?x.
?newVar ?s ?t.
?s ?d ?z.
?t course:termName ?y.
FILTER (regex(?z,"[^a-z]","i") && isLiteral(?z) )
}"""
,initNs=dict(course=Namespace.....
If you explain a bit more what your query does and how your data looks like then we might be able to help better.
Edited
Only change that yo might want to do is to formulate the SPARQL query without repeating the variable, something like ...
q = """SELECT ?x ?z ?y
WHERE {
course:%s course:termName ?x;
?s ?t.
?s ?d ?z.
?t course:termName ?y.
FILTER (regex(?z,'[^a-z0-9]','i') && isLiteral(?z) )
}ORDER BY ASC(?s)
"""%var_value
Notice the ;
at the end of the first triple pattern. I do not really understand the ?s ?d ?z
pattern, I need to see some sample data. I suspect that you are trying to achieve too much with this query. If your dataset is big this query is going to be very slow. I cannot say more than this without seeing the data.
来源:https://stackoverflow.com/questions/8422401/sparql-parameterized-queries