On this page

On this page

It is common to define a Global Secondary Index using a KEYS_ONLY projection. This ProjectionType helps keep indexes as small as possible which can reduce cost. Unfortunately, because ElectroDB abstracts away key management, querying this index type with ElectroDB requires unique considerations.

Hydrating Queries

The execution option hydrate can be used instruct ElectroDB to perform a query followed by an immediate batchGet to retrieve each individual item. Hydrate is available when performing query, scan, match, or find operations.

_Note: Without hydration, a KEYS_ONLY index will return empty objects as it only contains the keys, which are not returned by ElectroDB by default. To circumvent this, checkout the Returning Keys section below.

The Entity and Table Definition tabs show the setup this example runs against, and the generated parameters below are produced live by executing the example.

Edit in Playground ↗
import { assets } from "./entity";

// the locations index (gsi1pk-gsi1sk-index) is a KEYS_ONLY projection
const { data, cursor } = await assets.query
  .locations({ state: "Georgia" })
  .go({ hydrate: true });
Generated DynamoDB Parameters
Generating parameters…

Returning Keys

If you do not wish to “hydrate” your query response, you still have ways you can retrieve the keys returned by DynamoDB. The first mechanism is to use the query execution options { data: 'includeKeys' }.

Note: When using typescript these options do not impact the typing of the returned object so this approach may require casting

Include Keys

The query execution options { data: 'includeKeys' } allow you to return keys on the data array.

Edit in Playground ↗
import { assets } from "./entity";

// The elements in the `data` array are just the keys of the index, despite the typing saying otherwise.
const { data, cursor } = await assets.query
  .locations({ state: "Georgia" })
  .go({ data: "includeKeys" });
Generated DynamoDB Parameters
Generating parameters…

Raw Responses

The query execution option { data: 'raw' } will return the raw response from DynamoDB. This is one way you can access the results of a KEYS_ONLY index.

Edit in Playground ↗
import { assets } from "./entity";

// result is the actual DynamoDB response, despite the typing saying otherwise.
const result: any = await assets.query
  .locations({ state: "Georgia" })
  .go({ data: "raw" });
const { Items, LastEvaluatedKey } = result;
Generated DynamoDB Parameters
Generating parameters…

References