Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 29 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -161,18 +161,42 @@ We use the [X-Wines](https://github.com/rogerioxavier/X-Wines) dataset. It is re
|---|---|---|---|
| Test | 100 | 1 000 | Local development and automated tests |
| Slim | 1 007 | 150 000 | The VM |
| Full | 100 646 | about 21 million | Planned for load testing and to show that the solution scales |
| Full | 100 646 | 21 013 536 | Load test locally, see the numbers below |

Local development uses the Test version. The VM uses the Slim version, because it gives
enough wines to make search, filters and pagination meaningful, and it imports in a few seconds.
The Slim files are not in the repository. Download them from
[Kaggle](https://www.kaggle.com/datasets/rogerioxavier/x-wines-slim-version) and see the
[VM guide](docs/vm.md) for how to load them.

We plan to use Full locally to show that the solution scales. Search, filtering, sorting and pagination run in
PostgreSQL with indexes (a trigram index for text search and B-tree and GIN indexes for sorting and filters),
so the frontend never loads more than one page of results. When Full is loaded, we will add the import time,
the database size and the measured search time (with `EXPLAIN ANALYZE`) here.
### Load test with the Full dataset

We loaded the Full version locally to show that the solution scales. Search, filtering, sorting and
pagination run in PostgreSQL with indexes (a trigram index for text search and B-tree and GIN indexes
for sorting and filters), and the average and count are stored on the wine, so no query ever counts
21 million rows. The frontend never loads more than one page of results.

Measured on 16 November 2026, on a MacBook Air M4 with PostgreSQL 17:

| Step | Rows | Time |
|---|---|---|
| Import of wines | 100 646 | 4.8 s |
| Import of ratings | 21 013 536 | 228.8 s |
| Recalculating every average | 100 646 wines | 15.3 s |

| Request | Time |
|---|---|
| First page, sorted by rating | 55 ms |
| Search for "pinot noir" | 49 ms |
| Red wine from Italy, rating 4+, sorted by name | 23 ms |
| Counts for every filter group | 57 ms |

The database is 2.4 GB in total: 2.2 GB of ratings and 156 MB of wines.

The ratings file is 1 GB, which is larger as one string than Node allows, so the import reads it line
by line and writes it in batches of 5 000. That keeps the memory use flat, whichever version is loaded.

The VM uses the Slim version, because the Full dataset needs more disk than the VM has to spare.

This is subject to change as needed.

Expand Down
20 changes: 20 additions & 0 deletions backend/src/csv.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { describe, expect, it } from 'vitest';
import { splitCsvLine } from './csv';

describe('splitCsvLine', () => {
it('splits plain cells', () => {
expect(splitCsvLine('1,2,N.V.,4.5')).toEqual(['1', '2', 'N.V.', '4.5']);
});

it('keeps commas inside quotes', () => {
expect(splitCsvLine('1,"Merlot, Syrah",3')).toEqual(['1', 'Merlot, Syrah', '3']);
});

it('reads "" as one quote', () => {
expect(splitCsvLine('1,"say ""hi""",3')).toEqual(['1', 'say "hi"', '3']);
});

it('keeps empty cells', () => {
expect(splitCsvLine('1,,3')).toEqual(['1', '', '3']);
});
});
35 changes: 35 additions & 0 deletions backend/src/csv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,39 @@ function parseRows(text: string): string[][] {
rows.push(row);
}
return rows;
}

/**
* Splits one CSV line into cells. Used when the file is read line by line, which
* the 21M ratings file has to be: as one string it is larger than Node allows.
* Only safe when no field contains a newline, which is true for the ratings file.
*/
export function splitCsvLine(line: string): string[] {
const cells: string[] = [];
let cell = '';
let quoted = false;

for (let i = 0; i < line.length; i += 1) {
const char = line[i];
if (quoted) {
if (char === '"' && line[i + 1] === '"') {
cell += '"';
i += 1;
} else if (char === '"') {
quoted = false;
} else {
cell += char;
}
} else if (char === '"') {
quoted = true;
} else if (char === ',') {
cells.push(cell);
cell = '';
} else {
cell += char;
}
}

cells.push(cell);
return cells;
}
84 changes: 71 additions & 13 deletions backend/src/scripts/seed-xwines.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,21 @@
// Loads X-Wines CSV files into the database. Meant for the Test and Slim versions.
// Loads X-Wines CSV files into the database: the Test, Slim or Full version.
// Usage: tsx src/scripts/seed-xwines.ts <wines.csv> <ratings.csv>
// Safe to run more than once: existing wines are updated, existing ratings are skipped.
import { readFileSync } from 'node:fs';
import { parseCsv } from '../csv';
//
// The wines file is small enough to read at once. The ratings file is not: the Full
// version has 21 million rows and is larger as one string than Node allows, so it is
// read line by line and sent to the database in batches.
import { createReadStream, readFileSync } from 'node:fs';
import { createInterface } from 'node:readline';
import { parseCsv, splitCsvLine } from '../csv';
import { pool } from '../db';
import { parseNumber, parseTextList, parseYearList, toSearchText } from '../xwines-parse';
import { UPDATE_ALL_RATING_STATS } from '../rating-stats';

const BATCH_SIZE = 1000;
const WINE_BATCH_SIZE = 1000;
const RATING_BATCH_SIZE = 5000;
/** How often the import reports progress, in rows. */
const PROGRESS_EVERY = 500_000;

const UPSERT_WINES = `
INSERT INTO wine (id, name, type, elaborate, grapes, harmonize, abv, body, acidity,
Expand Down Expand Up @@ -75,27 +83,77 @@ function toRatingRow(row: Record<string, string>) {
};
}

async function insertInBatches(sql: string, rows: object[]) {
for (let start = 0; start < rows.length; start += BATCH_SIZE) {
await pool.query(sql, [JSON.stringify(rows.slice(start, start + BATCH_SIZE))]);
async function insertInBatches(sql: string, rows: object[], size: number) {
for (let start = 0; start < rows.length; start += size) {
await pool.query(sql, [JSON.stringify(rows.slice(start, start + size))]);
}
}

/** Reads the ratings file line by line, so only one batch is in memory at a time. */
async function importRatings(file: string): Promise<number> {
const lines = createInterface({
input: createReadStream(file, 'utf8'),
crlfDelay: Infinity,
});

let header: string[] | null = null;
let batch: object[] = [];
let total = 0;
let reported = 0;

for await (const line of lines) {
if (line.trim() === '') continue;

const cells = splitCsvLine(line);
if (!header) {
header = cells.map((name) => name.replace(/^\uFEFF/, ''));
continue;
}

batch.push(toRatingRow(Object.fromEntries(header.map((name, i) => [name, cells[i] ?? '']))));

if (batch.length >= RATING_BATCH_SIZE) {
await pool.query(INSERT_RATINGS, [JSON.stringify(batch)]);
total += batch.length;
batch = [];
if (total - reported >= PROGRESS_EVERY) {
reported = total;
console.log(` ${total.toLocaleString('en')} ratings …`);
}
}
}

if (batch.length > 0) {
await pool.query(INSERT_RATINGS, [JSON.stringify(batch)]);
total += batch.length;
}

return total;
}

/** Seconds since `start`, with one decimal. */
function secondsSince(start: number): string {
return `${((Date.now() - start) / 1000).toFixed(1)} s`;
}

async function main() {
const [winesFile, ratingsFile] = process.argv.slice(2);
if (!winesFile || !ratingsFile) {
throw new Error('Usage: seed-xwines <wines.csv> <ratings.csv>');
}

const wineStart = Date.now();
const wines = parseCsv(readFileSync(winesFile, 'utf8')).map(toWineRow);
const ratings = parseCsv(readFileSync(ratingsFile, 'utf8')).map(toRatingRow);
await insertInBatches(UPSERT_WINES, wines, WINE_BATCH_SIZE);
console.log(`Saved ${wines.length} wines in ${secondsSince(wineStart)}.`);

const ratingStart = Date.now();
const ratings = await importRatings(ratingsFile);
console.log(`Saved ${ratings} ratings in ${secondsSince(ratingStart)}.`);

await insertInBatches(UPSERT_WINES, wines);
console.log(`Saved ${wines.length} wines.`);
await insertInBatches(INSERT_RATINGS, ratings);
console.log(`Saved ${ratings.length} ratings.`);
const statsStart = Date.now();
await pool.query(UPDATE_ALL_RATING_STATS);
console.log('Updated average ratings.');
console.log(`Updated average ratings in ${secondsSince(statsStart)}.`);
}

main()
Expand Down
3 changes: 3 additions & 0 deletions docs/vm.md
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,9 @@ The files are not in the repository.
npx tsx src/scripts/seed-xwines.ts ~/xwines-slim/XWines_Slim_1K_wines.csv ~/xwines-slim/XWines_Slim_150K_ratings.csv
```

The same script loads the Full version (100 646 wines, 21 million ratings), but that needs about
2.4 GB of database and more disk than the VM has to spare, so we only use Full locally.

The import is safe to run more than once. The Test wines are part of Slim, so they are updated, not duplicated.
The backend does not need a restart.

Expand Down