View
214
Download
1
Embed Size (px)
Citation preview
Conjunctive Queries, Datalog,and Recursion
Zachary G. IvesUniversity of Pennsylvania
CIS 550 – Database & Information Systems
October 23, 2003
Some slide content courtesy of Susan Davidson, Dan Suciu, & Raghu Ramakrishnan
2
Administrivia/Reminders
Reviews for Shanmugasundaram et al. and the TSIMMIS paper will be due via email on Tuesday 10/21, before class(The Levy paper doesn’t need a review)
Your 1-2 page project plan will be due a week from today, 10/30
Midterm and HW4 will be returned Tuesday
3
Reasoning about Queries and Views
Views are incredibly powerful formalisms for describing how data relates: fn: rel … rel rel We can exploit them in many different ways…
But we need an elegant way of describing views (let’s assume a relational model for now) Should be declarative Should be less complex than SQL Doesn’t need to support all of SQL – aggregation,
for instance, may be more than we need
4
Let’s Go Back a Few Weeks…Domain Relational Calculus
Queries have form:
{<x1,x2, …, xn>| p }
Predicate: boolean expression over x1,x2, …, xn We have the following operations:
<xi,xj,…> R xi op xj xi op const const op xi
xi. p xj. p pq, pq p, pqwhere op is , , , , , and
xi,xj,… are domain variables; p,q are predicates Recall that this captures the same
expressiveness as the relational algebra
domain variables predicate
5
A Similar Logic-Based Language:Datalog
Borrows the flavor of the relational calculus but is a “real” query language Based on the Prolog logic-programming language A “datalog program” will be a series of if-then rules
(Horn rules) that define relations from predicates
Rules are generally of the form:Rout(T1) R1(T2), R2(T3), …, c(T2 [ … Tn)
where Rout is the relation representing the query result, Ri are predicates representing relations, c is an expression using arithmetic/boolean predicates
over vars, and Ti are tuples of variables
6
Datalog Terminology
An example datalog rule:idb(x,y) r1(x,z), r2(z,y), z < 10
Irrelevant variables can be replaced by _ (anonymous var)
Extensional relations or database schemas (edbs) are relations only occurring in rules’ bodies – these are base relations with “ground facts”
Intensional relations (idbs) appear in the heads – these are basically views
Distinguished variables are the ones output in the head
Ground facts only have constants, e.g., r1(“abc”, 123)
head subgoals
body
7
Datalog in Action
As in DRC, the output (head) consists of a tuple for each possible assignment of variables that satisfies the predicate We typically avoid “8” in Datalog queries:
variables in the body are existential, ranging over all possible values
Multiple rules with the same relation in the head represent a union
We often try to avoid disjunction (“Ç”) within rules Let’s see some examples of datalog queries
(which consist of 1 or more rules): Given Professor(fid, name), Teaches(fid, serno, sem),
Courses(serno, cid, desc), Student(sid, name) Return course names other than CIS 550 Return the names of the teachers of CIS 550 Return the names of all people (professors or students)
8
Datalog is Relationally Complete
We can map RA Datalog: Selection p: p becomes a datalog subgoal
Projection A: we drop projected-out variables from head Cross-product r s: q(A,B,C,D) r(A,B),s(C,D) Join r ⋈ s: q(A,B,C,D) r(A,B),s(C,D), condition Union r U s: q(A,B) r(A,B) ; q(C, D) :- s(C,D) Difference r – s: q(A,B) r(A,B), : s(A,B)
(If you think about it, DRC Datalog is even easier)
Great… But then why do we care about Datalog?
9
A Query We Can’tAnswer in RA/TRC/DRC…
Recall our example of a binary relation for graphs or trees (similar to an XML Edge relation):
edge(from, to)
If we want to know what nodes are reachable:
reachable(F, T) :- edge(F, T) distance 1reachable(F, T) :- edge(F, X), edge(X, T) dist. 2reachable(F, T) :- edge(F, X), dist2(X, T) dist. 3
But how about all reachable paths? (Note this was easy in XPath over an XML representation -- //edge)
(another way of writing )
10
Recursive Datalog Queries
Define a recursive query in datalog:reachable(F, T) :- edge(F, T) distance 1
reachable(F, T) :- edge(F, X), reachable(X, T)distance >1
What does this mean, exactly, in terms of logic? There are actually three different (equivalent)
definitions of semantics All make a “closed-world” assumption: facts should
exist only if they can be proven true from the input – i.e., assume the DB contains all of the truths out there!
11
Fixpoint Semantics
One of the three Datalog models is based on a notion of fixpoint: We start with an instance of data, then derive
all immediate consequences We repeat as long as we derive new facts
In the RA, this requires a while loop! However, that is too powerful and needs to be
restricted Special case: “inflationary semantics”
(which terminates in time polynomial in the size of the database!)
12
Our Query in RA + while(inflationary semantics, no negation)
Datalog:reachable(F, T) :- edge(F, T)reachable(F, T) :- edge(F, X), reachable(X, T)
RA procedure with while:reachable += edgewhile change {
reachable += F, T(T ! X(edge) ⋈ F ! X(reachable))
}
13
Negation in Datalog
Datalog allows for negation in rules It’s essential for capturing RA set difference-
style ops:Professor(_, name), NOT Student(_, name)
But negation can be tricky… … You may recall that in the DRC, we had a
notion of “unsafe” queries, and they return here…
Single(X) Person(X), NOT Married(X,Y)
14
Safe Rules/Queries
Range restriction, which requires that every variable: occurs at least once in a positive relational
predicate in the body, or it’s constrained to equal a finite set of
values by arithmetic predicatesUnsafe:q(X) r(Y)q(X) : r(X,X)q(X) r(X) Ç t(Y)
Safe:q(X) r(X,Y)q(X) X = 5 q(X) : r(X,X), s(X)q(X) r(X) Ç (t(Y),u(X,Y))
15
Negation and Recursion
Unfortunately, the fixpoint semantics we mentioned previously for recursion “breaks” with negation… q(x) \neg q(x) No fixpoint!
p(x) \neg q(x) Multiple minimal fixpoints!q(x) \neg p(x)
Or the fixpoint may not “converge” (or converge to a minimal fixpoint)
This is all bad news…
16
One Way to Fix Things: Stratified Semantics
Start with semipositive datalog: negation only over edb predicates From here, we can compute a set of values for
the idb predicates that depend on the edb’s
Now we can “materialize” the results of the first set of idbs; we’ll remove their rules and treat them as edbs to compute a next “stratum”
r (1,1)r (1,2)s (1,1)v1(x,y) :- r(x,y), : s(x,y)q(x,y) :- v1(x,y), : s(x,y)
r (1,1)r (1,2)s (1,1)v1 (1,2)q(x,y) :- v1(x,y), : s(x,y)
r (1,1)r (1,2)s (1,1)v1 (1,2)q (1,2)
17
Precedence Graphs
Take a set of datalog rules, create a node for each relation (edb or idb) If r r’ then add an edge labeled “+” from r
to r’ If r : r’ then add an edge labeled “-” from r
to r’ We can stratify if there are no cycles with “-”
edgesv1(x,y) :- r(x,y), : s(x,y)q(x,y) :- v1(x,y), : s(x,y)
sr
v1 q-
+
+
18
Stratifying Datalog Execution
foreach predicate p, set stratum(p) = 1do until no change, or some stratum > # of predicates
foreach rule h b {foreach negated subgoal of b with predicate q {stratum(p) = max(stratum(p), 1+stratum(q))}foreach positive subgoal of b with predicate q {stratum(p) = max(stratum(p), stratum(q)}
}
19
Conjunctive Queries
A single Datalog rule with no “Ç,” “:,” “8” can express select, project, and join – a conjunctive query
Conjunctive queries are possible to reason about statically (Note that we can write CQ’s in other languages, e.g., SQL!)
We know how to “minimize” conjunctive queriesAn important simplification that can’t be done for general SQL
We can test whether one conjunctive query’s answers always contain another conjunctive query’s answers (for ANY instance)
Why might this be useful?
20
Example of Containment
Suppose we have two queries:
q1(S,C) :- Student(S, N), Takes(S, C), Course(C, X), inCSE(C),
Course(C, “DB & Info Systems”)
q2(S,C) :- Student(S, N), Takes(S, C), Course(C, X)
Intuitively, q1 must contain the same or fewer answers vs. q2: It has all of the same conditions, except one extra conjunction
(i.e., it’s more restricted) There’s no union or any other way it can add more data
We can say that q2 contains q1 because this holds for any instance of our DB {Student, Takes, Course}
21
Checking Containment via Canonical DBs
To test for q1 µ q2: Create a “canonical DB” that contains a tuple for
each subgoal in q1 Execute q2 over it If q2 returns a tuple that matches the head of q1,
then q1 µ q2
(This is an NP-complete algorithm in the size of the query. Testing for full first-order logic queries is undecidable!!!)
Let’s see this for our example…
22
Example Canonical DB
q1(S,C) :- Student(S, N), Takes(S, C), Course(C, X), inCSE(C), Course(C, “DB & Info Systems”)
q2(S,C) :- Student(S, N), Takes(S, C), Course(C, X)
Student Takes Course inCSE
S N S C C X
C DB & Info
Systems
S
Need to get tuple <S,C> in executing q2 over this database
23
Wrapping up for the Week…
We’ve seen a new language, Datalog It’s basically a glorified DRC with a special feature,
recursion It’s much cleaner than SQL for reasoning about … But negation (as in the DRC) poses some
challenges
We’ve seen that a particular kind of query, the conjunctive query, is written naturally in Datalog Conjunctive queries are possible to reason about We saw an example of testing for containment Next time we’ll see some further examples