> ## Documentation Index
> Fetch the complete documentation index at: https://docs.activeviam.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Joining isolated stores in Copper

In databases, data is typically stored in different tables,
and it is often necessary to combine data from these tables.
In traditional SQL databases, this is done using the `JOIN` operator.
In Atoti, this can be done in two ways: [Datastore References](https://docs.activeviam.com/engine/java-sdk/6.2/datastore/datastore_config.md#references) and the
Copper API.
In this article we will explain how to use the Copper API and the `JOIN` operation to combine data from different
stores.

> We advise you to read the [following article](https://docs.activeviam.com/engine/java-sdk/6.2/copper/copper_publication.md) of the Copper documentation before
> proceeding as it contains important concepts relative to the Copper API.

## `JOIN` in Atoti

Datastore references allow joining data from different stores by matching fields.
This method is fast but has significant limitations:

* Only `LEFT JOIN` is available (returns all records from the first table as well as matching records from the second table if present or `NULL` otherwise).
* Only one-to-one and many-to-one relationships are supported: each record from the left table must match at most
  one record from the right table. This restriction is enforced at the datastore level during data loading.
* Datastore references cannot be used with [DirectQuery tables](https://docs.activeviam.com/engine/java-sdk/6.2/directquery/getting_started.md). Instead,
  DirectQuery joins must be used.

## Joining tables to a cube using Copper

The Copper API provides a more flexible way of joining data from different stores. This allows more complex joins and
relationships, such as one-to-many or many-to-many, without the restrictions of datastore references.

Unlike **datastore references**, which are designed for joining two tables, **Copper Join** allows a table to be joined to a cube.

When building a cube in Atoti, some fields from the base table become cube levels, while others become measures.
With Copper Join, fields from the new table can be used to:

* Specify the conditions that determine how the table fields are related (or joined) to existing cube levels (this is a **mapping**).
* Create new measures based on the joined data.
* Create new hierarchies in the cube, enriching the cube's structure and functionality for analysis.

Let's consider this simple case:

* The cube contains the single-level **user** hierarchy.
* The datastore contains a **hobbies** store, which is isolated from the selection and contains hobby related
  data (the primary key is `userName`):

| **user** |
| - |
| ALL |
|  Marion |
|  Nathan |
|  Roger |
|  Lukas |
|  Hannah |

| **userName (K)** | **hobby** | **budget** | **category** |
| - | - | - | - |
| Marion | dance | 1.0 | art |
| Roger | tennis | 2.0 | sport |
| Nathan | tennis | 2.0 | sport |
| Lukas | piano | 4.0 | art |
| Romain | piano | 4.0 | art |

Let's assume we want to create a measure that returns the budget a user has for their hobbies.
To achieve this, we need to join the cube with the datastore and then create a measure using the data from the datastore.

First, we create a join:

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
final CopperStore store =
    Copper.store("hobbies") // [1]
        .joinToCube(JoinType.INNER) // [2]
        .withMapping("userName", new LevelIdentifier("user", "user", "user")); // [3]
```

In line `[1]`, we select the table we want to join with the cube. \

In line `[2]`, we specify the use of `INNER JOIN`.
If you want to use `LEFT JOIN`, you can specify `JoinType.LEFT`.
If no join type is specified, `INNER JOIN` is used by default. \

In line `[3]`, we define that we want to join the table on the `userName` field to the cube's `user` level, similar to the `ON` clause in SQL.

The resulting `store` object can now be used to create measures and hierarchies based on the joined datastore.
Let's create a measure that returns the user's budget for hobbies:

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
Copper.newLookupMeasure(store.field("budget"))
    .withName("budget")
```

Now, we can retrieve the users' hobby budget by using the `budget` measure, for instance, with the following MDX query:

```mdx theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
SELECT 
  {[Measures].[budget]} ON COLUMNS, 
  NonEmpty([user].[user].[user].Members, [Measures].[budget]) ON ROWS
FROM [C]
```

This query will return the hobby budget for each user, using the `budget` measure created from the joined table data:

| | budget |
| - | - |
| Lukas | 4.0 |
| Marion | 1.0 |
| Nathan | 2.0 |
| Roger | 2.0 |

We can see that the user Hannah is not included in the results because she does not have any hobbies listed in the datastore.

> Note the function `NonEmpty`, which is used to filter out level members that have no corresponding measure values.
> By default, the results would include all cube levels, even those without any measure data.
> This happens due to the way the MDX engine in Atoti works: it first generates all possible combinations of levels
> on the axes (ignoring Copper Joins) and then fills in measure values.
> By using `NonEmpty`, you can ensure that only meaningful data is returned.

### `JOIN` types in Copper

In the Copper API, two types of JOIN are supported:

* `INNER JOIN`: returns only records that have matching values in both tables.
* `LEFT JOIN`: returns all records from the first table and matching records from the second table. For records without a match, `NULL` values are returned.

In the previous example, we used an `INNER JOIN`.
Now, let's see what changes if we use `LEFT JOIN`:

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
final CopperStore store =
    Copper.store("hobbies")
        .joinToCube(JoinType.LEFT)
        .withMapping("userName", new LevelIdentifier("user", "user", "user"));
```

Now, the result will include all users, even those who do not have hobbies in the datastore:

| | budget |
| - | - |
| **Hannah** | **0.0** |
| Lukas | 4.0 |
| Marion | 1.0 |
| Nathan | 2.0 |
| Roger | 2.0 |

In addition, we can specify a default value for cases where there are no matching records in the datastore.
This is done using the `withDefaultValue()` method:

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
final CopperStore store =
    Copper.store("hobbies")
        .joinToCube(JoinType.LEFT)
        .withDefaultValue(FieldPath.of("budget"), -666.0)
        .withMapping("userName", new LevelIdentifier("user", "user", "user"));
```

And result will be the following:

| | budget |
| - | - |
| **Hannah** | **-666.0** |
| Lukas | 4.0 |
| Marion | 1.0 |
| Nathan | 2.0 |
| Roger | 2.0 |

Note that `withDefaultValue()` only affects join measures.
In particular, labels of unknown hierarchy members still use the default value of the underlying store field as configured in the store description (e.g. "N/A" for strings by default).

### Use case: Many-To-Many Relationship

Let's consider a more complex scenario where a user can have multiple hobbies.
First, we need to modify the table schema by making the `hobby` field a key field.
Then, we will add a new record to the table:

| userName (K) | hobby (K) | budget | category |
| - | - | - | - |
| Marion | dance | 1.0 | art |
| Roger | tennis | 2.0 | sport |
| Nathan | tennis | 2.0 | sport |
| Lukas | piano | 4.0 | art |
| **Lukas** | **soccer** | **3.0** | **sport** |
| Romain | piano | 4.0 | art |

Now, Lukas has two hobbies: piano and soccer.
This is a **many-to-many** relationship:

* One user can have many hobbies.
* One hobby can be shared by many users.
* Or in other words, many users can have many hobbies.

For now, we can keep the same Java code as in the previous example:

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
final CopperStore store =
    Copper.store("hobbies") // [1]
        .joinToCube(JoinType.INNER) // [2]
        .withMapping("userName", new LevelIdentifier("user", "user", "user")); // [3]
```

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
Copper.newLookupMeasure(store.field("budget"))
    .withName("budget")
```

But if we keep the same MDX query,

```mdx theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
SELECT 
  {[Measures].[budget]} ON COLUMNS, 
  NonEmpty([user].[user].[user].Members, [Measures].[budget]) ON ROWS
FROM [C]
```

the result will be empty:

| | budget |
| - | - |
| | |

What's happening here?
The problem is that we have changed the structure of our data model with the addition of the many-to-many relationship.
The table structure is no longer aligned with the cube structure.

To solve this, Copper automatically creates hierarchies based on key fields in the datastore that aren't included in the mapping.
In our case, Copper will generate a `hobby` hierarchy containing all the hobbies from the datastore.
To retrieve the data, we need to use this hierarchy:

```mdx theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
SELECT
  {[Measures].[budget]} ON COLUMNS,
  NonEmpty(
    [user].[user].[user].Members * [hobby].[hobby].[hobby].Members, 
    [Measures].[budget]) ON ROWS
FROM [C]
```

Result:

| | | budget |
| - | - | - |
| Lukas | piano | 4.0 |
| Lukas | soccer | 3.0 |
| Marion | dance | 1.0 |
| Nathan | tennis | 2.0 |
| Roger | tennis | 2.0 |

Now, we can see that Lukas has two hobbies, and we can retrieve the budget for each of them.
But what if we want to get the total budget for all hobbies for each user?
To do this, we need to create an aggregated measure:

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
Copper.sum(store.field("budget"))
    .withName("budget")
```

Now, we can retrieve the total budget for each user:

| | budget |
| - | - |
| **Lukas** | **7.0** |
| Marion | 1.0 |
| Nathan | 2.0 |
| Roger | 2.0 |

Copper includes several built-in aggregations: `sum`, `avg`, `min`, and `max`.
You can also create your own custom aggregation by passing a plugin key to the `Copper.agg()` method.

If we want to configure the `hobby` hierarchy, we can do so by explicitly publishing it:

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
Copper.newHierarchy("hobby")
    .fromField(store.field("hobby"))
    .withLevelName("CUSTOM_NAME_FOR_HOBBY_LEVEL")
    .publish(context);
```

Hierarchies can be also created manually.
For example, let's add a `category` hierarchy:

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
Copper.newHierarchy("category").fromField(store.field("category")).publish(context);
```

Now, we can use the `category` hierarchy in MDX queries:

```mdx theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
SELECT
  [category].[category].[category].Members * {[Measures].[budget]} ON COLUMNS,
  NonEmpty([user].[user].[user].Members, [Measures].[budget]) ON ROWS
FROM [C]
```

Result:

| | art/budget | sport/budget |
| - | - | - |
| Lukas | 4.0 | 3.0 |
| Marion | 1.0 | |
| Nathan | | 2.0 |
| Roger | | 2.0 |

> A field does not have to be a key field to be used in a hierarchy.
> However, all key fields that are not included in the mapping will be automatically added as hierarchies.

This new hierarchy is an [analysis hierarchy](https://docs.activeviam.com/engine/java-sdk/6.2/cube/analysis_hierarchies.md). Its members match the records of
the `category` field in the `hobbies` store.

The created hierarchy can be configured similarly to a single-level hierarchy.
For more information, see [here](https://docs.activeviam.com/engine/java-sdk/6.2/copper/copper_hierarchies.md#hierarchy-metadata).

## Advanced topics

### Joining without mapping

In some cases, you may want to join a store to a cube without mapping any field.
This is possible by calling `joinToCube()` without any call to `withMapping()`.

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
final CopperStore store = Copper.store("hobbies").joinToCube();
```

The defined operation is sometimes referred to as `CROSS JOIN`.
As a result, hierarchies corresponding to all key fields in the datastore will be created.
If the joined store is an append-only store (a store without a primary key), all the fields are considered as part
of the *effective* primary key of the store.

### Multiple join

With the Copper API it is possible to join the same store of the datastore to the same cube with multiple join operations, as long as the join operations,
defined by the `CopperStore` object are different.

This means the same stores can be joined differently inside the same cube, for example by using different fields in the mapping, or
simply by using a different join type:

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
final CopperStore STORE_BUY =
    Copper.store("rates")
        .joinToCube(UnlinkedCopperStore.JoinType.INNER)
        .withMapping(
            "currency", new LevelIdentifier("buy_currency", "buy_currency", "buy_currency"));
final CopperStore STORE_SELL =
    Copper.store("rates")
        .joinToCube(UnlinkedCopperStore.JoinType.INNER)
        .withMapping(
            "currency", new LevelIdentifier("sell_currency", "sell_currency", "sell_currency"));
final CopperStore STORE_BUY_LEFT =
    Copper.store("rates")
        .joinToCube(UnlinkedCopperStore.JoinType.LEFT)
        .withDefaultValue(FieldPath.of("rate"), 1.0)
        .withDefaultValue(FieldPath.of("bank_change_commission"), 0.1)
        .withMapping(
            "currency", new LevelIdentifier("buy_currency", "buy_currency", "buy_currency"));
final CopperStore STORE_SELL_LEFT =
    Copper.store("rates")
        .joinToCube(UnlinkedCopperStore.JoinType.LEFT)
        .withDefaultValue(FieldPath.of("rate"), 1.0)
        .withDefaultValue(FieldPath.of("bank_change_commission"), 0.05)
        .withMapping(
            "currency", new LevelIdentifier("sell_currency", "sell_currency", "sell_currency"));
```

The previous block showcases four different join operations between a FOREX "rates" store and a cube (different join types and different mappings).
Each of the `CopperStore` instances created can be used independently to define its own measures and analysis hierarchies.

Note that the computations will also be independently created and performed.
Therefore, querying measures requiring the execution of multiple joins will impact the join computation time with linear cost.

### How to read the same store through independent joins

Hierarchies and measure attached to equal `CopperStore`s are computed together. The join group is part of the identity of the `CopperStore`,
so the group can be used to make 2 hierarchies/measures independent.
Without join groups, two hierarchies cannot use the same field of the same join: Copper rejects them with an error stating that only one hierarchy is allowed to use a given field.

Join groups, available from Atoti Server 6.2.3, make joins of the same store independent from each other, like two aliases of the same table in a SQL self-join.
Call `withJoinGroup(String)` on the joined store to put it in a named group:

* Hierarchies and measures built on stores of the same group read the same record of the joined store.
* Hierarchies and measures built on stores of different groups are independent.

Use join groups when the same field of a store must feed several hierarchies that users select independently.
For example, consider a store of parameter values, such as bucketing matrices, that is joined to the cube without mapping.
Two parameter hierarchies on the same `matrix` field let a user pick matrix A for one and matrix B for the other.
Without join groups, both hierarchies read the same record, so selecting A on one and B on the other returns nothing.

The following examples use the `hobbies` store of the [many-to-many use case](#use-case-many-to-many-relationship), where Lukas has the hobbies `piano` (category `art`, budget 4.0) and `soccer` (category `sport`, budget 3.0).
They show the crossjoin of two hierarchies built on the same joined store, first in the same group, then in different groups.

#### Hierarchies in the same group

The `hobby` and `category` hierarchies are built on stores of the same group, so they read the same record of the `hobbies` store.
The crossjoin only returns the combinations that exist together in a record:

```mdx theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
SELECT
  {[Measures].[budget]} ON COLUMNS,
  {[hobby].[hobby].[hobby].[piano], [hobby].[hobby].[hobby].[soccer]}
    * {[category].[category].[category].[art], [category].[category].[category].[sport]} ON ROWS
FROM [C]
```

Result:

| | budget |
| - | - |
| piano / art | 4.0 |
| piano / sport | |
| soccer / art | |
| soccer / sport | 3.0 |

#### Hierarchies in different groups

The `first_hobby` and `second_hobby` hierarchies are built on stores of different groups, so they are independent.
The crossjoin returns every combination, and each measure reads the group of its own hierarchy:

```mdx theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
SELECT
  {[Measures].[first_budget], [Measures].[second_budget]} ON COLUMNS,
  {[first_hobby].[first_hobby].[first_hobby].[piano], [first_hobby].[first_hobby].[first_hobby].[soccer]}
    * {[second_hobby].[second_hobby].[second_hobby].[piano], [second_hobby].[second_hobby].[second_hobby].[soccer]} ON ROWS
FROM [C]
```

Result:

| | first\_budget | second\_budget |
| - | - | - |
| piano / piano | 4.0 | 4.0 |
| piano / soccer | 4.0 | 3.0 |
| soccer / piano | 3.0 | 4.0 |
| soccer / soccer | 3.0 | 3.0 |

Here, `first_budget` is the budget of the hobby selected in `first_hobby`, and `second_budget` the budget of the hobby selected in `second_hobby`.

#### Rules

The following rules apply to join groups:

* A store on which `withJoinGroup()` is never called, or on which it is called with `null`, belongs to the default group. This is the behavior of joins without groups.
* A measure belongs to the group of the store it is built from. A measure can only be used in one group.
* Each group is a separate join operation, as described in [Multiple join](#multiple-join). Expect one extra read of the joined store per group, which means one more SQL query per group with DirectQuery.
* `withJoinGroup()` copies the default values of the store it is called on. Defaults set with `withDefaultValue()` before calling `withJoinGroup()` are inherited by every group created from that store, whereas defaults set after apply to that group only.

> [!NOTE]
>
> If the joined store has a key field that is neither mapped nor used by a hierarchy, Copper creates an implicit single-level hierarchy on it for each join. It is a regular hierarchy of the cube, visible and usable in queries.
> In the default group, the dimension and the hierarchy are named after the field, for example `tenor`.
> In a named group, they are named `field (group)`, for example `tenor (first)` and `tenor (second)` for the groups `first` and `second`. The level keeps the field name, so the MDX unique name of the level is `[tenor (first)].[tenor (first)].[tenor]`.
> Each group therefore gets its own implicit hierarchy and the groups do not clash.
> To choose the names yourself, publish a hierarchy on that key field in each group. It replaces the implicit hierarchy.
> The examples above do this with `first_hobby` and `second_hobby`: `hobby` is a key field of the `hobbies` store that is not part of the mapping.

### Using multiple stores with Datastore references

It is possible to access data from multiple isolated stores if they are linked together with datastore references:

Let's say that we separate the hobbies store into two stores: **hobbies** and **hobbyDetails**.

**hobbies**:

| **userName (K)** | **hobby (K)** |
| - | - |
| Marion | dance |
| Roger | tennis |
| Nathan | tennis |
| Lukas | piano |
| Lukas | soccer |
| Romain | piano |

**hobbyDetails**:

| **hobby (K)** | **budget** | **category** |
| - | - | - |
| dance | 1.0 | art |
| tennis | 2.0 | sport |
| piano | 4.0 | art |
| soccer | 3.0 | sport |

If the datastore description declares a reference between two isolated stores, as represented below:

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
StartBuilding.reference()
    .fromStore("hobbies")
    .toStore("hobbyDetails")
    .withName("hobbiesToHobbyDetails")
    .withMapping("hobby", "hobby")
    .build();
```

It will be then possible to use the fields of the referenced store when defining join operations, by using the field's expression rather than using its name:

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
Copper.sum(store.field(FieldPath.of("hobbiesToHobbyDetails", "budget")))
    .withName("budget")
    .publish(context);
Copper.newHierarchy("category")
    .fromField(store.field(FieldPath.of("hobbiesToHobbyDetails", "category")))
    .publish(context);
```

### Performance considerations about join operations

Copper joins define a many-to-many relationship between the cube facts and the records of a store isolated from the selection.

> [!WARNING]
>
> Querying a measure that uses data from the joined store requires computing the join operation at query time, as the many-to-many
> relationship must be resolved to return the corresponding data, since it is not materialized in the stores.

Using a join-related measure impacts query performance. This is because at every query runtime the many-to-many relationship needs to be resolved. The cost of this resolution is proportional to the number of queried locations in the largest partition of the cube's aggregate provider, multiplied by the size of the largest partition of the isolated store.

If both the aggregate provider and the isolated store have large, similarly-sized partitions, the time spent resolving the join can significantly impact overall query computation time.

One way to reduce this cost is to align the partitioning of the aggregate provider and the joined store at a finer granularity. This helps because the join is resolved asynchronously, partition by partition, across the cube and the isolated store.

If performance remains an issue after these optimizations, consider "flattening" the many-to-many joined data, fully materializing the existing many-to-many combinations inside the base store schema. Once the joined store is merged into the base store, the join operation is no longer needed. However, this significantly increases the datastore's size, and therefore the application's RAM requirement.

### Copper join optimization

This is an experimental query-planning optimization that speeds up Copper joins that have a selective filter on the joined (right) table.
The feature was introduced in Atoti 6.2.0 and is disabled by default.

Without it, the `Direct Join` algorithm scans both tables in full before joining. With the feature enabled, the optimizer can instead choose a `Runtime Filtering Join`. It scans the right table first, builds a dynamic filter from that result, and uses the filter to prune the left table's scan before joining. This avoids a full scan of the left table when the right-table filter is selective. The optimizer selects the algorithm automatically per query, falling back to `Direct Join` when `Runtime Filtering Join` is not safe or not beneficial. No code change is required.

To activate it, set the JVM system property `activeviam.feature.experimental.fast_copper_join.enabled` to `true` (for example, `-Dactiveviam.feature.experimental.fast_copper_join.enabled=true`).

The `Runtime Filtering Join` is not used, and `Direct Join` applies instead, when any of the following conditions are met:

* A left join where rows without a match in the right table still need to appear in the result with their default value. The runtime filter cannot guarantee these rows are kept, so it is not used.
* The join doesn't create an analysis hierarchy and only computes a join measure. With no hierarchy to restrict which rows to keep, the runtime filter is not used.
* There is no predicate on the joined table to propagate. In this case, runtime filtering does not bring any improvement.
