我是SPARQL和Fuseki的新手。我用
设置了Fuseki Serverfuseki-server --update --mem /address_act
创建数据集。
我有一个包含许多三元组的图表,然后我想通过SPARQLUPDATE将这些三元组添加到数据集中。以下是将三元组放入图形并尝试通过Fuseki Server将其保存到数据集的代码:
import requests
import rdflib
import re
from rdflib import ConjunctiveGraph, Graph, Literal, URIRef
from rdflib.plugins.stores import sparqlstore
query_endpoint = 'http://localhost:3030/address_act/query'
update_endpoint = 'http://localhost:3030/address_act/update'
store = sparqlstore.SPARQLUpdateStore()
store.open((update_endpoint, update_endpoint))
default_graph = URIRef('http://example.org/default-graph')
ng = Graph(store, identifier=default_graph)
g = Graph()
g1 = Graph()
for i in range(1,2):
url = 'http://gnafld.net/address/?per_page=3&page=' + str(i)
g.parse(url)
page = g.query("""SELECT ?subject
WHERE {
?subject a <http://gnafld.net/def/gnaf#Address>.
}""")
for row in page:
ad_info = requests.get(row.subject).content
g1.parse(data=ad_info, format='turtle')
#print('The number of triples in Graph: {}'.format(len(g1)))
ng.update(
u'INSERT DATA { %s }' % g1.serialize(format='turtle')
)
此外,我还有另一种方法可以使用SPARQLWrapper:
import requests
import rdflib
import re
from rdflib import ConjunctiveGraph, Graph, Literal, URIRef
from rdflib.plugins.stores import sparqlstore
from SPARQLWrapper import SPARQLWrapper
query_endpoint = 'http://localhost:3030/address_act/query'
update_endpoint = 'http://localhost:3030/address_act/update'
store = sparqlstore.SPARQLUpdateStore()
store.open((update_endpoint, update_endpoint))
default_graph = URIRef('http://example.org/default-graph')
g = Graph()
g1 = Graph(identifier=default_graph)
for i in range(1,2):
url = 'http://gnafld.net/address/?per_page=3&page=' + str(i)
g.parse(url)
page = g.query("""SELECT ?subject
WHERE {
?subject a <http://gnafld.net/def/gnaf#Address>.
}""")
for row in page:
ad_info = requests.get(row.subject).content
g1.parse(data=ad_info, format='turtle')
#print('The number of triples in Graph: {}'.format(len(g1)))
for s,p,o in g1:
queryStringUpload = 'INSERT DATA {GRAPH <http://example.org/default-graph> {%s %s %s}}' %(s,p,o)
sparql = SPARQLWrapper('http://localhost:3030/address_act/update')
sparql.setQuery(queryStringUpload)
sparql.method = 'POST'
sparql.query()
当我运行上面的两个时,程序中的最后一句ng.update(u'INSERT DATA { %s }' % g1.serialize(format='turtle'))
和sparql.query()
会导致错误。我确信这些三元组已存在于图表中,但是当更新时,两者都会给出错误:
QueryBadFormed: QueryBadFormed: a bad request has been sent to the endpoint, probably the sparql query is bad formed.
Response:
b'Error 400: Lexical error at line 11, column 59. Encountered: "\\\'" (39), after : "b"\n\n\nFuseki - version 3.7.0 (Build date: 2018-04-05T11:04:59+0000)\n'
和错误如:
QueryBadFormed: QueryBadFormed: a bad request has been sent to the endpoint, probably the sparql query is bad formed.
Response:
b'Error 400: Line 1, column 56: Unresolved prefixed name: http:\n\n\nFuseki - version 3.7.0 (Build date: 2018-04-05T11:04:59+0000)\n'
似乎SPARQL更新操作不起作用。有没有语法错误,以至于无法插入三元组?不知道怎么解决这个问题?感谢任何努力。