- Notifications
You must be signed in to change notification settings - Fork23
TopN is an open source PostgreSQL extension that returns the top values in a database according to some criteria
License
citusdata/postgresql-topn
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
TopN is an open source PostgreSQL extension that returns the top values in a database according to some criteria. TopN takes elements in a data set, ranks them according to a given rule, and picks the top elements in that data set. When doing this, TopN applies an approximation algorithm to provide fast results using few compute and memory resources.
TheTopN extension becomes useful when you want to materialize top values, incrementally update these top values, and/or merge top values from different time intervals. If you're familiar withthe PostgreSQL HLL extension, you can think ofTopN as its cousin.
TopN becomes helpful when serving customer-facing dashboards or running analytical queries that need sub-second responses. Ranking events, users, or products in a given dimension becomes important for these workloads.
TopN is used by customers in production to serve real-time analytics queries over terabytes of data.
Calculating TopN elements in a set by applying count, sort, and limit is simple. As data sizes increase however, this method becomes slow and resource intensive.
The open sourceTopN extension enables you to serve instant and approximate results to TopN queries. To do this, you first materialize top values according to some criteria in a data type. You can then incrementally update these top values, or merge them on-demand across different time intervals.
TopN was originally created to helpCitus Data customers, who needed to scale out their PostgreSQL databases across dozens of machines. These customers needed to compute top values over terabytes of data in less than a second. We realized that the broader Postgres community could benefit fromTopN, and decided to open source it for all users.
The TopN approximation algorithm keeps a predefined number of frequent items and counters. If a new item already exists among these frequent items, the algorithm increases the item's frequency counter. Else, the algorithm inserts the new item into the counter list when there is enough space. If there isn't enough space, the algorithm evicts the bottom half of all counters. Since we typically keep counters for many more items (e.g. 100*N) than we are actually interested in, the actual top N items are unlikely to get evicted and will typically have accurate counts.
You can increase the algoritm's accuracy by increasing the predefined number of frequent items/counters.
Once you have PostgreSQL, you're ready to build TopN. For this, you will need to include the pg_config directory path in your make command. This path is typically the same as your PostgreSQL installation's bin/ directory path. For example:
PATH=/usr/local/pgsql/bin/:$PATH makesudo PATH=/usr/local/pgsql/bin/:$PATH make installYou can run the regression tests as the following.
sudo make installcheckIn this example, we take example customer reviews data from Amazon. We're then going to analyze the most reviewed products based on different criteria.
Let's start by downloading and decompressing source data files.
wget http://examples.citusdata.com/customer_reviews_2000.csv.gzgzip -d customer_reviews_2000.csv.gzNext, we're going to connect to PostgreSQL and create theTopN extension.
CREATE EXTENSION topn;
Let's then create our example table and load data into it.
CREATETABLEcustomer_reviews( customer_idTEXT, review_dateDATE, review_ratingINTEGER, review_votesINTEGER, review_helpful_votesINTEGER, product_idCHAR(10), product_titleTEXT, product_sales_rankBIGINT, product_groupTEXT, product_categoryTEXT, product_subcategoryTEXT, similar_product_idsCHAR(10)[]);\COPY customer_reviewsFROM'customer_reviews_2000.csv' WITH CSV;
Now, we're going to create an aggregation table that captures the most popular products for each month. We're then going to materialize top products for each month.
-- Create a roll-up table to capture most popular productsCREATETABLEpopular_products( review_datedate UNIQUE, agg_data jsonb);-- Create different summaries by grouping top reviews for each date (day, month, year)INSERT INTO popular_productsSELECT review_date, topn_add_agg(product_id)FROM customer_reviewsGROUP BY review_date;
From this table, you can compute the most popular/reviewed product for each day, in the blink of an eye.
SELECT review_date, (topn(agg_data,1)).*FROM popular_productsORDER BY review_date;
You can also instantly find the top 10 reviewed products across any time interval, in this case January.
SELECT (topn(topn_union_agg(agg_data),10)).*FROM popular_productsWHERE review_date>='2000-01-01'AND review_date<'2000-02-01'ORDER BY2DESC;
Or, you can quickly find the most reviewed product for each month in 2000.
SELECT date_trunc('month', review_date)AS review_month, (topn(topn_union_agg(agg_data),1)).*FROM popular_productsWHERE review_date>='2000-01-01'AND review_date<'2001-01-01'GROUP BY review_monthORDER BY review_month;
TopN provides the following user-defined functions and aggregates.
A PostgreSQL type to keep the frequent items and their frequencies.
This is the aggregate add function. It creates an emptyJSONB and inserts series of item from given column to create aggregate summary of these items. Note that the value must beTEXT type or casted toTEXT.
This is the aggregate for union operation. It merges theJSONB counter lists and returns the finalJSONB which stores overall result.
Gives the most frequentn elements and their frequencies as set of rows from the givenJSONB.
Adds the given text value as a new counter into theJSONB and returns a newJSONB if there is an enough space for one more counter. If not, the counter is added and then the counter list is pruned.
Takes the union of bothJSONBs and returns a newJSONB.
Sets the number of counters to be tracked in aJSONB. If at some point, the current number of counters exceedtopn.number_of_counters * 3, the list is pruned. The default value is 1000 fortopn.number_of_counters. When you increase this setting,TopN uses more space and provides more accurate estimates.
TopN is compatible with the PostgreSQL 9.6, 10, 11, 12, 13, 14, 15, 16 and 17 releases.TopN is also compatible with all supported Citus releases, including Citus 6.x, 7.x, 8.x, and 9.x. If you need to runTopN on a different version of PostgreSQL or Citus, please open an issue. Opening a pull request (PR) is also highly appreciated.
TheTopN extension to Postgreswas created by and is maintained by theCitus database team, now part of Microsoft. The Citus team also createdCitus, anopen source extension to Postgres that transforms Postgres into a distributed database.
About
TopN is an open source PostgreSQL extension that returns the top values in a database according to some criteria
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors14
Uh oh!
There was an error while loading.Please reload this page.