Skip to content
For the complete documentation index, see llms.txt. This page is also available as Markdown.

From Key-Value to SQL: The JOIN Problem

Move beyond client-side joins. Annotate POJOs with @QuerySqlField, run SqlFieldsQuery on cached data, and use colocation for fast cross-cache JOINs.

Introduction

A customer support screen shows every invoice for a given customer. A monthly report pulls all orders billed from Brazil. Each screen starts with something you know (a customer ID, a country name) and returns records whose keys you do not know.

Cache API lookups need keys you already have. The Cache API can push a single-cache predicate to the server with ScanQuery and IgniteBiPredicate, and cache.iterator() can return every entry for client-side filtering. Neither helps when the question is "invoices joined to their customers filtered by country and grouped by month." This tutorial teaches the same caches to answer the harder questions with SQL: you load the Chinook music-store dataset (59 customers, 412 invoices) into two caches, ask one concrete question three ways, and finish with a cross-cache JOIN whose EXPLAIN plan shows how colocation keeps the JOIN local.

Prerequisites

This tutorial builds a fresh Maven project called sql-on-cache/. It does not extend the cache-client/ project from the Foundations path because the SQL engine needs the ignite-indexing dependency that the Cache API tutorials did not use.

Returning to these tutorials? Verify your cluster is running.

Check that the cluster container is up:

docker ps --filter name=gridgain8-node1 --format "table {{.Names}}\t{{.Status}}"

Expected output:

NAMES             STATUS
gridgain8-node1   Up X hours

If the container is stopped, restart it:

docker compose -f cache-cluster/docker-compose.yml start

If the cluster was destroyed (docker compose down), recreate it from the cache-cluster Docker Compose in the Foundations path. The cluster runs in-memory, so destroying it discards the cache. Running ConfigureCaches and SeedFromChinook in this tutorial will recreate the caches and reload the dataset.

What You Will Learn

In this tutorial, you:

  • Annotate POJOs with @QuerySqlField so the cache knows which fields are SQL columns

  • Configure two caches with setIndexedTypes to register the SQL schema from the annotations

  • Seed the caches from a Chinook dataset file using SQL INSERT statements through SqlFieldsQuery

  • Answer "find all invoices for customer 17" with the Cache API alone and watch the client-side scan do the wrong thing

  • Replace the scan with a parameterized SqlFieldsQuery and see the filter run server-side on an index

  • Run a cross-cache JOIN between Customer and Invoice and read the H2 EXPLAIN plan that confirms it stayed local

Define the Queryable Schema

Three POJOs carry the schema: Customer, Invoice, and the composite InvoiceKey. Annotations on their fields tell the cache which columns exist, which ones are indexed, and which one drives partitioning.

Create a Maven project called sql-on-cache/. The pom.xml adds two things the Foundations path did not need: the ignite-indexing dependency that brings the H2 SQL engine onto the classpath, and an extra --add-opens entry so the optimized marshaller can read java.sql.Date.

ignite-indexing is new here. The Foundations path used only gridgain-core because none of those tutorials ran SQL. Without ignite-indexing on the classpath, the first call to setIndexedTypes logs a warning, and the first SQL query fails with CacheException: Failed to execute query. Add module 'ignite-indexing' to the classpath of all Ignite nodes.

The extra --add-opens=java.sql/java.sql=ALL-UNNAMED is also new. The optimized marshaller needs reflective access to java.sql.Date when an invoice's invoiceDate field serializes. Under Java 17, the module system forbids that access unless the java.sql module is opened explicitly.

Create the three model classes under src/main/java/com/example/sqlquery/model/:

Three fields, three @QuerySqlField annotations. Every annotated field becomes a SQL column with the same name as the field. Fields without the annotation are still stored on the cache entry, but they are invisible to SQL and cannot appear in SELECT column lists or WHERE predicates. The customerId is the cache key here, not a field. SQL references the cache key through a pseudo-column called _key, which the cross-cache JOIN later in this tutorial uses in its join predicate.

The Invoice POJO carries the fields that change per invoice: the date, the billing country, and the total. It does not carry invoiceId or customerId. Both of those fields live on the composite key class because the cache key in the Invoice cache is a composite of (invoiceId, customerId). Putting customerId on the key lets one annotation do two jobs: drive partitioning so customer 17's invoices live on the same node as customer 17, and expose the field as a SQL column so queries can filter on it.

