问题
I am having difficulty making the following SPARQL query parametric.
First I load the request library:
?- use_module(library(semweb/sparql_client)).
% library(uri) compiled into uri 0.02 sec, 290,256 bytes
% library(readutil) compiled into read_util 0.00 sec, 17,464 bytes
% library(socket) compiled into socket 0.00 sec, 11,936 bytes
% library(option) compiled into swi_option 0.00 sec, 14,288 bytes
% library(base64) compiled into base64 0.00 sec, 17,912 bytes
% library(debug) compiled into prolog_debug 0.00 sec, 21,864 bytes
% library(http/http_open) compiled into http_open 0.03 sec, 438,368 bytes
% library(sgml) compiled into sgml 0.00 sec, 39,480 bytes
% library(quintus) compiled into quintus 0.00 sec, 23,896 bytes
% rewrite compiled into rewrite 0.01 sec, 35,336 bytes
% library(record) compiled into record 0.00 sec, 31,368 bytes
% rdf_parser compiled into rdf_parser 0.01 sec, 132,840 bytes
% library(gensym) compiled into gensym 0.00 sec, 4,792 bytes
% rdf_triple compiled into rdf_triple 0.00 sec, 39,672 bytes
% library(rdf) compiled into rdf 0.01 sec, 244,240 bytes
% library(semweb/sparql_client) compiled into sparql_client 0.04 sec, 707,080 bytes
true.
I have this query that, as you can see, seems work well:
?- sparql_query('select COUNT(*) where {?place a dbpedia-owl:Place ; rdfs:label "Pescara"@it.}', Row, [ host('dbpedia.org'), path('/sparql/')]).
Row = row(literal(type('http://www.w3.org/2001/XMLSchema#integer', '1'))).
My problem is that I want this query to be parametric. In the previous example I have a Pescara
value is fixed and should be a variable. I have something like:
?- Place = 'Roma'
and in the query:
?- sparql_query('select COUNT(*) where {?place a dbpedia-owl:Place ; rdfs:label $Place@it.}', Row, [ host('dbpedia.org'), path('/sparql/')]).
This doesn't seem to work.
回答1:
You can use atom_concat/3 and atomic_list_concat/3.
:- val('select COUNT(*) where {?place a dbpedia-owl:Place ; rdfs:label $Place@it.}').
12 ?- Z='rdfs:label $', val(X), atom_concat(A,B,X), atom_concat(Z,C,B),
atom_concat('Place',D,C), Place='"Roma"',
atomic_list_concat([A,Z,Place,D],R).
.....
Place = '"Roma"',
R = 'select COUNT(*) where {?place a dbpedia-owl:Place ; rdfs:label $"Roma"@it.}' ;
false.
and then
?- sparql_query($R, Row, [ host('dbpedia.org'), path('/sparql/')]).
Or, simply,
makeQuery(Place, Query, Row) :- %% e.g. Place = '"Rome"'
atomic_list_concat( [ 'select COUNT(*) where {?place a dbpedia-owl:Place ;',
' rdfs:label $', Place, '@it.}'], Query),
sparql_query(Query, Row, [ host('dbpedia.org'), path('/sparql/')] ).
来源:https://stackoverflow.com/questions/16820606/how-to-parameterize-a-sparql-query-in-swi-prolog