This example creates a table with a GSI to store students, courses, and their many-to-many relationships. The last query finds all students in course 456 by querying the GSI.
CREATE TABLE School (
PK STRING,
SK STRING,
GSI_PK STRING,
GSI_SK STRING,
Data STRING,
PRIMARY KEY (PK, SK)
);
-- Create Global Secondary Index
CREATE GLOBAL SECONDARY INDEX GSI1 ON School (GSI_PK, GSI_SK);
-- Insert student
INSERT INTO School VALUES ('STUDENT#123', 'METADATA', 'STUDENT#123', 'METADATA', 'Alice');
-- Insert course
INSERT INTO School VALUES ('COURSE#456', 'METADATA', 'COURSE#456', 'METADATA', 'Math 101');
-- Link student to course (query by course)
INSERT INTO School VALUES ('STUDENT#123', 'COURSE#456', 'COURSE#456', 'STUDENT#123', NULL);
-- Link course to student (query by student)
INSERT INTO School VALUES ('COURSE#456', 'STUDENT#123', 'STUDENT#123', 'COURSE#456', NULL);
-- Query all students in course 456
SELECT PK, SK FROM School WHERE GSI_PK = 'COURSE#456' AND GSI_SK <> 'METADATA';