InvoiceKey is the most concept-dense class in the tutorial. Three annotations across two fields encode three separate decisions:

  • @QuerySqlField on invoiceId surfaces the field as a SQL column. Without the annotation, SELECT invoiceId FROM Invoice fails with Column "INVOICEID" not found.

  • @QuerySqlField(index = true) on customerId does two things at once: surfaces the column to SQL, and tells the SQL engine to maintain an index on it. Queries later in this tutorial filter on this column, and the index is what makes those queries an index scan rather than a table scan.

  • @AffinityKeyMapped on customerId is the colocation declaration. The cache partitions entries by hashing this field, which places every invoice on the same node as the customer whose ID matches. The cross-cache JOIN relies on this. @AffinityKeyMapped alone does not expose the field to SQL, and @QuerySqlField alone does not influence partitioning. Both annotations stack on the colocation key so it does both jobs.

Open InvoiceKey and hover on @AffinityKeyMapped. The IDE's JavaDoc popup names the default affinity mapper that reads the annotation: GridCacheDefaultAffinityKeyMapper. No CacheConfiguration.setAffinityMapper() call is needed to activate it. The mapper is the cluster's default and reflectively inspects every key class for the annotation.

Configure the Caches and Seed the Dataset

The caches need QueryEntity descriptions built from the annotations. After they exist, the Chinook dataset loads into them: 59 customers and 412 invoices.

Create ConfigureCaches.java in com.example.sqlquery:

Compile and run:

Expected output:

Two caches exist. Both have QueryEntity descriptions built from the POJO annotations. Both are ready to accept SQL.

Now populate them. Download the dataset file into the sql-on-cache/ directory so it sits next to the pom.xml:

SeedFromChinook reads the file relative to the JVM's working directory, which is also sql-on-cache/ when you run Maven from there.

The file contains 59 Customer INSERTs and 412 Invoice INSERTs, trimmed from the full Chinook music-store schema to the columns this tutorial queries. The dates use H2's parsedatetime() function because the cached SQL engine is H2.

Create SeedFromChinook.java in the same package:

Run it:

Expected output:

SqlFieldsQuery runs DML, not just SELECT. The count queries also confirm that SQL and the Cache API share one storage. Rows inserted via SQL are the same entries cache.get(1) returns as a Customer POJO.

Look at a Customer INSERT in the dataset file: INSERT INTO Customer (_key, firstName, lastName, country) VALUES (1, 'Luís', 'Gonçalves', 'Brazil');. The _key pseudo-column names the primitive cache key, which is not a field on the Customer POJO. Invoice INSERTs use the named fields directly (INSERT INTO Invoice (invoiceId, customerId, ...) VALUES (...)) because both fields of the composite InvoiceKey are visible as regular SQL columns thanks to @QuerySqlField on the key class.

The Client-Side Filter

The caches hold 59 customers and 412 invoices. Consider the question that opened this tutorial: "find all invoices for customer 17." You know customerId = 17. You do not know the invoice IDs.

The Cache API has two iteration paths. cache.iterator() returns every entry to the client and the filter runs in Java. cache.query(new ScanQuery<>(predicate)) pushes a single-cache IgniteBiPredicate to the server so only matches cross the network. This step uses the first path so the cost of pulling every entry is visible. Later steps move to SQL when the question outgrows a single-cache predicate.

Create ClientSideFilter.java:

Run it:

Expected output:

The invoice dates match the parsedatetime values in the dataset file. A client JVM in a time zone behind the server's can show them one day earlier, because java.sql.Date prints in the client's zone.

Customer 17 has seven invoices, all from the USA. The scanned-count line makes the cost visible: 412 entries crossed the wire, 405 were thrown away. Scale that ratio to millions of entries and the JVM runs out of heap before the scan finishes.

The Cache API can push a server-side predicate over a single cache with ScanQuery and IgniteBiPredicate, which would skip the wasted-entry shipping shown above. What the Cache API cannot do is join two caches in one query, run an aggregation, or accept the composable typed predicates a column-aware engine offers. The annotations you added in the last step gave the cache another way to answer those questions: SQL.

SQL on one Cache

Create IndexedQuery.java. The class runs three queries against the Invoice cache: a parameterized lookup by the indexed customerId, a two-predicate scan, and an aggregation.

Run it:

Expected output:

Query 1 returned the same seven invoices as the client-side scan, but the filter ran on the server against the customerId index. Only matching rows crossed the wire, and the ORDER BY invoiceDate clause also ran server-side.

Query 2 applied two predicates. Neither billingCountry nor total has an index, so H2 scans the Invoice data and applies both conditions as filters during the scan. The predicates compose at the SQL layer in one statement. A Cache API version would need a custom loop evaluating both conditions per entry.

Query 3 is the biggest shift. The cache computed COUNT(*), SUM(total), and MAX(total) for the seven matching invoices and returned one row with three columns. The Cache API has no cache.count(predicate) or cache.sum(field, predicate). Aggregations are a SQL-only surface.

