Esempio n. 1
0
 def sesame_is_sparql_test(self):
     url = 'http://dbpedia.org/sparql'
     g1 = SesameGraph(url)
     g2 = SPARQLGraph(url)        
     q1 = "select distinct ?Concept where {[] a ?Concept} LIMIT 10"
     r1 = set(list(g1.query(q1,resultMethod='xml')))
     r2 = set(list(g2.query(q1,resultMethod='xml')))        
     assert r1==r2
Esempio n. 2
0
 def initBindings_test1(self):
     query = 'select * where {?s ?P ?oo.?ss ?p \n?oo}'
     initBindings = dict(oo=URIRef("OHO"), P=Decimal("4.40"))
     processed = SPARQLGraph._processInitBindings(query, initBindings)
     assert processed == \
         'select * where {?s "4.40"^^' + \
         '<http://www.w3.org/2001/XMLSchema#decimal> <OHO>.?ss ?p \n<OHO>}'
Esempio n. 3
0
def find_relationships(person1, person2):
    graph = SPARQLGraph('http://dbpedia.org/sparql')
    query = '''
        PREFIX dcterms: <http://purl.org/dc/terms/>
        PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
        SELECT DISTINCT ?p ?o WHERE {
            <%s> ?p ?o .
            <%s> ?p ?o .
            FILTER (?p != <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> && ?p != <http://dbpedia.org/property/wikiPageUsesTemplate> && ?p != <http://dbpedia.org/property/wordnet_type> )
        }
    '''
    query = query % (person1, person2)
    relationships = []
    for r in graph.query(query, resultMethod='json'):
        relationships.append((str(r[0]), str(r[1])))
    return relationships
Esempio n. 4
0
def main(url=None):

    try:
        output = ""

        try:
            opts, args = optparser.parse_args()
        except LookupError:
            optparser.print_help()

        if len(args) < 1:
            Usage(
                'you must give at filename to read' +
                ' the query from..."-" signials stdin')
        elif len(args) > 2:
            Usage('too many args')

        fname = args[-1]
        if fname == '-':
            stream = sys.stdin
        else:
            stream = file(fname)

        query = stream.read()

        # output = opt.get.fileOut or sys.stdout
        if not opts.url:
            try:
                url = re.search(
                    r'(?:^|\n) *# *--url=([^ \s\n]+)', query).groups()[0]
            except:
                raise ValueError("Need a url for the endpoint")
        else:
            url = opts.url
        if not opts.fout:
            output = sys.stdout
        else:
            output = open(opts.fout, "w")

        result = SPARQLGraph(url).query(
            query, resultMethod=opts.format, rawResults=True)
        print >>output, result.read()

    except Usage, err:
        print >> sys.stderr, sys.argv[0].split("/")[-1] + ": " + str(err.msg)
        print >> sys.stderr, "\t for help use --help"
        return 2
Esempio n. 5
0
    def find_related(self):
        """Find related Linked Data.

        Returns:
            A list of the URIs of the related Linked Data.
        """
        related_concepts = []
        if not self._is_dbpedia_uri():
            return related_concepts
        graph = SPARQLGraph('http://dbpedia.org/sparql')
#         query = '''
#                 PREFIX dcterms: <http://purl.org/dc/terms/>
#                 PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
#                 SELECT DISTINCT ?c WHERE {
#                     {
#                         <%s> dcterms:subject ?cat .
#                         ?c dcterms:subject ?cat .
#                     } UNION {
#                         <%s> dcterms:subject ?cat .
#                         ?n_cat skos:broader ?cat .
#                         ?c dcterms:subject ?n_cat .
#                     } UNION {
#                         <%s> dcterms:subject ?cat .
#                         ?cat skos:broader ?n_cat .
#                         ?c dcterms:subject ?n_cat .
#                     }
#                 }'''
#         query = query % (self.uri, self.uri, self.uri)
        query = '''
                PREFIX dcterms: <http://purl.org/dc/terms/>
                PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
                SELECT DISTINCT ?c WHERE {
                    {
                        <%s> dcterms:subject ?cat .
                        ?c dcterms:subject ?cat .
                    }
                }'''
        query = query % self.uri
#         i = 0
        for r in graph.query(query, resultMethod='json'):
#             if i > 10:
#                 break
            if str(r[0]) != self.uri:
                related_concepts.append(str(r[0]))
#                 i += 1
        return related_concepts
Esempio n. 6
0
def find_persons_share_prop(person, preidicate, value):
    graph = SPARQLGraph('http://dbpedia.org/sparql')
    query = '''
        PREFIX dcterms: <http://purl.org/dc/terms/>
        PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
        PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
        SELECT DISTINCT ?other_person WHERE {
            <%s> <%s> %s .
            ?other_person a <http://dbpedia.org/ontology/Person> ;
                <%s> %s .
        }
    '''
    query = query % (person, preidicate, value, preidicate, value)
    relationships = []
    for r in graph.query(query, resultMethod='json'):
        relationships.append(str(r[0]))
    return relationships
