Lesson 10.1: Functions as views
Abstracting complex patterns
In Lesson 5.4, we learned how to define functions for TypeDB’s to capture subqueries and abstract away reusable ideas. In this lesson, we’ll learn how to design function that capture domain logic, in this case for the domain of an online bookstore. To begin with, let’s consider a piece of domain logic expressed in natural language.
A review is verified if: the review is for a book that has been previously bought by the user who made the review.
This could be easily translated into TypeQL, allowing us to query for reviews that are verified as follows.
match
rating ($review, $book);
order-line ($order, $book);
$_ isa action-execution ($user, $review), has timestamp $review-time;
$_ isa action-execution ($user, $order), has timestamp $order-time;
$review-time > $order-time;
fetch {
"review-id": $review.id,
};
Now let’s consider how we might apply this domain logic. Suppose we want to query for the average review score of each book, as we did in Lesson 8.2, except this time we only want to include verified reviews in the average.
match
$book isa book;
fetch {
"title": $book.title,
"average-verified-score": (
match
$review isa review, has score $score;
rating ($review, $book);
order-line ($order, $book);
$_ isa action-execution ($user, $review), has timestamp $review-time;
$_ isa action-execution ($user, $order), has timestamp $order-time;
$review-time > $order-time;
return mean($score);
)
};
The addition of the verification check makes the query significantly more complicated, and it’s not straightforward to read through. As queries become larger and retrieve more complex data patterns, they can become harder to maintain. This is a good use case for functions, which can significantly simplify queries. For this particular case, we’ll use the following function.
fun verified-reviews($book: book) -> { review }:
match
$review isa review;
rating ($review, $book);
order-line ($order, $book);
$_ isa action-execution ($user, $review), has timestamp $review-time;
$_ isa action-execution ($user, $order), has timestamp $order-time;
$review-time > $order-time;
return { $review };
Now, we can use this encapsulated logic to simplify the query we really wanted to write:
match
$book isa book;
fetch {
$book: title;
average-verified-score: (
match
let $review in verified-reviews($book);
$review has score $score;
return mean($score);
)
};
Using functions to abstract a complex query pattern into a more easily queried form is one of the most common use cases for functions in TypeDB. In principle this process is no different from using a view in a relational database.
Write a Fetch query that lists users. For each user, retrieve their user ID and the number of validated reviews they have written. Write the query once without making use of functions, and again writing a function similar to the above. Other than the ordering of results, the queries should give identical outputs.
You may find it useful to refer to the bookstore’s schema.
Schema
define
entity book @abstract,
owns isbn @card(0..2),
owns isbn-13 @key,
owns isbn-10 @unique,
owns title,
owns page-count,
owns genre @card(0..),
owns price,
plays contribution:work,
plays publishing:published,
plays promotion-inclusion:item,
plays order-line:item,
plays rating:rated,
plays recommendation:recommended;
entity hardback sub book,
owns stock;
entity paperback sub book,
owns stock;
entity ebook sub book;
entity contributor,
owns name,
plays contribution:contributor,
plays authoring:author,
plays editing:editor,
plays illustrating:illustrator;
entity company @abstract,
owns name;
entity publisher sub company,
plays publishing:publisher;
entity courier sub company,
plays delivery:deliverer;
entity publication,
owns year,
plays publishing:publication,
plays locating:located;
entity user,
owns id @key,
owns name,
owns birth-date,
plays action-execution:executor,
plays locating:located,
plays recommendation:recipient;
entity order,
owns id @key,
owns status,
plays order-line:order,
plays action-execution:action,
plays delivery:delivered;
entity promotion,
owns code @key,
owns name,
owns start-timestamp,
owns end-timestamp,
plays promotion-inclusion:promotion;
entity review,
owns id @key,
owns score,
owns verified,
plays rating:review,
plays action-execution:action;
entity login,
owns success,
plays action-execution:action;
entity address,
owns street,
plays delivery:destination,
plays locating:located;
entity place @abstract,
owns name,
plays locating:located,
plays locating:location;
entity city sub place;
entity state sub place;
entity country sub place;
relation contribution,
relates contributor,
relates work;
relation authoring sub contribution,
relates author as contributor;
relation editing sub contribution,
relates editor as contributor;
relation illustrating sub contribution,
relates illustrator as contributor;
relation publishing,
relates publisher,
relates published,
relates publication;
relation promotion-inclusion,
relates promotion,
relates item,
owns discount;
relation order-line,
relates order,
relates item,
owns quantity,
owns price;
relation rating,
relates review,
relates rated;
relation action-execution,
relates action,
relates executor,
owns timestamp;
relation delivery,
relates deliverer,
relates delivered,
relates destination;
relation locating,
relates located,
relates location;
relation recommendation,
relates recommended,
relates recipient;
attribute isbn @abstract, value string;
attribute isbn-13 sub isbn;
attribute isbn-10 sub isbn;
attribute title, value string;
attribute page-count, value integer;
attribute genre, value string;
attribute stock, value integer;
attribute price, value double;
attribute discount, value double;
attribute id, value string;
attribute code, value string;
attribute name, value string;
attribute birth-date, value datetime;
attribute street, value string;
attribute year, value integer;
attribute quantity, value integer;
attribute score, value integer;
attribute verified, value boolean;
attribute timestamp, value datetime;
attribute start-timestamp, value datetime;
attribute end-timestamp, value datetime;
attribute status, value string @regex("^(paid|dispatched|delivered|returned|canceled)$");
attribute success, value boolean;
# TODO: Change to check
fun is_review_verified_by_purchase($review: review) -> { order }:
match
($review, $product) isa rating;
($order, $product) isa order-line;
($user, $review) isa action-execution, has timestamp $review-time;
($user, $order) isa action-execution, has timestamp $order-time;
$review-time > $order-time;
return { $order };
fun book_recommendations_for($user: user) -> {book}:
match
$new-book isa book;
{
let $new-book in book_recommendations_by_author($user);
} or {
let $new-book in book_recommendations_by_genre($user);
};
return { $new-book };
fun book_recommendations_by_genre($user: user) -> { book }:
match
$user isa user;
$liked-book isa book;
{
($user, $order-for-liked) isa action-execution;
($order-for-liked, $liked-book) isa order-line;
} or {
($user, $review-for-liked) isa action-execution;
($review-for-liked, $liked-book) isa rating;
$review-for-liked has score >= 7;
};
$new-book isa book;
not { {
($user, $order-for-new) isa action-execution;
($order-for-new, $new-book) isa order-line;
} or {
($user, $review-for-new) isa action-execution;
($review-for-new, $new-book) isa rating;
}; };
$liked-book has genre $shared-genre;
$new-book has genre $shared-genre;
not { {
$shared-genre == "fiction";
} or {
$shared-genre == "nonfiction";
}; };
return { $new-book };
fun book_recommendations_by_author($user: user) -> { book }:
match
$user isa user;
$liked-book isa book;
{
($user, $order-for-liked) isa action-execution;
($order-for-liked, $liked-book) isa order-line;
} or {
($user, $review-for-liked) isa action-execution;
($review-for-liked, $liked-book) isa rating;
$review-for-liked has score >= 7;
};
$new-book isa book;
not { {
($user, $order-for-new) isa action-execution;
($order-for-new, $new-book) isa order-line;
} or {
($user, $review-for-new) isa action-execution;
($review-for-new, $new-book) isa rating;
}; };
($liked-book, $shared-author) isa authoring;
($new-book, $shared-author) isa authoring;
return { $new-book };
fun order_line_best_price($line: order-line) -> { double }:
match
($order) isa action-execution, has timestamp $order-time;
$line isa order-line, links ($order, $item);
$item has price $retail-price;
let $time_value = $order-time;
let $best-discount = best_discount_for_item($item, $time_value);
let $discounted-price = round(100 * $retail-price * (1 - $best-discount)) / 100;
$line has quantity $quantity;
let $line-total = $quantity * $discounted-price;
return { $line-total };
fun best_discount_for_item($item: book, $order-time: datetime) -> double:
match
{
$inclusion isa promotion-inclusion,
links ($promotion, $item),
has discount $discount-attr;
$promotion has start-timestamp <= $order-time,
has end-timestamp >= $order-time;
let $discount = $discount-attr;
} or {
let $discount = 0.0; # default
};
return max($discount);
fun transitive_places($place: place) -> { place }:
match
{
locating (located: $place, location: $parent);
} or {
locating (located: $place, location: $middle);
let $parent in transitive_places($middle);
};
return { $parent };
Sample solution
Without functions:
match
$user isa user, has id $id;
fetch {
"user-id": $id,
"verified-reviews": (
match
rating ($review, $book);
order-line ($order, $book);
$_ isa action-execution ($user, $review), has timestamp $review-time;
$_ isa action-execution ($user, $order), has timestamp $order-time;
$review-time > $order-time;
return count;
)
};
With functions:
with fun verified-user-reviews($user: user) -> { review }:
match
$review isa review;
rating ($review, $book);
order-line ($order, $book);
$_ isa action-execution ($user, $review), has timestamp $review-time;
$_ isa action-execution ($user, $order), has timestamp $order-time;
$review-time > $order-time;
return { $review };
match
$user isa user, has id $id;
fetch {
"user-id": $id,
"verified-reviews": (
match
let $review in verified-user-reviews($user);
return count;
)
};