Type new SqlFieldsQuery("SELECT 1"). and let the IDE show the builder methods. Beyond setArgs (used here) the list includes setSchema, setLazy, setDistributedJoins, setPageSize, and setTimeout. Most tutorials use a small subset. The two you are most likely to reach for next are setPageSize(int) for large result sets and setTimeout(int, TimeUnit) for long-running analytical queries.

Cross-Cache JOIN With Colocation

The next question spans two caches: which Brazilian customers have spent the most in total? Country lives on the Customer cache. Invoice totals live on the Invoice cache. One JOIN answers both.

@AffinityKeyMapped on InvoiceKey.customerId already aligns the two caches so each customer's invoices live on the same partition as the customer record. The JOIN below uses that alignment, and the EXPLAIN plan after confirms it.

Create ColocatedJoin.java:

Run it:

Expected output:

Five Brazilian customers ranked by lifetime spend. Luís Gonçalves at $39.62 leads by a narrow margin. The other four tie at $37.62 because their Chinook purchase histories are nearly identical.

The EXPLAIN block shows two distinct SQL statements separated by the second SELECT. That structure is how distributed SQL executes. The first statement is the map phase that runs locally on each partition. The second statement is the reduce phase that runs at a single coordinator to merge the partial results. Read each block separately.

Map phase (runs on each partition):

  • FROM "Invoice"."INVOICE" "I__Z1" scans the local Invoice partition with the comment /* Invoice.INVOICE.__SCAN_ */. The scan is a full read of the partition. This plan does not use the INVOICEKEY_CUSTOMERID_IDX index.

  • INNER JOIN "Customer"."CUSTOMER" "C__Z0" with the comment /* Customer._key_PK: _KEY = I__Z1.CUSTOMERID */ looks up each invoice's customer in the Customer primary-key index. The lookup column is _KEY, the cache key, and it matches the invoice's affinity field customerId. That match is what makes the lookup local: the customer row sits in the same partition as the invoice. The COUNTRY = ?1 predicate is applied to the rows the lookup returns.

  • The critical absence is anything saying "distributed" or "broadcast." The JOIN runs on each partition against the partition's local Invoice and Customer rows. No data moves between partitions.

Reduce phase (runs at the coordinator):

  • FROM "PUBLIC"."__T0" with the comment /* Customer.merge_scan */ is the synthetic table that holds the partial aggregates from every partition's map phase. The coordinator groups them again and produces the final result. Because each partition only sends one small aggregate, the reduce phase stays cheap even for large tables.

Some schemas cannot colocate. Order lines might need to be colocated with orders, not with customers. Product records might be referenced from every order without a natural colocation key. For those cases, SqlFieldsQuery has a setDistributedJoins(true) flag that tells the engine to move data between partitions to resolve the JOIN. The query returns correct results, but the cost model changes. The planner may stream rows between partitions, which is slower than a colocated JOIN. A later guide covers when to reach for the flag.

The latest GridGain 8 version runs the H2 SQL engine.

Summary

You added two annotations and two new calls to a cache you already knew how to use. The cache went from "key lookups only" to "full SQL surface with indexes, aggregations, and cross-cache JOINs."

The shape of the question selects the interface. Lookups by a known key keep using cache.get at in-memory speed. Any predicate on a non-key field, any aggregation, any filter composition, and any JOIN uses SqlFieldsQuery. Both views exist on the same cache, over the same data. The choice is not a storage strategy. It is a query strategy made per call site.

Colocation is a schema-design decision, not a runtime one. Without colocation, a JOIN between two caches returns incomplete results unless you enable setDistributedJoins(true), and with the flag on the cost differs by orders of magnitude because rows move between nodes. @AffinityKeyMapped on the right key turns the JOIN into a local per-partition operation that scales with the number of partitions rather than the size of the data moved between them. Make the colocation decision when you define the cache, not when the query gets slow.

The deeper reframing is that the cache is a distributed database with two access surfaces. Key-value access handles single-key hot paths at in-memory speed. Everything else, filters, aggregations, JOINs, uses SqlFieldsQuery against the same data. One annotation on the POJO and one setIndexedTypes call replace the need for a separate query database alongside the cache.

What's Next

  • setDistributedJoins(true) for the case where colocation is not possible, covered in When to Break Colocation.

  • Secondary indexes and composite (group) indexes. See Defining Indexes.

  • DDL-based cache creation (CREATE TABLE ... WITH "CACHE_NAME=..., VALUE_TYPE=..."), the alternative path that creates caches from SQL instead of Java configuration. See SQL and Key-Value Usage.

The next tutorial in this learning path, Atomic Operations Across Keys: The Transaction Problem, shifts from queries to writes. Cross-partition transactions solve the problem of atomically updating two keys that live on different nodes, a case single-shard txStart() does not cover.

This page is: Copyright © 2026 MariaDB. All rights reserved.

Last updated

Was this helpful?