def _remove_tp_filters(self, tp): """ Transforms a triple pattern that may contain filters to a new one with both subject and object bounded to variables :param tp: The triple pattern to be filtered :return: Filtered triple pattern """ def __create_var(elm, predicate): if elm in self._filter_mapping.values(): elm = list(filter(lambda x: self._filter_mapping[x] == elm, self._filter_mapping)).pop() elif predicate(elm): v = '?{}'.format(uuid()) self._filter_mapping[v] = elm elm = v return elm s, p, o = tp_parts(tp) s = __create_var(s, lambda x: '<' in x and '>' in x) o = __create_var(o, lambda x: '"' in x or ('<' in x and '>' in x)) return '{} {} {}'.format(s, p, o)
def _query(fid, gp): """ Query the fragment using the original request graph pattern :param gp: :param fid: :return: The query result """ def __build_query_from(x, depth=0): def build_pattern_query((u, v, data)): return '\nOPTIONAL { %s %s %s %s }' % (u, data['predicate'], v, __build_query_from(v, depth + 1)) out_edges = list(gp_graph.out_edges_iter(x, data=True)) out_edges = reversed(sorted(out_edges, key=lambda x: gp_graph.out_degree)) if out_edges: return ' '.join([build_pattern_query(x) for x in out_edges]) return '' gp_parts = [tp_parts(tp) for tp in gp] blocks = [] gp_graph = nx.DiGraph() for gp_part in gp_parts: gp_graph.add_edge(gp_part[0], gp_part[2], predicate=gp_part[1]) roots = filter(lambda x: gp_graph.in_degree(x) == 0, gp_graph.nodes()) blocks += ['%s a stoa:Root\nOPTIONAL { %s }' % (root, __build_query_from(root)) for root in roots] where_gp = ' .\n'.join(blocks) q = """SELECT DISTINCT * WHERE { %s }""" % where_gp result = [] try: log.info('Querying fragment {}:\n{}'.format(fid, q)) result = fragment_graph(fid).query(q) except Exception as e: # ParseException from query traceback.print_exc() log.warning(e.message) return result
def graph_from_gp(gp): gp_graph = nx.DiGraph() gp_parts = [tp_parts(tp) for tp in gp] for gp_part in gp_parts: gp_graph.add_edge(gp_part[0], gp_part[2], predicate=gp_part[1]) return gp_graph