Conjunctive Queries Datalog and Recursion Zachary G Ives

  • Slides: 23
Download presentation
Conjunctive Queries, Datalog, and Recursion Zachary G. Ives University of Pennsylvania CIS 550 –

Conjunctive Queries, Datalog, and Recursion Zachary G. Ives University of Pennsylvania CIS 550 – Database & Information Systems October 23, 2003 Some slide content courtesy of Susan Davidson, Dan Suciu, & Raghu Ramakrishnan

Administrivia /Reminders § Reviews for Shanmugasundaram et al. and the TSIMMIS paper will be

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 HW 4 will be returned Tuesday 2

Reasoning about Queries and Views § Views are incredibly powerful formalisms for describing how

Reasoning about Queries and Views § Views are incredibly powerful formalisms for describing how data relates: fn: 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 3

Let’s Go Back a Few Weeks… Domain Relational Calculus Queries have form: domain variables

Let’s Go Back a Few Weeks… Domain Relational Calculus Queries have form: domain variables {<x 1, x 2, …, xn>| p } predicate Predicate: boolean expression over x 1, x 2, …, xn § We have the following operations: <xi, xj, …> R xi op xj xi op const op xi xi. p xj. p p q, p q p, p q where op is , , , and xi, xj, … are domain variables; p, q are predicates § Recall that this captures the same expressiveness as the relational algebra 4

A Similar Logic-Based Language: Datalog Borrows the flavor of the relational calculus but is

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(T 1) R 1(T 2), R 2(T 3), …, c(T 2 [ … 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 5

Datalog. Terminology § An example datalog rule: body idb(x, y) r 1(x, z), r

Datalog. Terminology § An example datalog rule: body idb(x, y) r 1(x, z), r 2(z, y), z < 10 head subgoals § 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. , r 1(“abc”, 123) 6

Datalogin Action § As in DRC, the output (head) consists of a tuple for

Datalogin 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) 7

Datalogis Relationally Complete § We can map RA Datalog: § § Selection p: p

Datalogis 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? 8

A Query We Can’t Answer in RA/TRC/DRC… Recall our example of a binary relation

A Query We Can’t Answer 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: (another way of writing ) reachable(F, T) : - edge(F, T) reachable(F, T) : - edge(F, X), edge(X, T) reachable(F, T) : - edge(F, X), dist 2(X, T) distance 1 dist. 2 dist. 3 But how about all reachable paths? (Note this was easy in XPath over an XML representation -- //edge) 9

Recursive. Datalog. Queries Define a recursive query in datalog: reachable(F, T) : - edge(F,

Recursive. Datalog. Queries Define a recursive query in datalog: reachable(F, T) : - edge(F, T) reachable(F, T) : - edge(F, X), reachable(X, T) distance 1 distance >1 What does this mean, exactly, in terms of logic? § There 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! 10

Fixpoint. Semantics One of the three Datalog models is based on a notion of

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!) 11

Our Query in RA + while (inflationary semantics, no negation) Datalog: reachable(F, T) :

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 += edge while change { reachable += F, T( T ! X(edge) ⋈ F ! X(reachable)) } 12

Negation in. Datalog allows for negation in rules § It’s essential for capturing RA

Negation in. 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) 13

Safe Rules/Queries Range restriction , which requires that every variable: § occurs at least

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 predicates Unsafe: 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)) 14

Negation and Recursion § Unfortunately, the fixpoint semantics we mentioned previously for recursion “breaks”

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) neg p(x) Multiple minimal fixpoints! § Or the fixpoint may not “converge” (or converge to a minimal fixpoint) § This is all bad news… 15

One Way to Fix Things: Stratified Semantics § Start with semipositive datalog: negation only

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) v 1(x, y) : - r(x, y), : s(x, y) q(x, y) : - v 1(x, y), : s(x, y) r (1, 1) r (1, 2) s (1, 1) v 1 (1, 2) q (1, 2) 16

Precedence Graphs § Take a set of datalog rules, create a node for each

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 “-” edges v 1(x, y) : - r(x, y), : s(x, y) q(x, y) : - v 1(x, y), : s(x, y) v 1 + r + q s 17

Stratifying. Datalog. Execution foreach predicate p, set stratum(p) = 1 do until no change,

Stratifying. Datalog. Execution foreach predicate p, set stratum(p) = 1 do 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) } } 18

Conjunctive Queries A single Datalog rule with no “Ç, ” “: , ” “

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 queries An 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? 19

Example of Containment Suppose we have two queries: q 1(S, C) : - Student(S,

Example of Containment Suppose we have two queries: q 1(S, C) : - Student(S, N), Takes(S, C), Course(C, X), in. CSE(C), Course(C, “DB & Info Systems”) q 2(S, C) : - Student(S, N), Takes(S, C), Course(C, X) Intuitively, q 1 must contain the same or fewer answers vs. q 2: § 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 q 2 contains q 1 because this holds for any instance of our DB {Student, Takes, Course} 20

Checking Containment via Canonical. DBs § To test for q 1 µ q 2:

Checking Containment via Canonical. DBs § To test for q 1 µ q 2: § Create a “canonical DB” that contains a tuple for each subgoal in q 1 § Execute q 2 over it § If q 2 returns a tuple that matches the head of q 1, then q 1 µ q 2 (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… 21

Example Canonical DB § q 1(S, C) : - Student(S, N), Takes(S, C), Course(C,

Example Canonical DB § q 1(S, C) : - Student(S, N), Takes(S, C), Course(C, X), in. CSE(C), Course(C, “DB & Info Systems”) § q 2(S, C) : - Student(S, N), Takes(S, C), Course(C, X) Student S N Takes S C Course C C X DB & Info Systems in. CSE S Need to get tuple <S, C> in executing q 2 over this database 22

Wrapping up for the Week… We’ve seen a new language, Datalog § It’s basically

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 23