> ## 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.

# DirectQuery

Atoti Market Data provides a way to store various types of market data and retrieve it, efficiently, during a query. These retrievals are executed as
Get-by-key or List queries on the individual market data tables. In the course of a complex calculation, such as PnL Explain, there may be many thousands of
these queries.

With an in-memory Atoti application, the datastore is highly optimized to handle these operations and, even with high volumes, they are
executed quickly. However, in an Atoti application using DirectQuery, each of these queries must be executed on the external database.
This may mean many thousands of database queries over a network, which will drastically slow any user workflows.

The [DirectQuery Local Cache](https://docs.activeviam.com/engine/java-sdk/6.2/directquery/directquery_local_cache.md)
is a solution to this problem. Atoti Market Data is designed to work with this cache.

Please see the [DirectQuery Local Cache Atoti documentation](https://docs.activeviam.com/engine/java-sdk/6.2/directquery/directquery_local_cache.md)
to understand how the cache works, and for details on how to use it in an Atoti application. For this guide, we will assume you have read the documentation,
and you are using the cache in your project.

## Concepts

### Filling the cache

Each of the non-abstract [post-processors](https://docs.activeviam.com/solutions/libraries/market-data/1.5/postprocessors.md) in Atoti Market Data are configured to use the cache.

If these post-processors are part of your query, they will submit a request to fill the cache with market data during the prefetch phase. When they later run
Get-by-key or List queries, these queries will use the cached data, improving retrieval speed.

### Cache Partitions

A fundamental aspect of the DirectQuery Local Cache design is the use of partitions. A cache does not contain the entire underlying table but instead holds only
a subset, i.e., a partition. Partitions are configurable per cache.

In the case of Atoti Market Data, a partition is defined as a unique combination of `AsOfDate`, and `MarketDataSet`.
This means that when Atoti Market Data is used to retrieve a market data value, the cache will be filled with all market data values related to the AsOfDate
and MarketDataSet for the request.
Any subsequent requests for values with the same AsOfDate and MarketDataSet will be retrieved from the cache, making them significantly faster.

### Why do previous-day and next-day retrievals still query the database?

To retrieve market data for the previous or next date, Atoti Market Data first queries all the distinct `AsOfDate` values of the market data table.
The cache cannot answer this query, so it is sent to the database, once per query for each market data table involved.
This is a known issue.

## Set up

### Cache descriptions

To cache data from a table, you must provide a [cache description](https://docs.activeviam.com/engine/java-sdk/6.2/directquery/how_to/define_and_use_cache.md#how-to-define-a-local-cache) when the application starts.

For each [market data store](./data-model/stores) there is a corresponding [configuration class](https://docs.activeviam.com/solutions/libraries/market-data/1.5/config-classes.md#directquery)
that exposes a `SingleTableCacheDescription` bean. These classes are available in the `market-data-config` module. These beans should be collected and used when configuring your Atoti application.

Each cache description is created with a [cache capacity](https://docs.activeviam.com/engine/java-sdk/6.2/directquery/how_to/define_and_use_cache.md#eviction-policy),
which determines the maximum number of rows or partitions to keep in the cache. You can configure the cache capacity by exposing a supplier bean for the relevant cache.

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
@Configuration
@Import({
        // The cache configuration of each store the application uses.
        CubeMarketDataDirectQueryCacheConfig.class,
        CurveMarketDataDirectQueryCacheConfig.class,
        FxRateMarketDataDirectQueryCacheConfig.class,
        SpotMarketDataDirectQueryCacheConfig.class,
        SurfaceMarketDataDirectQueryCacheConfig.class
})
public class CacheDescriptionConfig {
    // The capacity of the cube cache, read by CubeMarketDataDirectQueryCacheConfig.
    @Bean
    public CubeMarketDataDirectQueryCacheConfig.CacheCapacitySupplier cubeCacheCapacitySupplier() {
        return () -> CacheCapacity.MaxPartitionsCount.of(6);
    }
    // The capacity of the curve cache, read by CurveMarketDataDirectQueryCacheConfig.
    @Bean
    public CurveMarketDataDirectQueryCacheConfig.CacheCapacitySupplier curveCacheCapacitySupplier() {
        return () -> CacheCapacity.MaxPartitionsCount.of(4);
    }
    // The capacity of the FX rate cache, read by FxRateMarketDataDirectQueryCacheConfig.
    @Bean
    public FxRateMarketDataDirectQueryCacheConfig.CacheCapacitySupplier fxRateCacheCapacitySupplier() {
        return () -> CacheCapacity.MaxPartitionsCount.of(4);
    }
    // The capacity of the spot cache, read by SpotMarketDataDirectQueryCacheConfig.
    @Bean
    public SpotMarketDataDirectQueryCacheConfig.CacheCapacitySupplier spotCacheCapacitySupplier() {
        return () -> CacheCapacity.MaxPartitionsCount.of(2);
    }
    // The capacity of the surface cache, read by SurfaceMarketDataDirectQueryCacheConfig.
    @Bean
    public SurfaceMarketDataDirectQueryCacheConfig.CacheCapacitySupplier surfaceCacheCapacitySupplier() {
        return () -> CacheCapacity.MaxPartitionsCount.of(10);
    }
}
```

### DatabaseCacheManager injection

Each of the non-abstract [post-processors](https://docs.activeviam.com/solutions/libraries/market-data/1.5/postprocessors.md) in Atoti Market Data is configured to use the cache but, to do so, they must be injected with the [IDatabaseCacheManager](https://docs.activeviam.com/engine/java-sdk/6.2/directquery/how_to/define_and_use_cache.md#how-to-use-the-cache-manager).

There is a [configuration class](https://docs.activeviam.com/solutions/libraries/market-data/1.5/config-classes.md#directquery) in `market-data-config` that will inject the `IDatabaseCacheManager` into all relevant
post-processors. You can import this class in your project, and you must also expose `IDatabaseCacheManager` as a bean.

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
@Configuration
@Import({
        // Injects the cache manager into the post-processors that use the cache.
        DatabaseCacheManagerInjectionConfig.class
})
public class PostProcessorCacheConfig {
    // The cache manager that DatabaseCacheManagerInjectionConfig injects.
    @Bean
    public IDatabaseCacheManager databaseCacheManager(IDirectQueryDatabase database) {
        return database.getCacheManager();
    }
}
```

### AllMarketDataDirectQueryConfig

The `market-data-config` includes an `AllMarketDataDirectQueryConfig` class that will import the cache descriptions for all stores, and the post-processor
injection configuration.

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
@Configuration
@Import({
        // The cache descriptions of all stores, and the injection of the cache manager.
        AllMarketDataDirectQueryConfig.class
})
public class AtotiMarketDataCacheConfig {
    // The cache manager that AllMarketDataDirectQueryConfig injects.
    @Bean
    public IDatabaseCacheManager databaseCacheManager(IDirectQueryDatabase database) {
        return database.getCacheManager();
    }
    // The capacity of the cube cache, read by CubeMarketDataDirectQueryCacheConfig.
    @Bean
    public CubeMarketDataDirectQueryCacheConfig.CacheCapacitySupplier cubeCacheCapacitySupplier() {
        return () -> CacheCapacity.MaxPartitionsCount.of(6);
    }
    // The capacity of the curve cache, read by CurveMarketDataDirectQueryCacheConfig.
    @Bean
    public CurveMarketDataDirectQueryCacheConfig.CacheCapacitySupplier curveCacheCapacitySupplier() {
        return () -> CacheCapacity.MaxPartitionsCount.of(4);
    }
    // The capacity of the FX rate cache, read by FxRateMarketDataDirectQueryCacheConfig.
    @Bean
    public FxRateMarketDataDirectQueryCacheConfig.CacheCapacitySupplier fxRateCacheCapacitySupplier() {
        return () -> CacheCapacity.MaxPartitionsCount.of(4);
    }
    // The capacity of the spot cache, read by SpotMarketDataDirectQueryCacheConfig.
    @Bean
    public SpotMarketDataDirectQueryCacheConfig.CacheCapacitySupplier spotCacheCapacitySupplier() {
        return () -> CacheCapacity.MaxPartitionsCount.of(2);
    }
    // The capacity of the surface cache, read by SurfaceMarketDataDirectQueryCacheConfig.
    @Bean
    public SurfaceMarketDataDirectQueryCacheConfig.CacheCapacitySupplier surfaceCacheCapacitySupplier() {
        return () -> CacheCapacity.MaxPartitionsCount.of(10);
    }
}
```

## Advanced customization

If you are using the default Atoti Market Data stores and post-processors, simply follow the [Set up](#set-up) steps to start caching market data. If you
have made customizations or are not using all the components of Atoti Market Data you may need to make further changes.

### Cache partition customizations

A [cache partition](#cache-partitions) is defined as a combination of `AsOfDate` and `MarketDataSet` for all Atoti Market Data stores. We believe this
provides the best [level of granularity](https://docs.activeviam.com/engine/java-sdk/6.2/directquery/directquery_local_cache.md#partitioning-fields-considerations)
for most projects.

If, however, you require a different partitioning, you must define your own cache definition for the table. Be sure not to also import the provided
[cache config](#cache-descriptions) class.

`AS_OF_DATE` in the cache descriptions below is a constant of `MarketDataConstants`.

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
@Configuration
public class CustomCubeMarketDataDirectQueryCacheConfig {
    // A cache description for the cube store, with custom partitioning fields.
    @Bean
    public SingleTableCacheDescription cubeStoreCacheDescription(@Qualifier("cubeMarketDataStore") IStoreDescription store) {
        return SingleTableCacheDescription.builder()
                .tableName(store.getName())
                .cachePartitioningFields(List.of(AS_OF_DATE, "Custom"))
                .capacity(CacheCapacity.MaxPartitionsCount.of(6))
                .build();
    }
}
```

The [post-processors](https://docs.activeviam.com/solutions/libraries/market-data/1.5/postprocessors.md) in Atoti Market Data are designed to work with the default [cache descriptions](#cache-descriptions) and the
partitioning they define. They extract the `AsOfDate` and `MarketDataSet` from the location and use this to feed the cache.
If you change the partitioning, the post-processors will need to be updated. This is done by extending the post-processor and overriding the `getConverter` method.

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
@AtotiExtendedPluginValue(intf = IPostProcessor.class, key = CustomCubeMarketDataPostProcessor.PLUGIN_KEY)
public class CustomCubeMarketDataPostProcessor extends CubeMarketDataPostProcessor {
    public static final String PLUGIN_KEY = "CustomCubeMarketDataPostProcessor";
    public CustomCubeMarketDataPostProcessor(String name, IPostProcessorCreationContext creationContext) {
        super(name, creationContext);
    }
    // Reads the cache partition of a location from the levels of the custom partitioning fields.
    @Override
    public ILocationToCachePartitionConverter getConverter(Properties properties) {
        return new BestEffortLocationToCachePartitionConverter(List.of(
                new LevelIdentifier("Dates", "Date", "AsOfDate"),
                new LevelIdentifier("Custom", "Custom", "Custom")));
    }
    @Override
    public String getType() {
        return PLUGIN_KEY;
    }
}
```

The post-processor has its own plugin key, so the application injects the `IMarketDataRetrievalContainerService` under that key:

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
@Configuration
@AllArgsConstructor
public class CustomCubeMarketDataPostProcessorInjectionConfig {
    private final IMarketDataRetrievalContainerService<IDefaultMarketDataRetriever> containerService;
    @EventListener
    @Order(MarketDataPostProcessorInjectionConstants.DEFAULT_ORDER)
    public void injectIntoCustomCubeMarketDataPostProcessor(final ContextRefreshedEvent ignored) {
        ExtendedPluginInjector.inject(IPostProcessor.class, CustomCubeMarketDataPostProcessor.PLUGIN_KEY,
                IMarketDataRetrievalContainerServiceAware.PROPERTY_NAME, containerService);
    }
}
```

Measures that use the post-processor are built with [`MarketDataMeasureBuilderHelper`](./postprocessors#marketdatameasurebuilderhelper) and its plugin
key, `new MarketDataMeasureBuilderHelper<Double>(CustomCubeMarketDataPostProcessor.PLUGIN_KEY, CUBE_MARKET_DATA_RETRIEVER)`, with the levels that
`CubeMarketDataMeasureBuilder` takes. `CubeMarketDataMeasureBuilder` builds its measures with the plugin key of `CubeMarketDataPostProcessor`.

### Store customizations

The [cache descriptions](#cache-descriptions) are configured based on the default structure of the underlying store. Most importantly, they require that the
store has an `AsOfDate`, and a `MarketDataSet` field as these are used for the [cache partitions](#cache-partitions).

If you have customized the store and these fields are no longer present, you must define your own cache definition for the table and update relevant post-processors.
This follows the same steps as to [modify the cache partitioning](#cache-partition-customizations).

### New stores and post-processors

If you write new post-processors, you will need to ensure these are set up to work with the cache.

If the new post-processor is retrieving market data from a custom store, you will need to provide your own cache description for the store.

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
@Configuration
public class CustomDirectQueryCacheConfig {
    @Bean
    public SingleTableCacheDescription customStoreCacheDescription() {
        return SingleTableCacheDescription.builder()
                .tableName("CustomMarketDataStore")
                .cachePartitioningFields(List.of(AS_OF_DATE, "Custom"))
                .capacity(CacheCapacity.MaxPartitionsCount.of(6))
                .build();
    }
}
```

Your custom post-processors are responsible for filling the cache as described in the [Atoti documentation](https://docs.activeviam.com/engine/java-sdk/6.2/directquery/how_to/define_and_use_cache.md#prefetch-a-cache-partition-in-a-post-processor-advanced).
We offer two classes to help with this.

`ADirectQueryCachingMarketDataPostProcessor` is an abstract class that configures a `DatabaseCachePrefetcher` for you.
It uses `getMarketDataRetrievalContainer().retriever().getTableName()` as the name of the cache, and it assumes the cache partitioning uses
`AsOfDate` and `MarketDataSet`, taking these levels from the first two entries of `LEVELS_PROPERTY`. To partition by other levels, override
`getCachePartitioningLevels(Properties)`.

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
@AtotiExtendedPluginValue(intf = IPostProcessor.class, key = CustomMarketDataPostProcessor.PLUGIN_KEY)
public class CustomMarketDataPostProcessor extends ADirectQueryCachingMarketDataPostProcessor<IDefaultMarketDataRetriever> {
    public static final String PLUGIN_KEY = "CustomMarketDataPostProcessor";
    public CustomMarketDataPostProcessor(String name, IPostProcessorCreationContext creationContext) {
        super(name, creationContext);
    }
    @Override
    protected IDefaultContextualMarketDataRetriever getMarketDataRetriever(ILocation location) {
        var container = getMarketDataRetrievalContainer();
        return new SingleContextualMarketDataRetriever<>(container.name(), container.coordinateTranslator(), container.retriever());
    }
    @Override
    public String getType() {
        return PLUGIN_KEY;
    }
}
```

If your post-processor does not meet the requirements of `ADirectQueryCachingMarketDataPostProcessor`, for instance, you have a different cache partitioning,
you can instead implement the `IDirectQueryCachingPostProcessor` interface.

By implementing `IDirectQueryCachingPostProcessor`, your post-processor will be injected with the `IDatabaseCacheManager`
(provided you import the [injection configuration class](#databasecachemanager-injection)) and there is a helper method to add the `DatabaseCachePrefetcher`.
However, you must specify the cache name and the converter.

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
@AtotiExtendedPluginValue(intf = IPostProcessor.class, key = CustomPartitioningMarketDataPostProcessor.PLUGIN_KEY)
public class CustomPartitioningMarketDataPostProcessor extends APropertyMarketDataPostProcessor<IDefaultMarketDataRetriever>
        implements IDirectQueryCachingPostProcessor {
    public static final String PLUGIN_KEY = "CustomPartitioningMarketDataPostProcessor";
    // The cache manager, with the getter and setter that its injection uses.
    @Getter @Setter protected IDatabaseCacheManager databaseCacheManager;
    public CustomPartitioningMarketDataPostProcessor(String name, IPostProcessorCreationContext creationContext) {
        super(name, creationContext);
    }
    @Override
    public List<IPrefetcher<?>> initializePrefetchers(Properties properties) {
        var prefetchers = super.initializePrefetchers(properties);
        return addDatabaseCachePrefetcher(prefetchers, properties, getActivePivot());
    }
    @Override
    public String getCacheName(Properties properties) {
        return "CustomMarketDataStore";
    }
    // Reads the cache partition of a location from the levels of the partitioning fields of the cache.
    @Override
    public ILocationToCachePartitionConverter getConverter(Properties properties) {
        return new BestEffortLocationToCachePartitionConverter(List.of(
                new LevelIdentifier("Dates", "Date", "AsOfDate"),
                new LevelIdentifier("Custom", "Custom", "Custom")));
    }
    @Override
    protected IDefaultContextualMarketDataRetriever getMarketDataRetriever(ILocation location) {
        var container = getMarketDataRetrievalContainer();
        return new SingleContextualMarketDataRetriever<>(container.name(), container.coordinateTranslator(), container.retriever());
    }
    @Override
    public String getType() {
        return PLUGIN_KEY;
    }
}
```

Both post-processors find their retriever with `getMarketDataRetrievalContainer()`, so each needs the `IMarketDataRetrievalContainerService` injected
under its plugin key, as for the [custom partitioning post-processor](#cache-partition-customizations).
