I'm trying to query by a field of a Interleaved table using Spring Data Spanner. The id comparison is automatically done by Spring Data Spanner when it does the ARRAY STRUCT inner join, but I'm not being able to add a WHERE clause to the Interleaved table query.
Considering the example below:
CREATE TABLE Singers (
Id INT64 NOT NULL,
FirstName STRING(1024),
LastName STRING(1024),
SingerInfo BYTES(MAX),
) PRIMARY KEY (Id);
CREATE TABLE Albums (
SingerId INT64 NOT NULL,
Id INT64 NOT NULL,
AlbumTitle STRING(MAX),
) PRIMARY KEY (SingerId, Id),
INTERLEAVE IN PARENT Singers ON DELETE CASCADE;
Let's suppose I want to query all Singers where the AlbumTitle is "Fear of the Dark", how can I write a repository method to achieve that using Spring Data Spanner?
You're example seems to either contain a couple of typos, or it is otherwise not completely correct:
Idwhich is the primary key. That is in itself fine, but when creating a hierarchy of interleaved tables, it is recommended to prefix the primary key column with the table name. So it would be better to name itSingerId.Albumstable has aSingerIdcolumn and anIdcolumn. These two columns form the primary key of theAlbumstable. This is technically incorrect (and confusing), and also the reason that I think that your example is not completely correct. BecauseAlbumsis interleaved inSingers,Albumsmust contain the same primary key columns as theSingerstable, in addition to any additional columns that form the primary key ofAlbums. In this caseIdreferences theSingerstable, and theSingerIdis an additional column in theAlbumstable that has nothing to do with theSingerstable. The primary key columns of the parent table must also appear in the same order as in the parent table.The example data model should therefore be changed to:
From this point on you can consider the
SingerIdcolumn in theAlbumstable as a foreign key relationship to aSingerand treat it as you would in any other database system. Note also that there can be multiple albums for each singer, so a query for ...I want to query all Singers where the AlbumTitle is "Fear of the Dark" is slightly ambiguous. I would rather say:Give me all singers that have at least one album with the title "Fear of the Dark"
A valid query for that would be: