In DynamoDB, when using Number in KeyConditionExpression, it is interpreted as a Map which can lead to unexpected

Setting

In my TypeScript CDK project, I am dealing with the QueryInput-Object. The code snippet below shows how it's being used:

const params: QueryInput = {
    TableName: criticalMessagesTableName,
    ProjectionExpression: 'message',
    KeyConditionExpression: 'myId = :myId and #ts BETWEEN :startTimestamp AND :endTimestamp',

    ExpressionAttributeValues: {
        ':myId': { S: myId },
        ':startTimestamp': { N: String(startTimestamp) },
        ':endTimestamp': { N: String(startTimestamp + range - 1) },
    },
    ExpressionAttributeNames: {
        '#ts': 'timestamp',
    },
};

These are the values of the variables:

const myId = "some-string-based-partition-key-value";
const startTimestamp = 1630927923544; //ms since epoch value
const range = 60000; // some range in ms

The partition key of the table is myId (String) and the sort key is timestamp (Number).

Issue

Upon executing the query with an AWS.DynamoDB.DocumentClient instance, the error log points to the following problem:

{
"message": "Invalid KeyConditionExpression: Incorrect operand type for operator or function; operator or function: BETWEEN, operand type: M",
"code": "ValidationException",
"time": "2021-09-06T12:18:33.720Z",
"requestId": "M041V4RVD57IGRGNF7P7U15GRNVV4KQNSO5AEMVJF66Q9ASUAAJG",
"statusCode": 400,
"retryable": false,
"retryDelay": 43.99195146574429

}

It appears that the :startTimestamp and :endTimestamp are being interpreted as a map, leading to the error message. Any insights on this issue would be greatly appreciated.

Unfortunately, using <= and > as a workaround is not feasible due to the limitation of one operator per key in a KeyConditionExpression.

Any assistance or guidance on this specific to TypeScript documentation would be highly valuable.

Answer №1

If you are utilizing the AWS.DynamoDB.DocumentClient, you'll notice a key distinction from its relative, AWS.DynamoDB. The former employs native JavaScript types rather than encasing them within an AttributeValue map. As a result, your query should be structured in the following manner:

