# Explore the NBA games dataset with dcupl

The NBA games dataset on Kaggle covers every game since the 2003-04 season: teams, games with their final scores, and a box score line for every player in every game, about 650,000 rows. In this example you load three of its files into a local dcupl app, link games to teams and box scores to games, and answer questions like "how did the 2020 Finals go" or "who scored the most points in a season".

**Time required:** 15 minutes

**What you will learn:** set the key of a generated model yourself, see how dcupl reports duplicate keys, compose labels with expressions across references, and aggregate over 650,000 rows by a value derived from another model.

## The dataset

The data comes from [NBA games data on Kaggle](https://www.kaggle.com/datasets/nathanlauga/nba-games). This example uses three of its five files:

| File                | Rows (in the copy used here) | What a row is                                                          |
| ------------------- | ---------------------------: | ---------------------------------------------------------------------- |
| `teams.csv`         |                           30 | A team: city, nickname, arena, head coach                              |
| `games.csv`         |                       25,796 | A game: date, season, home and visitor team, points and shooting stats |
| `games_details.csv` |                      645,953 | One player's box score in one game: minutes, points, rebounds, assists |

`players.csv` (player per team and season) and `ranking.csv` (daily standings) fit in the same way once you have done this one. The copy used here covers the seasons 2003 to 2021; the dataset on Kaggle may have been extended since, so your counts can differ. Check the dataset's licence on its Kaggle page before you publish anything built on it.

## Prerequisites

- The [dcupl CLI](/cli/installation) installed (`dcupl --version` to check)
- A Kaggle account to download the dataset

## Step 1: create the workspace

```bash filename="terminal"
dcupl init nba --starter empty
cd nba
kaggle datasets download -d nathanlauga/nba-games --unzip -p dcupl/data
```

Without the Kaggle CLI, download the ZIP from the [Kaggle page](https://www.kaggle.com/datasets/nathanlauga/nba-games) and copy `teams.csv`, `games.csv` and `games_details.csv` into `dcupl/data/`.

## Step 2: generate the models

```bash filename="terminal"
dcupl generate model --from dcupl/data/teams.csv --name Team --register
dcupl generate model --from dcupl/data/games.csv --name Game --register
dcupl generate model --from dcupl/data/games_details.csv --name GameDetail --register
```

The generator detects no key column in any of the three files and gives each model generated keys. That is right for `GameDetail` (a box score line has no ID of its own), but teams and games have one. Set it in both models:

```json title="Team.dcupl.json: change these two fields"
{ "keyProperty": "TEAM_ID", "autoGenerateKey": false }
```

```json title="Game.dcupl.json: change these two fields"
{ "keyProperty": "GAME_ID", "autoGenerateKey": false }
```

`GAME_ID` is not quite unique: 29 games appear twice in `games.csv`. Keyed by `GAME_ID`, each of them becomes one game, and the app reports the collision when it loads (step 4).

## Step 3: link and label the models

```mermaid
classDiagram
  direction LR
  class Team {
    TEAM_ID : key
    CITY : string
    NICKNAME : string
    fullName : expression
  }
  class Game {
    GAME_ID : key
    HOME_TEAM_ID : Team
    VISITOR_TEAM_ID : Team
    matchup : expression
  }
  class GameDetail {
    GAME_ID : Game
    PLAYER_NAME : string
    PTS : float
    SEASON : derived
  }
  Game --> Team : HOME_TEAM_ID
  Game --> Team : VISITOR_TEAM_ID
  GameDetail --> Game : GAME_ID
```

**Team.** Add an expression property that joins city and nickname into the team's full name:

```json title="Team.dcupl.json: add to properties"
{ "key": "fullName", "type": "string", "expression": "${CITY} ${NICKNAME}" }
```

**Game.** Delete the `HOME_TEAM_ID` and `VISITOR_TEAM_ID` properties and make them references to `Team`:

```json title="Game.dcupl.json: references"
[
  { "key": "HOME_TEAM_ID", "type": "singleValued", "model": "Team" },
  { "key": "VISITOR_TEAM_ID", "type": "singleValued", "model": "Team" }
]
```

Then derive both teams' full names, and add an expression that reaches through the references for a short label:

```json title="Game.dcupl.json: add to properties"
{ "key": "homeTeam", "type": "string", "derive": { "localReference": "HOME_TEAM_ID", "remoteProperty": "fullName" } },
{ "key": "visitorTeam", "type": "string", "derive": { "localReference": "VISITOR_TEAM_ID", "remoteProperty": "fullName" } },
{ "key": "matchup", "type": "string", "expression": "${VISITOR_TEAM_ID.NICKNAME} @ ${HOME_TEAM_ID.NICKNAME}" }
```

**GameDetail.** Delete the `GAME_ID` property, reference the game, and derive its season, so you can filter box scores by season:

```json title="GameDetail.dcupl.json: references"
[{ "key": "GAME_ID", "type": "singleValued", "model": "Game" }]
```

```json title="GameDetail.dcupl.json: add to properties"
{ "key": "SEASON", "type": "int", "derive": { "localReference": "GAME_ID", "remoteProperty": "SEASON" } }
```

See [Expression properties](/sdk/advanced/expression-properties) for what an expression can reach and [Derived properties](/sdk/advanced/derived-properties) for `derive`.

## Step 4: load the data

```bash filename="terminal"
dcupl app create --load --auto-serve --json
```

```json title="Output (last line)"
{
  "appId": "jolly-magpie-e307",
  "built": true,
  "collisions": [{ "model": "Game", "keyProperty": "GAME_ID", "duplicateCount": 29 }]
}
```

The app ID is random. `collisions` is the duplicate check from step 2: 29 rows of `games.csv` shared a `GAME_ID` with an earlier row, and the later row won.

## Step 5: query the data

### One game, fully resolved

The 2020 Finals' deciding game 6, with the derived team names and the `matchup` expression:

```bash filename="terminal"
dcupl app query one --model Game --item-key 41900406 --json \
  | jq '{GAME_DATE_EST, matchup, homeTeam, visitorTeam, PTS_home, PTS_away}'
```

```json title="Output"
{
  "GAME_DATE_EST": "2020-10-11T00:00:00.000Z",
  "matchup": "Lakers @ Heat",
  "homeTeam": "Miami Heat",
  "visitorTeam": "Los Angeles Lakers",
  "PTS_home": 93,
  "PTS_away": 106
}
```

### The Finals series

Finals games have IDs from `41900401` on in the 2019-20 season; filter by ID range and sort by date:

```bash filename="terminal"
dcupl app query execute --model Game \
  --query '[{"attribute":"GAME_ID","operator":"gte","value":41900401},{"attribute":"GAME_ID","operator":"lte","value":41900407}]' \
  --sort GAME_DATE_EST:asc --projection GAME_DATE_EST,matchup,PTS_away,PTS_home --json
```

```json title="Output"
[
  {
    "key": "41900401",
    "GAME_DATE_EST": "2020-09-30T00:00:00.000Z",
    "matchup": "Heat @ Lakers",
    "PTS_away": 98,
    "PTS_home": 116
  },
  {
    "key": "41900402",
    "GAME_DATE_EST": "2020-10-02T00:00:00.000Z",
    "matchup": "Heat @ Lakers",
    "PTS_away": 114,
    "PTS_home": 124
  },
  {
    "key": "41900403",
    "GAME_DATE_EST": "2020-10-04T00:00:00.000Z",
    "matchup": "Lakers @ Heat",
    "PTS_away": 104,
    "PTS_home": 115
  },
  {
    "key": "41900404",
    "GAME_DATE_EST": "2020-10-06T00:00:00.000Z",
    "matchup": "Lakers @ Heat",
    "PTS_away": 102,
    "PTS_home": 96
  },
  {
    "key": "41900405",
    "GAME_DATE_EST": "2020-10-09T00:00:00.000Z",
    "matchup": "Heat @ Lakers",
    "PTS_away": 111,
    "PTS_home": 108
  },
  {
    "key": "41900406",
    "GAME_DATE_EST": "2020-10-11T00:00:00.000Z",
    "matchup": "Lakers @ Heat",
    "PTS_away": 106,
    "PTS_home": 93
  }
]
```

### Top scorers of a season

Group the box scores of the 2019-20 season (`SEASON` 2019, derived from the game) by player, add up the points and keep the five highest sums (`PTS_sum`, the aggregate's sort key); `jq` only shortens the output:

```bash filename="terminal"
dcupl app fn groupBy --model GameDetail --attribute PLAYER_NAME \
  --query '{"attribute":"SEASON","operator":"eq","value":2019}' \
  --aggregate PTS:sum --sort PTS_sum:desc --limit 5 --json \
  | jq '[.items[] | {player: .key, points: ._aggregates[0].sum}]'
```

```json title="Output"
[
  { "player": "James Harden", "points": 2957 },
  { "player": "LeBron James", "points": 2369 },
  { "player": "Anthony Davis", "points": 2273 },
  { "player": "Giannis Antetokounmpo", "points": 2246 },
  { "player": "Damian Lillard", "points": 2158 }
]
```

The sums cover every game of the season in the file, preseason and playoffs included, so they are higher than the official regular-season totals.

### How scoring changed

The average points of the home team, in the 2004-05 and the 2019-20 season:

```bash filename="terminal"
dcupl app fn aggregate --model Game --attribute PTS_home --types avg \
  --query '{"attribute":"SEASON","operator":"eq","value":2004}' --json
dcupl app fn aggregate --model Game --attribute PTS_home --types avg \
  --query '{"attribute":"SEASON","operator":"eq","value":2019}' --json
```

```json title="Output"
{ "attribute": "PTS_home", "types": ["avg"], "avg": 98.60499265785609 }
{ "attribute": "PTS_home", "types": ["avg"], "avg": 112.27477840451249 }
```

When you are done, stop the app with `dcupl app destroy`.

## Use it in your application

The workspace is a regular dcupl project: the [loader](/sdk/api/loader) loads the same models and files in Node.js or the browser, and `list.catalog.fn.groupBy()` runs the same group-by. `games_details.csv` is about 90 MB; keep it on the server or in a [REST API](/console/rapi) instance, and load only teams and games in the browser.

## Next steps

- [Austrian lottery example](/learn/examples/austrian-lottery) — one model, expressions and tagged resources
- [Expression properties](/sdk/advanced/expression-properties) — templates across references
- [groupBy()](/sdk/fn/group-by) — groups with per-group aggregates
- [Local data apps](/cli/local-data-apps) — every `dcupl app` command
