Encounter difficulties with KeyConditionExpression when querying a DynamoDB table

How can I resolve the error below and what is causing "operand type: M" to appear? Despite consulting AWS documentation and searching on stack overflow, I have been unable to find a solution to this issue after spending several hours. My goal is to query an item that is currently active and has a dateSold between a specified start and end date in ISO format. I believe the error "operand type: M" indicates that I am using the map type in my operands such as dateSold, :start, and :end. However, all these operands are simply strings.

The equivalent SQL command would resemble this: SELECT dateSold, profit FROM Items WHERE isActive = 'true' AND dateSold > start AND dateSold < end

Error: "message":"Invalid KeyConditionExpression: Incorrect operand type for operator or function; operator or function: BETWEEN, operand type: M","code":"ValidationException"

Code:

AWS.config.update({ region: "us-east-2" });
    const documentClient = AWS.DynamoDB.DocumentClient({ apiVersion: "2012-08-10" });

    const options = {
        TableName: "Items",
        ProjectionExpression: "dateSold, profit",
        IndexName: "isActive-dateSold-index",
        KeyConditionExpression:
          "isActive = :isActive AND dateSold BETWEEN :start AND :end",
        ExpressionAttributeValues: {
          ":start": { S: start.toISOString() },
          ":end": { S: end.toISOString() },
          ":isActive": { S: "true" },
        },
      }

    const result = await documentClient
      .query(options)
      .promise()

Schema:

Table: {
    AttributeDefinitions: [
    { AttributeName: "dateSold", AttributeType: "S" },
    { AttributeName: "id", AttributeType: "S" },
    { AttributeName: "isActive", AttributeType: "S" },
    ],
    TableName: "Items",
    KeySchema: [{ AttributeName: "id", KeyType: "HASH" }],
    GlobalSecondaryIndexes: [
    {
        IndexName: "isActive-dateSold-index",
        KeySchema: [
        { AttributeName: "isActive", KeyType: "HASH" },
        { AttributeName: "dateSold", KeyType: "RANGE" },
        ],
    },
    ],
},

Answer №1

Your current query includes the following Expression Attribute Values:

ExpressionAttributeValues: {
          ":start": { S: start.toISOString() },
          ":end": { S: end.toISOString() },
          ":isActive": { S: "true" },
        },

It's worth noting that certain DynamoDB SDKs handle type encoding automatically. In some cases, you may not need to explicitly specify { S: start.toISOString() }; simply using start.toIsoString() could suffice. It depends on the specific SDK you are utilizing. For instance, the Python SDK (boto3) handles this automatically.

Additionally, it's interesting how S is used instead of "S" (as a quoted string) in your code. This raises questions about its functionality within your implementation.

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

One cannot initialize an empty object in Typescript

