π¦Έ Advanced Exercises
Extra activity! Do it if you have extra time or are following along at home. These won't be covered during the hands-on lab.
Promote shorter booksβ
You've noticed that readers tend to prefer shorter books. Without using a large score boost, try to promote shorter books in the search results.
Even without a score adjuster, the should
operator will still boost the score of the documents that match it.
Answer
public async searchBooks(query: string): Promise<Book[]> {
const aggregationPipeline = [
{
$search: {
"index": "fulltextsearch",
"compound": {
"must": [
{
"text": {
query,
"path": ["title", "authors.name", "genres"],
fuzzy: {
maxEdits: 2
}
}
}
],
"should": [
{
"equals": {
"value": true,
"path": "bookOfTheMonth",
"score": {
"boost": { value: 10 }
}
}
},
{
"range": {
path: "pages",
lt: 80
}
}
]
}
}
}
];
const books = await collections?.books?.aggregate(aggregationPipeline).toArray() as Book[];
return books;
}
Choose your favorite method to build aggregation pipelines and try to solve the following exercises.
Most available book of the month booksβ
Build a search aggregation stage that will promote the books of the month and return the books with the most copies available first.
Most prolific pooh authorβ
Find out which author has written the most books that contain the word "pooh" (we're talking about the bear here) in the title or synopsis.
Assume typos but still find the matchesβ
Find books that match a user query, but also return books that match with a typo. These books should be returned after the books that match the query.