sparql_loader.py 1.88 KB
Newer Older
ina's avatar
ina committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
from typing import List, Tuple

from SPARQLWrapper import JSON, SPARQLWrapper

from graphs import KG


class SPARQLLoader(KG):
    """Represents a Knowledge Graph from a SPARQL endpoint."""

    def __init__(self, location):
        self.location = location
        self.endpoint = SPARQLWrapper(self.location)

    def get_hops(self, vertex: str) -> List[Tuple[str, str]]:
        """Returns a hop (vertex -> predicate -> object)

        Args:
            vertex: The name of the vertex to get the hops.

        Returns:
            The hops of a vertex in a (predicate, object) form.

        """
        if not vertex.startswith("http://"):
            return []

        query = (
            """
            SELECT ?p ?o WHERE {
                <"""
            + vertex
            + """> ?p ?o .
            }
        """
        )
        self.endpoint.setQuery(query)
        self.endpoint.setReturnFormat(JSON)
        results = self.endpoint.query().convert()
        return [
            (result["p"]["value"], result["o"]["value"])
            for result in results["results"]["bindings"]
        ]


    def get_sub_pred(self, vertex: str) -> List[Tuple[str, str]]:
        """Returns a hop (subject -> predicate -> vertex)

        Args:
            vertex: The name of the vertex to get the hops.

        Returns:
            The hops of a vertex in a (subject, predicate) form.

        """
        if not vertex.startswith("http://"):
            return []

        query = (
            """
            SELECT ?s ?p WHERE {
                ?s ?p <"""
            + vertex
            + """>  .
            }
        """
        )
        self.endpoint.setQuery(query)
        self.endpoint.setReturnFormat(JSON)
        results = self.endpoint.query().convert()
        return [
            (result["s"]["value"], result["p"]["value"])
            for result in results["results"]["bindings"]
        ]