Esempio n. 7
0
def main(url=None):

    try:
        output = ""

        try:
            opts, args = optparser.parse_args()
        except LookupError:
            optparser.print_help()

        if len(args) < 1:
            Usage('you must give at filename to read the query from..."-" signials stdin')
        elif len(args) > 2:
            Usage("too many args")

        fname = args[-1]
        if fname == "-":
            stream = sys.stdin
        else:
            stream = file(fname)

        query = stream.read()

        # output = opt.get.fileOut or sys.stdout
        if not opts.url:
            try:
                url = re.search(r"(?:^|\n) *# *--url=([^ \s\n]+)", query).groups()[0]
            except:
                raise ValueError, "Need a url for the endpoint"
        else:
            url = opts.url
        if not opts.fout:
            output = sys.stdout
        else:
            output = open(fout, "w")

        result = SPARQLGraph(url).query(query, resultMethod=opts.format, rawResults=True)
        print >> output, result.read()

    except Usage, err:
        print >>sys.stderr, sys.argv[0].split("/")[-1] + ": " + str(err.msg)
        print >>sys.stderr, "\t for help use --help"
        return 2
Esempio n. 8
0
def find_related_persons(person_uri):
    graph = SPARQLGraph('http://dbpedia.org/sparql')
    query = '''
        PREFIX dcterms: <http://purl.org/dc/terms/>
        PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
        SELECT DISTINCT ?other_person ?o WHERE {
            <%s> dcterms:subject ?o .
            ?other_person a <http://dbpedia.org/ontology/Person> ;
                dcterms:subject ?o .
        } LIMIT 1000
    '''
    # query = '''
    #     PREFIX dcterms: <http://purl.org/dc/terms/>
    #     PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
    #     SELECT DISTINCT ?other_person ?p WHERE {
    #         <%s> ?p ?other_person.
    #         ?other_person a <http://dbpedia.org/ontology/Person> .
    #     }
    # '''
    query = query % person_uri
    related_concepts = []
    for r in graph.query(query, resultMethod='json'):
        related_concepts.append((str(r[0]), str(r[1])))
    return related_concepts
Esempio n. 9
0
def create_engine(url='', identifier="", create=False):
    """
    :returns: returns an opened rdflib ConjunctiveGraph

    :param url: a string of the url
    :param identifier: URIRef of the default context for writing e.g.:

      - create_engine('sleepycat://~/working/rdf_db')
      - create_engine('kyotocabinet://~/working/rdf_db')
      - create_engine('zodb:///var/rdflib/Data.fs')
      - create_engine('zodb://*****:*****@localhost/rdflibdb')
      - create_engine('sqlalchemy+postgresql://myname@localhost/rdflibdb')

    etc.

    """
    if url == '' or url.startswith('IOMemory'):
        from rdflib import ConjunctiveGraph
        db = ConjunctiveGraph('IOMemory')

    elif url.lower().startswith('sleepycat://'):
        from rdflib import ConjunctiveGraph
        db = ConjunctiveGraph('Sleepycat', identifier=identifier)
        openstr = os.path.abspath(os.path.expanduser(url[12:]))
        db.open(openstr, create=create)

    elif url.lower().startswith('kyotocabinet://'):
        from rdflib import ConjunctiveGraph
        db = ConjunctiveGraph('Kyotocabinet', identifier=identifier)
        openstr = os.path.abspath(os.path.expanduser(url[15:]))
        db.open(openstr, create=create)

    elif url.lower().startswith('sqlalchemy+'):
        from rdflib import ConjunctiveGraph
        db = ConjunctiveGraph('SQLAlchemy', identifier=identifier)
        db.open(url[11:], create=create)

    elif url.lower().startswith('zodb://'):
        import ZODB
        # import transaction
        from rdflib import ConjunctiveGraph
        db = ConjunctiveGraph('ZODB')
        if url.endswith('.fs'):
            from ZODB.FileStorage import FileStorage
            openstr = os.path.abspath(os.path.expanduser(url[7:]))
            if not os.path.exists(openstr) and not create:
                raise "File not found: %s"
            fs = FileStorage(openstr)
        else:
            from ZEO.ClientStorage import ClientStorage
            schema, opts = _parse_rfc1738_args(url)
            fs = ClientStorage((opts['host'], int(opts['port'])))
        # get the Zope Database
        zdb = ZODB.DB(fs)
        # open it
        conn = zdb.open()
        #get the root
        root = conn.root()
        # get the Conjunctive Graph
        if 'rdflib' not in root and create:
            root['rdflib'] = ConjunctiveGraph('ZODB')
        db = root['rdflib']

    elif url.lower().startswith('sesame://'):
        from rdfalchemy.sparql.sesame2 import SesameGraph
        db = SesameGraph("http://" + url[9:])

    elif url.lower().startswith('sparql://'):
        from rdfalchemy.sparql import SPARQLGraph
        db = SPARQLGraph("http://" + url[9:])

    else:
        raise "Could not parse  string '%s'" % url
    return db
Esempio n. 10
0
from rdfalchemy.sparql import SPARQLGraph

url = 'http://bel-epa.com:8080/joseki/ukpp'
g = SPARQLGraph(url)

q1 = "select ?s ?p ?o where {?s ?p ?o} LIMIT 10"

responses = {}
x = set(list(g.query(q1, resultMethod='xml')))
j = set(list(g.query(q1, resultMethod='json')))

print(len(x))


def sizes_test():
    assert len(x) == len(j)


def eq_jx_test():
    assert j == x