const params: QueryInput = {
    // ...
    ExpressionAttributeValues: {
        ':myId': myId,
        ':startTimestamp': startTimestamp,
        ':endTimestamp': startTimestamp + range - 1,
    }

To delve deeper into this topic, refer to the API documentation for the document client linked here (specifically focusing on the section "Marshalling Input and Unmarshalling Response Data"): https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging AWS CDK to seamlessly integrate an established data pipeline into your infrastructure

I currently have a data pipeline set up manually, but now I want to transition to using CDK code for management. How can I achieve this using the AWS CDK TypeScript library to locate and manage this data pipeline? For example, with AWS SNS, we can utilize ...

The output from the second request using RxJS

I am facing an issue with returning an Observable from the second request. Here is the scenario I am encountering: commandRequest(action:string, commandData:any):Observable<CashDesckResponse> { let command:CashDeskRequest; //ask my backend f ...

Executing a TypeScript file in Sublime Text

Is there a way to compile a TypeScript file (.ts) in the sublime text 3 console and display the output similarly to how sublime handles Python? Since TypeScript is a compiled language, it needs to convert the .ts file to a .js file before execution. How ca ...

Using @HostBinding based on the @Input() condition

I'm attempting to link the CSS class foo to my parent component by utilizing @HostBinding based on a condition I evaluate against a dynamic variable. However, I am struggling to get it to function as expected. Here are the different approaches I hav ...

Operators within an observable that perform actions after a specific duration has elapsed

Is there a way in an rxjs observable chain to perform a task with access to the current value of the observable after a specific time interval has elapsed? I'm essentially looking for a functionality akin to the tap operator, but one that triggers onl ...

Ways to pass functions as properties to a React custom modal?

I'm currently working on a React login page setup. The login functionality is embedded in a Modal using the React-Modal library. When a user presses the login button, data is supposed to be sent to a Custom Modal as props to display a notification win ...

In TypeScript, fetch JSON data from a URL and gain access to an array of JSON objects

I'm struggling to find a solution and implement it in the correct format. An API returns a JSON file to me via a URL. The format is as follows: {"success":true, "data":[ { "loadTimestamp":"2022-07-20T ...

Encountering issues with compiling files in react app using webpack, failing to compile as anticipated

When it comes to compiling, I prefer using webpack with TypeScript files. In my webpack.config.js file: module.exports = async (env, options) => { const dev = options.mode === "development"; const config = { //Webpack configuration pr ...

How can you typically verify the type of an object variable in TypeScript?

How can I verify if the obj variable contains all the properties defined in the Person interface? interface Person { name: string; age: number; } const jsonObj = `{ name: "John Doe", age: 30, }`; const obj: Person = JSON.parse(jsonObj); ...

` Detecting initialized properties of classes using Eslint rule`

When useDefineForClassFields:true is used, the code below becomes invalid when targeting es2022: Cannot read properties of undefined (reading 'array') class Bar { array = new Array(); } class Foo { foo = this.bar.array; // Property &apo ...

What purpose does the # symbol serve in Angular when interpolating values?

Here is an example provided from the following link: https://angular.io/guide/lifecycle-hooks export class PeekABoo implements OnInit { constructor(private logger: LoggerService) { } // Implementing OnInit's `ngOnInit` method ngOnInit() { this ...

When converting to a React Functional Component using Typescript, an error occurred: The property 'forceUpdateHandler' could not be found on the type 'MutableRefObject<Spinner | null>'

Looking to convert the App component in this CodePen into a Functional component using Typescript. Encountering an error when attempting to run it: ERROR in src/App.tsx:13:14 TS2339: Property 'forceUpdateHandler' does not exist on type 'Mu ...

How can I store various data types in a single array in TypeScript?

I have a scenario I need help with. Let's say we have two interfaces, Cats and Dogs. How can I create an array that can store both Cats and Dogs? interface Cats { name: string; age: number; } interface Dog { owner: string; } const cat1: Cat ...

Angular compilation encounters errors

While following a tutorial from Angular University, I encountered an issue where running ng serve/npm start would fail. However, simply re-saving any file by adding or removing a blank space would result in successful compilation. You can view the screensh ...

Compatibility issues arise with static properties in three.d.ts when using the most recent version of TypeScript

When compiling three.d.ts (which can be found at this link) using the TypeScript develop branch, an error occurs with the following message: Types of static property 'Utils' of class 'THREE.Shape' and class 'THREE.Path' are i ...

Converting a string into a TypeScript class identifier

Currently, I am dynamically generating typescript code and facing an issue with quotes in my output: let data = { path: 'home', component: '${homeComponentName}', children:[] }; let homeComponentName = 'HomeComponent' ...

Group data by two fields with distinct values in MongoDB

I have developed a Typescript Node.js application and I am looking to organize documents by two fields, "one_id" and "two_id", based on a specific "one_id" value. Below is the data within my collection: { "_id":"5a8b2953007a1922f00124fd", "one_id ...

How can I test for equality with an array item using v-if in Vue.js?

Currently, I am facing a challenge in my Vue.js project where I need to determine if a number is equal to an element within an array. Here is the code snippet that I am working with: <div v-if="someValue != arrayElement"> // </div> I am st ...

The operation of the "CheckFileSystemCaseSensitive" task has encountered an unexpected failure. It was unable to load the file or assembly 'System.IO.FileSystem'

I recently upgraded my Visual Studio 2017 ASP.NET Core MVC web project by adding the Microsoft.TypeScript.MSBuild NuGet package v2.3.1 and updating my ASP.NET Core assemblies from 1.0.* to 1.1.1. However, after these changes, I encountered a new exception ...

Encountering a NPM error when trying to launch the server using ng serve

I encountered an error : ERROR in /opt/NodeJS/FutureDMS/src/app/app.module.ts (5,9): Module '"/opt/NodeJS/FutureDMS/src/app/app.routing"' has no exported member 'APP_ROUTE'. Within my code, I have utilized arrow function in the loadCh ...