Exemplo n.º 1
0
    def is_subclass(self, qid_1, qid_2):

        if qid_1 == qid_2:
            return True

        # Reply from cache if possible.
        cache_key = self.cache_key(qid_1, qid_2)
        if cache_key in self.cache:
            return self.cache[cache_key]

        # Prepare the query.
        query = """
        PREFIX wd: <http://www.wikidata.org/entity/>
        PREFIX wdt: <http://www.wikidata.org/prop/direct/>

        SELECT ( COUNT( 1 ) AS ?count ) WHERE {
            wd:%s wdt:%s* wd:%s  .
        }
        """ % (qid_1, self.subclass_pid, qid_2)

        # Run the query.
        results = sparql_wikidata(query)

        # Cache the result.
        retval = '1' == results['bindings'][0]['count']['value']
        self.cache[cache_key] = retval

        return retval
    def build_cache(self, subclass_qid):

        # Stop building the cache if we reached the needle.
        if subclass_qid in self.cache.keys():
            return

        # Set the initial set.
        self.cache[subclass_qid] = set()

        # Prepare the query.
        query = """
        PREFIX wd: <http://www.wikidata.org/entity/>
        PREFIX wdt: <http://www.wikidata.org/prop/direct/>

        SELECT ?parent WHERE {
            wd:%s wdt:%s ?parent  .
        }
        """ % (subclass_qid, self.subclass_pid)

        # Run the query.
        results = sparql_wikidata(query)

        for result in results["bindings"]:
            q = to_q(result["parent"]["value"])
            self.cache[subclass_qid].add(q)
Exemplo n.º 3
0
    def prefetch_children(self, qid, force=False):
        """
        Prefetches (in Redis) all the children of a given class
        """

        if qid in self.sets:
            return  # children are already prefetched

        sparql_query = """
        PREFIX wd: <http://www.wikidata.org/entity/>
        PREFIX wdt: <http://www.wikidata.org/prop/direct/>
        SELECT ?child WHERE { ?child wdt:%s* wd:%s
            . FILTER( strstarts( str( ?child ), 'http://www.wikidata.org/entity/Q' ) )
        }
        """ % (self.subclass_pid, qid)
        results = sparql_wikidata(sparql_query)

        new_set = set()
        for result in results["bindings"]:
            child_qid = to_q(result["child"]["value"])
            if child_qid:  # this can fail if the entity is a property, lexeme…
                new_set.add(int(child_qid[1:]))

        self.sets[qid] = new_set
Exemplo n.º 4
0
 def __enter__(self):
     self.query_results = sparql_wikidata(
         self.query, endpoint=self.endpoint)['bindings']
     return self