How to query last inserted item? #340
-
I have the following entity and I would like to query the last inserted item, when we don't particularly know the primary key.
Scan doesn't work for me: |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Hi @meightythree 👋 Two things here: Thing 1Your syntax is nearly correct, the correct syntax would be the following: await MyEntity.scan.go({ limit: 1, order: 'desc' }); The Thing 2I'm glad you shared your full intent because I don't believe this query will actually get you what you need 😱 Unfortunately it is a DynamoDB thing (not an ElectroDB thing), but scan actually does not guarantee any return order for the items in response 👎 Order is only guaranteed when you query within a partition, and only if your table has a sort key. Easiest way to accomplish this would be to change your model and table schema to be something like the below model, but if you expect high throughput you may need to consider a more robust approach to prevent hot partitions: import { Entity, EntityItem } from 'electrodb';
import { Table } from 'sst/node/table';
import { dynamoDBClient } from 'core/db';
export const MyEntity = new Entity(
{
model: {
entity: 'myEntity',
version: '1',
service: 'myService',
},
attributes: {
dateId: {
type: 'string',
required: true,
readOnly: true,
},
base: {
type: 'string',
readOnly: true,
required: true,
},
// other attributes...
},
indexes: {
myEntity: {
sk: {
field: 'sk',
composite: ['dateId'],
},
pk: {
field: 'pk',
composite: [],
},
},
},
},
{
client: dynamoDBClient,
table: Table.myEntity.tableName,
}
); |
Beta Was this translation helpful? Give feedback.
Hi @meightythree 👋
Two things here:
Thing 1
Your syntax is nearly correct, the correct syntax would be the following:
The
params
andgo
methods are two ways to terminate an operation (terminal methods). Theparams
terminal method synchronously returns DynamoDB JSON parameters for a given operation, while thego
terminal method executes the operation. In the above example I would either callparams
orgo
but not both. You can find more information about those methods here: https://electrodb.dev/en/core-concepts/executing-queries/#execution-methodsThing 2
I'm glad you shared your full intent because I don't believe this query will actual…