简体   繁体   中英

ASK SPARQL queries in rdflib

I'm trying to learn SPARQL and I'm using python's rdflib to train. I've done a few tries, but any ASK query always seems to give me back a True result. For instance, i tried the following:

#!/usr/bin/python
# -*- coding: utf-8 -*-
import rdflib
mygraph=rdflib.Graph();
mygraph.parse('try.ttl',format='n3');
results=mygraph.query("""
ASK {?p1 a <http://false.com>}
 """)
print bool(results)

The result is true, even if there is no subject of type false.com in 'try.ttl'. Can anyone explain me why? Thank you in advance for your help!

UPDATE: Reading the rdflib manual, I found out that results is of type list and (in my case) should contain a single boolean with the return value from the ask query. I tried the following: for x in results: print x And I got "None". I'm guessing I don't use the query method in the right way.

The documentation doesn't actually says that it's of type list, but that you can iterate over it, or you can convert it to a boolean:

If the type is "ASK", iterating will yield a single bool (or bool(result) will return the same bool)

This means that print bool(results) , as you've done, should work. In fact, your code does work for me:

$ touch try.ttl
$ cat try.ttl # it's empty
$ cat test.py # same code
#!/usr/bin/python
# -*- coding: utf-8 -*-
import rdflib
mygraph=rdflib.Graph();
mygraph.parse('try.ttl',format='n3');
results=mygraph.query("""
ASK {?p1 a <http://false.com>}
 """)
print bool(results)
$ ./test.py # the data is empty, so there's no match
False

If we add some data to the file that would make the query return true, we get true:

$ cat > try.ttl 
<http://example.org> a <http://false.com> .
$ cat try.ttl 
<http://example.org> a <http://false.com> .
$ ./test.py 
True

Maybe you're using an older version of the library? Or a newer version and a bug was introduced? I'm using 4.0.1:

$ python
Python 2.7.3 (default, Feb 27 2014, 19:58:35) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg_resources
>>> pkg_resources.get_distribution("rdflib").version
'4.0.1'

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