Grouping Text Rows into Equal-Sized Groups

Grouping large datasets into manageable chunks is crucial for user-friendly interfaces. This article explores how to create equal-sized groups using SQL and PostgreSQL, ensuring balanced group sizes and concise group names.

Binary Buddies · 5 min read · 10 views

The challenge of grouping text rows into equal-sized groups arises when dealing with large datasets, such as a table containing thousands of items. The goal is to create a (materialized) view that groups these items into manageable chunks, each containing approximately the square root of the total number of items. This approach reduces the number of elements users need to scroll through, making it easier to navigate and select items. For instance, if there are 10,000 items, the UI would display 100 groups, each containing 100 items. Each group is named based on the range of text values it contains, such as A-B or C-EG, to provide a clear and concise label.

The key is to balance group size and the length of group names. Ideally, each group should have a name that is at most three characters long, but this can be relaxed to ensure that group sizes are reasonably consistent. This problem can be approached using a scoring function that identifies local minimums, which determine the boundaries of each group. The function considers the number of common first letters between consecutive items and a SIN squared function that oscillates based on the square root of the total number of items. This heuristic helps in finding a compromise between group size and name length.

Generating Random Data

To demonstrate the solution, we start by creating a table with random data. This table, named Test, will contain a large number of items, each with a type and a name. The names are generated using a combination of random characters to simulate a real-world dataset.

CREATE TABLE Test ( ItemType INTEGER, ItemName VARCHAR );
WITH Chars(chars) AS ( SELECT ARRAY[ 'A'... 'z' ] ) INSERT INTO Test SELECT t, string_agg(chars[random(0, 165)], '') FROM chars CROSS JOIN generate_series(1, 3) t CROSS JOIN generate_series(1, 5) l CROSS JOIN generate_series(1, 400) i GROUP BY t, i;

This query creates a table with 400 items, each having a type and a randomly generated name. The string_agg function concatenates random characters to form the item names, ensuring a diverse and realistic dataset.

Materializing and Indexing the Data

To optimize performance, we materialize the trimmed and uppercased item names and create an index on them. This step is crucial for efficient querying and grouping.

CREATE TABLE Items ( item_type INTEGER, item_name VARCHAR(8), item_name_upper VARCHAR(8) GENERATED ALWAYS AS (TRIM(BOTH FROM UPPER(item_name))) STORED ); CREATE INDEX ix_test_type_nameUpper ON items(item_type, item_name_upper);

The item_name_upper column stores the trimmed and uppercased version of the item name, and the index on item_type and item_name_upper speeds up the query performance.

Calculating Group Boundaries

The next step is to calculate the group boundaries using a scoring function. This function considers the number of common first letters between consecutive items and a SIN squared function. The SIN squared function oscillates based on the square root of the total number of items, helping to identify the local minimums that determine the group boundaries.

