0

I can't figure out the correct syntax to perform a scan and filter on a table. I want to filter on books written after 2018.

Given this book model:

import { attribute, hashKey, rangeKey, table } from '@aws/dynamodb-data-mapper-annotations';

@table('book')
export class Book {
    @hashKey()
    isbn?: string;

    @rangeKey()
    written?: string; // an ISO-8601 string, e.g. 2020-05-30T16:34:20.985Z

    @attribute()
    title?: string;
}

My scan query filter:

mapper.scan(Book, { filter: '> 2018' }); // what goes here?

Unfortunantly, I get this TypeScript error:

Type 'string' is not assignable to type '(ConditionExpressionSubject & EqualityExpressionPredicate) | (ConditionExpressionSubject & InequalityExpressionPredicate) | ... 15 more ... | undefined'.

What is the correct filter syntax?

2 Answers 2

0

The AWS DynamoDB lib documentation is terrible but I ended up figuring it out:

import { ConditionExpression } from '@aws/dynamodb-expressions';

// ... later in the file ...

const dateFilter: ConditionExpression = {
    type: 'GreaterThanOrEqualTo',
    subject: 'written',
    object: '2018'
};

const paginator = mapper.scan(Book, { filter: dateFilter });
for await (const book of paginator) {
    console.log(book); // book available here
}
Sign up to request clarification or add additional context in comments.

Comments

0

The filter option must be a ConditionExpression type. According to the official docs, the scan method of mapper takes 1 to 2 arguments. The first argument is the class you want to map to your record in Dynamodb. The second argument takes some options. Filter is one of those options.

The syntax:

    const exp1: ConditionExpression = {
      type: string,
      subject: string,
      object: string
    }

Perform the scan operation:

    mapper.scan(MyClass, {filter: exp1})

If you have more than one condition, you can combine those conditions with compound expressions.

    const exp2: ConditionExpression = {
      type: string,
      subject: string,
      object: string
    }

    const compoundExp: ConditionExpression = {
      type: "And" | "Or" | "Not",
      conditions: [exp1, exp2]
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.