In this scenario, I am working with a variable named 'body' that is initially set to null: const body: { "name": string, "photo": { "fileName": string, "file": NodeJS.ReadableStream, "encoding": string, "m ...

"Error: The method setValue is not found in the AbstractControl type" when trying to clear form in Angular 2

Here is the template code: <form [formGroup]="form" (ngSubmit)="onSubmit(form.value)" novalidate="novalidate"> <textarea [ngClass]="{ 'error': comment }" [formControl]="form.controls['comment']" ...

Uploading Images to Imgur with Angular 4

As a newcomer to TypeScript, I am faced with the challenge of uploading an image to the Imgur API using Angular. Currently, my approach involves retrieving the file from a file picker using the following code: let eventObj: MSInputMethodContext = <MSIn ...

Component remains populated even after values have been reset

My child component is structured as shown below, ChildComponent.html <div> <button type="button" data-toggle="dropdown" aria-haspopup="true" (click)="toggleDropdown()"> {{ selectedItemName }} <span></span> </but ...

Building a Next.js application that supports both Javascript and Typescript

I currently have a Next.js app that is written in Javascript, but I am looking to transition to writing new code in Typescript. To add Typescript to my project, I tried creating a tsconfig.json file at the project root and then ran npm install --save-dev ...

Using `useLocation()` in a React Router SSR setup is restricted to being within the confines of a `<Router>` component

I recently followed the steps outlined in this guide on server-side rendering without a data router to implement server-side rendering for my app. Here is an example of how I set up the StaticRouter: <StaticRouter location={req.url}> <Routes> ...

What is the best way to incorporate an exported TypeScript class into my JavaScript file?

One of my JavaScript files is responsible for uploading a file to Microsoft Dynamics CRM. This particular JavaScript file makes use of RequireJS to reference another JavaScript file. The referenced JavaScript file, in turn, was compiled from multiple Typ ...

Error: Attempting to access property 'prod_id' of an undefined variable

Hi there, I'm encountering an issue and would appreciate some assistance. I need to test a function as shown in the code snippet below: populateForm() { this.activatedRoute.params.subscribe( params => { this.ws.getbyid(params[&a ...

Tips for formatting numbers within a chart

One issue in my chart is that the values are not formatted correctly. For instance, I have a number 15900 and I would like it to be displayed as 15 900 with a space between thousands and hundreds. Below is the code snippet I would like to implement for s ...

Hermes js engine encounters a TypeError when attempting to access the property '__expo_module_name__' of an undefined value

After updating my expo and react native app to the latest version, I encountered a problem that I couldn't find a solution for despite searching on Google. Link to image ...

Error message occurs when using Typescript with es2017 target, indicating a potential need for a loader despite successful project builds in es5

We are working on a typescript react 'main' project. In the package.json file, there is a dependency on another internal library that we utilize. The 'main' project builds successfully when both projects are set to target es5. However, ...

"Encountering issues with Firebase deployment related to function-builder and handle-builder while working with TypeScript

I encountered 4 errors while executing firebase deploy with firebase cloud functions. The errors are originating from files that I didn't modify. node_modules/firebase-functions/lib/function-builder.d.ts:64:136 - error TS2707: Generic type 'Req ...

Using axiosjs to send FormData from a Node.js environment

I am facing an issue with making the post request correctly using Flightaware's API, which requires form data. Since Node does not support form data, I decided to import form-data from this link. Here is how my code looks like with axios. import { Fl ...

Organizing a mat-table by date does not properly arrange the rows

My API retrieves a list of records for me. I would like to display these records sorted by date, with the latest record appearing at the top. However, the TypeScript code I have written does not seem to be ordering my rows correctly. Can anyone assist me ...

Angular: Display an element above and in relation to a button

Before I dive in, let me just mention that I have searched extensively for a solution to my problem without much luck. The issue is describing exactly what I'm trying to accomplish in a way that yields relevant search results. If you're interest ...

Encounter a Config validation error while trying to utilize Nest.js ConfigService within e2e tests

I'm encountering an error despite having the NODE_ENV=development variable in my .env file. The error message reads: ● Test suite failed to run Config validation error: "NODE_ENV" must be one of [development, production] 11 | imports ...

Can a file be transferred from the private path to the document directory?

I wrote this code using the captureVideo() method from the Ionic Native MediaCapture plugin. Here is the file path I obtained: /private/var/mobile/Containers/Data/Application/95DB5A64-700B-4E3D-9C2C-562C46520BEC/tmp/52515367181__BBC39D42-69EC-4384-A36F-7 ...

Can all intervals set within NGZone be cleared?

Within my Angular2 component, I have a custom 3rd party JQuery plugin that is initialized in the OnInit event. Unfortunately, this 3rd party library uses setIntervals extensively. This poses a problem when navigating away from the view as the intervals rem ...

Mapping Form Fields (with Formik)

Currently, the Formik/Yup validation setup in my form is working perfectly: export default function AddUserPage() { const [firstName, setFirstName] = useState(""); const [email, setEmail] = useState(""); return ( <div> <Formik ...

The unspoken rules of exporting and importing in TypeScript

In comparison to Java (as well as other programming languages), TypeScript provides multiple options for exporting and importing entities such as classes, functions, etc. For instance, you have the ability to export numerous classes, constants, functions ...