WITH Items(ItemType, ItemName) AS ( SELECT ItemType, TRIM(BOTH FROM upper(ItemName)) FROM Test ), stats1(ItemType, NameStarts) AS ( SELECT DISTINCT Items.ItemType, TRIM(BOTH FROM upper(left(ItemName, generate_series(1, 3)))) AS btrim FROM Items ), stats2(ItemType, NameStarts, NameCount) AS ( SELECT s1.ItemType, s1.NameStarts, count(*) FILTER (WHERE left(i.ItemName, length(s1.NameStarts)) <= s1.NameStarts) AS count FROM stats1 s1 JOIN items i ON s1.ItemType = i.ItemType GROUP BY s1.ItemType, s1.NameStarts ), stats3(ItemType, NameStarts, NameCount, totalnamecount) AS ( SELECT stats2.ItemType, min(stats2.NameStarts) AS min, stats2.NameCount, max(stats2.NameCount) OVER (PARTITION BY stats2.ItemType) AS max FROM stats2 GROUP BY stats2.ItemType, stats2.NameCount ), stats4(ItemType, NameStarts, NameCount, score, groupnumber) AS ( SELECT stats3.ItemType, stats3.NameStarts, stats3.NameCount, length(stats3.NameStarts) * (.05 + .95 * power(sin(pi() * stats3.NameCount / sqrt(stats3.totalnamecount)::integer), 2)), row_number() OVER (PARTITION BY stats3.ItemType ORDER BY length(stats3.NameStarts) * (.05 + .95 * power(sin(pi() * stats3.NameCount / sqrt(stats3.totalnamecount)::integer), 2)) ) ...

The scoring function combines the length of the name start and the SIN squared function to determine the score. The row_number() function is used to assign a group number based on the score, ensuring that the groups are created based on the local minimums.

Creating the Grouped View

Once the group boundaries are calculated, we create a materialized view to store the grouped data. This view is refreshed regularly, such as nightly, to ensure that the groups remain up-to-date. The materialized view provides a snapshot of the grouped data, which can be efficiently queried and displayed in the UI.

CREATE MATERIALIZED VIEW grouped_items AS WITH look_around(item_type, item_name, type_row_count, rn, prev_name) AS ( SELECT item_type, item_name_upper, COUNT(*) OVER (PARTITION BY item_type), ROW_NUMBER() OVER (PARTITION BY item_type ORDER BY item_name_upper), LAG(item_name_upper, 1, '') OVER (PARTITION BY item_type ORDER BY item_name_upper) FROM items ), prefixed(item_type, item_name, type_row_count, rn, prev_name, name_prefix) AS ( SELECT *, prefix FROM look_around CROSS JOIN LATERAL ( SELECT CASE WHEN LEFT(item_name, 3) = LEFT(prev_name, 3) THEN NULL WHEN LEFT(item_name, 2) = LEFT(prev_name, 2) THEN LEFT(item_name, 3) WHEN LEFT(item_name, 1) = LEFT(prev_name, 1) THEN LEFT(item_name, 2) ELSE LEFT(item_name, 1) END ) AS prefix(prefix) ), paginated_and_scored(item_type, item_name, type_row_count, rn, name_prefix, group_count, group_size, theta, naive_group_id, score, new_group_marker, min_score) AS ( SELECT item_type, item_name, type_row_count, rn, name_prefix, group_count, group_size, theta, page.id, page.score, -- Mark as new page start if lowest score in prelimary group -- > But never mark a new page start in first or last group CASE WHEN page.id = 0 THEN 0 WHEN page.id = group_count THEN 0 WHEN 1 = ROW_NUMBER() OVER (PARTITION BY item_type, page.id ORDER BY page.score) THEN 1 ELSE 0 END, MIN(page.score) OVER (PARTITION BY item_type, page.id) FROM prefixed CROSS JOIN LATERAL ( SELECT CASE WHEN type_row_count < 20 THEN 1 ELSE SQRT(type_row_count) END::INT ) AS group_count(group_count) CROSS JOIN LATERAL ( SELECT type_row_count::FLOAT / group_count ) AS group_size(group_size) CROSS JOIN LATERAL ( SELECT pi() * 2 * (rn-1) / group_size + pi() ) AS theta(theta) CROSS JOIN LATERAL ( SELECT (LENGTH(name_prefix) + 1) * (POWER((COS(theta) + 1) / 2, 2) + 0.5) ) AS page(id, score) ) SELECT item_type, item_name, type_row_count, rn, name_prefix, group_count, group_size, theta, naive_group_id, score, new_group_marker, min_score, SUM(new_group_marker) OVER (PARTITION BY item_type ORDER BY item_name) AS page_id FROM paginated_and_scored;

The materialized view grouped_items stores the grouped data, including the item type, name, and the group it belongs to. The view is designed to be refreshed regularly to maintain up-to-date groups.

Handling Uneven Distribution

Uneven distribution of the first few characters in the item names can be a significant issue. However, the scoring function and the use of the SIN squared function help to mitigate this problem. The SIN squared function ensures that the groups are more evenly distributed, even if the distribution of the first few characters is uneven. This approach works well in most cases, but it may not be perfect in all scenarios.

For example, if the dataset has a large number of items starting with the same few characters, the groups may still be uneven. To handle this, you can adjust the scoring function to give more weight to the distribution of the first few characters or use a different heuristic. This flexibility allows you to fine-tune the grouping logic based on the specific characteristics of your dataset.

Performance Considerations

Performance is a critical aspect of this solution, especially when dealing with large datasets. The use of materialized views and appropriate indexing can significantly improve query performance. The materialized view provides a snapshot of the grouped data, which can be queried efficiently without the need to recalculate the groups every time.

Additionally, the use of window functions and the optimization of the scoring function help to reduce the computational overhead. The scoring function is designed to be computationally efficient, and the use of the SIN squared function ensures that the groups are created in a way that balances group size and name length.

Trade-offs and Limitations

While this approach provides a robust solution for grouping text rows into equal-sized groups, it has some trade-offs and limitations. The main trade-off is the balance between group size and name length. Adjusting the scoring function can help to optimize this balance, but it may not always be perfect.

Another limitation is the performance impact of recalculating the groups, especially for very large datasets. While the use of materialized views and indexing can mitigate this, the initial creation and periodic refreshing of the materialized view can still be resource-intensive.

Finally, the solution assumes that the distribution of the first few characters in the item names is relatively uniform. If the distribution is highly skewed, the groups may still be uneven, and additional tuning of the scoring function may be necessary.

This article draws on Grouping text rows in equal-sized groups and answers to it (1, 2), on the Stack Exchange network, licensed under CC BY-SA 4.0.

  • #equal-sized groups
  • #grouping
  • #materialized view
  • #postgresql
  • #sql
  • #text rows

Comments

Add a comment
Sign in with Google to join the conversation