Skip to content

Instantly share code, notes, and snippets.

@kasei
Last active August 29, 2015 14:25
Show Gist options
  • Save kasei/2ec4723304386be552e1 to your computer and use it in GitHub Desktop.
Save kasei/2ec4723304386be552e1 to your computer and use it in GitHub Desktop.
Attean tree rewriting
use v5.14;
use autodie;
use utf8;
use RDF::Query;
use Attean;
use Attean::TreeRewriter;
use AtteanX::RDFQueryTranslator;
my $sparql = <<"END";
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT *
WHERE {
?s a foaf:Person ;
foaf:name ?name ;
foaf:nick ?nick .
}
END
my $w = Attean::TreeRewriter->new();
$w->register_pre_handler(sub {
# Pull apart BGP triples and take all triples that use foaf:name or foaf:nick, and put them in a BGP by themselves
my ($a, $parent, $thunk) = @_;
if ($a->isa('Attean::Algebra::BGP')) {
my $triples = $a->triples;
my @recognized;
my @other;
foreach my $t (@$triples) {
# Categorize the triples as either recognized or non-recognized based on some condition
if ($t->predicate->value =~ m<^http://xmlns.com/foaf/0.1/(name|nick)$>) {
push(@recognized, $t);
} else {
push(@other, $t);
}
}
if (scalar(@recognized) and scalar(@other)) {
# If there are both recognized triples *and* other triples, rewrite the BGP as Join(BGP(recognized), BGP(other))
my $l = Attean::Algebra::BGP->new( triples => \@recognized );
my $r = Attean::Algebra::BGP->new( triples => \@other );
my $rewritten = Attean::Algebra::Join->new(children => [$l, $r]);
my $handled = 1; # Indicate that we are returning a rewritten algebra tree
my $descend = 0; # Indicate to the rewriting code that our rewritten algebra tree should NOT also be rewritten
return ($handled, $descend, $rewritten)
}
}
return (0, 1, $a);
});
my $query = RDF::Query->new($sparql);
my $t = AtteanX::RDFQueryTranslator->new();
my $a = $t->translate_query($query);
my ($changed, $rewritten) = $w->rewrite($a, {});
if ($changed) {
warn "Query was rewritten:\n";
warn $rewritten->as_sparql;
} else {
warn "Query was not rewritten.\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment