Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

@DynamoDbSecondaryPartitionKey and @DynamoDbSecondarySortKey annotations have no effect on table.createTable() #3923

Closed
acouvreur opened this issue Apr 20, 2023 · 7 comments
Assignees
Labels
bug This issue is a bug. dynamodb-enhanced p2 This is a standard priority issue

Comments

@acouvreur
Copy link
Contributor

Describe the bug

Given the following class with two simple enums (Status and CommandType):

@DynamoDbBean
@Getter
@Setter
public class Command {

    public static final String COMMANDS_BY_STATUS = "commands_by_status";
    public static final String COMMANDS_BY_TYPE = "commands_by_type";

    private UUID id;
    private Status status;
    private CommandType type;

    @DynamoDbPartitionKey
    public UUID getId() {
        return id;
    }

    @DynamoDbSecondaryPartitionKey(indexNames = COMMANDS_BY_STATUS)
    public Status getStatus() {
        return this.status;
    }

    @DynamoDbSortKey
    @DynamoDbSecondarySortKey(indexNames = {COMMANDS_BY_STATUS, COMMANDS_BY_TYPE})
    public CommandType getType() {
        return this.type;
    }

And another service in charge of the initialization of this specific bean:

@Service
public class DynamoDbService {
    private static final TableSchema<Command> tableSchema = TableSchema.fromBean(Command.class);
    private final DynamoDbTable<Command> table;
    private final DynamoDbClient client;
    private final String tableName;

    @Autowired
    public DynamoDbService(DynamoDbEnhancedClient enhancedClient, DynamoDbClient client, DynamoDbTableNameResolver resolver) {
        this.client = client;
        this.tableName = resolver.resolve(Command.class);
        this.table = enhancedClient.table(tableName, tableSchema);
    }

    @PostConstruct
    public void createTableIfNotExists() {
        if (!this.tableExists(tableName)) {
            table.createTable()
        }
    }
}

The call to TableSchema.fromBean(Command.class); produces the following table metadata with the index by name map like:
image

Right here I can see the the schema correctly scans the annotations.


When calling table.createTable(), the following thing happens:

It makes a calls to

@Override
public void createTable() {
createTable(CreateTableEnhancedRequest.builder().build());
}

Which then goes all the way down with the default empty request to software.amazon.awssdk.enhanced.dynamodb.internal.operations.CreateTableOperation.java.

In the generateRequest you have the following piece of code:

String primaryPartitionKey = tableSchema.tableMetadata().primaryPartitionKey();
Optional<String> primarySortKey = tableSchema.tableMetadata().primarySortKey();
Set<String> dedupedIndexKeys = new HashSet<>();
dedupedIndexKeys.add(primaryPartitionKey);
primarySortKey.ifPresent(dedupedIndexKeys::add);
List<software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndex> sdkGlobalSecondaryIndices = null;
List<software.amazon.awssdk.services.dynamodb.model.LocalSecondaryIndex> sdkLocalSecondaryIndices = null;
if (this.request.globalSecondaryIndices() != null) {
sdkGlobalSecondaryIndices =
this.request.globalSecondaryIndices().stream().map(gsi -> {
String indexPartitionKey = tableSchema.tableMetadata().indexPartitionKey(gsi.indexName());
Optional<String> indexSortKey = tableSchema.tableMetadata().indexSortKey(gsi.indexName());
dedupedIndexKeys.add(indexPartitionKey);
indexSortKey.ifPresent(dedupedIndexKeys::add);
return software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndex
.builder()
.indexName(gsi.indexName())
.keySchema(generateKeySchema(indexPartitionKey, indexSortKey.orElse(null)))
.projection(gsi.projection())
.provisionedThroughput(gsi.provisionedThroughput())
.build();
}).collect(Collectors.toList());
}

As you can see:

  • sdkGlobalSecondaryIndices is initialized to null
  • sdkLocalSecondaryIndices is initialized to null

And the following call

if (this.request.globalSecondaryIndices() != null) {

Directly checks the empty default request.

It does not check for the table schema metadata on secondary indices.

Expected Behavior

I'd expect the @DynamoDbSecondaryPartitionKey and @DynamoDbSecondarySortKey annotations to be used when calling table.createTable() from the table schema of the same bean.

Current Behavior

The current call to table.createTable() produces the following schema:

{
  "AttributeDefinitions": [
    {
      "AttributeName": "id",
      "AttributeType": "S"
    },
    {
      "AttributeName": "type",
      "AttributeType": "S"
    }
  ],
  "TableName": "local_command",
  "KeySchema": [
    {
      "AttributeName": "id",
      "KeyType": "HASH"
    },
    {
      "AttributeName": "type",
      "KeyType": "RANGE"
    }
  ],
  "TableStatus": "ACTIVE",
  "CreationDateTime": "2023-04-20T13:40:20.610Z",
  "ProvisionedThroughput": {
    "LastIncreaseDateTime": "1970-01-01T00:00:00.000Z",
    "LastDecreaseDateTime": "1970-01-01T00:00:00.000Z",
    "NumberOfDecreasesToday": 0,
    "ReadCapacityUnits": 0,
    "WriteCapacityUnits": 0
  },
  "TableSizeBytes": 0,
  "ItemCount": 0,
  "TableArn": "arn:aws:dynamodb:ddblocal:000000000000:table/local_command",
  "BillingModeSummary": {
    "BillingMode": "PAY_PER_REQUEST",
    "LastUpdateToPayPerRequestDateTime": "2023-04-20T13:40:20.610Z"
  }
}

If you look closely at my description of the issue, I explain how I searched for the payload crafting.

Reproduction Steps

Create the @DynamoDbBean from my example and try to create the table from the schema.

Possible Solution

The fix is counter intuitive because of how I expected the annotations to work.

I just used the createTable method with the request argument to produce the following:

if (!this.tableExists(tableName)) {
        Projection all = Projection.builder()
                .projectionType(ProjectionType.ALL)
                .build();

        table.createTable(r -> {
                r.globalSecondaryIndices(
                EnhancedGlobalSecondaryIndex.builder()
                        .indexName(COMMANDS_BY_STATUS)
                        .projection(all)
                        .build(),
                EnhancedGlobalSecondaryIndex.builder()
                        .indexName(COMMANDS_BY_TYPE)
                        .projection(all)
                        .build()
                );
        });
}

Which produces the final and expected schema on DynamoD:

{
  "AttributeDefinitions": [
    {
      "AttributeName": "id",
      "AttributeType": "S"
    },
    {
      "AttributeName": "type",
      "AttributeType": "S"
    },
    {
      "AttributeName": "status",
      "AttributeType": "S"
    }
  ],
  "TableName": "local_command",
  "KeySchema": [
    {
      "AttributeName": "id",
      "KeyType": "HASH"
    },
    {
      "AttributeName": "type",
      "KeyType": "RANGE"
    }
  ],
  "TableStatus": "ACTIVE",
  "CreationDateTime": "2023-04-20T13:46:23.072Z",
  "ProvisionedThroughput": {
    "LastIncreaseDateTime": "1970-01-01T00:00:00.000Z",
    "LastDecreaseDateTime": "1970-01-01T00:00:00.000Z",
    "NumberOfDecreasesToday": 0,
    "ReadCapacityUnits": 0,
    "WriteCapacityUnits": 0
  },
  "TableSizeBytes": 0,
  "ItemCount": 0,
  "TableArn": "arn:aws:dynamodb:ddblocal:000000000000:table/local_command",
  "BillingModeSummary": {
    "BillingMode": "PAY_PER_REQUEST",
    "LastUpdateToPayPerRequestDateTime": "2023-04-20T13:46:23.072Z"
  },
  "GlobalSecondaryIndexes": [
    {
      "IndexName": "commands_by_status",
      "KeySchema": [
        {
          "AttributeName": "status",
          "KeyType": "HASH"
        },
        {
          "AttributeName": "type",
          "KeyType": "RANGE"
        }
      ],
      "Projection": {
        "ProjectionType": "ALL",
      },
      "IndexStatus": "ACTIVE",
      "ProvisionedThroughput": {
        "ReadCapacityUnits": 0,
        "WriteCapacityUnits": 0
      },
      "IndexSizeBytes": 0,
      "ItemCount": 0,
      "IndexArn": "arn:aws:dynamodb:ddblocal:000000000000:table/local_command/index/commands_by_status"
    },
    {
      "IndexName": "commands_by_type",
      "KeySchema": [
        {
          "AttributeName": "id",
          "KeyType": "HASH"
        },
        {
          "AttributeName": "type",
          "KeyType": "RANGE"
        }
      ],
      "Projection": {
        "ProjectionType": "ALL",
      },
      "IndexStatus": "ACTIVE",
      "ProvisionedThroughput": {
        "ReadCapacityUnits": 0,
        "WriteCapacityUnits": 0
      },
      "IndexSizeBytes": 0,
      "ItemCount": 0,
      "IndexArn": "arn:aws:dynamodb:ddblocal:000000000000:table/local_command/index/commands_by_type"
    }
  ]
}

Additional Information/Context

No response

AWS Java SDK version used

2.20.30

JDK version used

18.0.2

Operating System and version

MacOS M1 (13.3.1)

@acouvreur acouvreur added bug This issue is a bug. needs-triage This issue or PR still needs to be triaged. labels Apr 20, 2023
@debora-ito
Copy link
Member

@acouvreur I see how this is counter intuitive. Thank you for reaching out.

@debora-ito debora-ito added dynamodb-enhanced needs-review This issue or PR needs review from the team. p2 This is a standard priority issue and removed needs-triage This issue or PR still needs to be triaged. needs-review This issue or PR needs review from the team. labels Apr 20, 2023
@breader124
Copy link
Contributor

Hi, is it open for contributions? If so, could you please assign it to me? I'd like to help

@acouvreur
Copy link
Contributor Author

Hi, is it open for contributions? If so, could you please assign it to me? I'd like to help

The fix seems straightforward, but the annotation still lacks configuration on the projection though.

@debora-ito
Copy link
Member

@breader124 yes, assigned you to the issue.

breader124 pushed a commit to breader124/aws-sdk-java-v2 that referenced this issue May 13, 2023
* detect and group indices present in table schema into LSIs and GSIs
* pass request with indices information appended further
breader124 pushed a commit to breader124/aws-sdk-java-v2 that referenced this issue Jun 2, 2023
* If there's no information about the billing mode of the new table,
  then it'll be using the PAY_PER_REQUEST one. It means that all
  GSIs related to this table will be doing the same and there's
  no need to hard code any provisioned throughput like it was done
breader124 added a commit to breader124/aws-sdk-java-v2 that referenced this issue Jun 8, 2023
* CreateTableRequest cannot handle empty list of indices of any type. It
  throws exception when given such a list. At the same time, it nicely
  handles the cases when indices lists are null. Make sure then that
  when empty indices list is passed CreateTableOperation, then in the
  CreateTableRequest it's just reflected as null.
L-Applin added a commit that referenced this issue Jun 14, 2023
* Create secondary indices based on table bean annotations (#3923)

* detect and group indices present in table schema into LSIs and GSIs
* pass request with indices information appended further

* Remove specifying provisioned throughput for GSIs (#3923)

* If there's no information about the billing mode of the new table,
  then it'll be using the PAY_PER_REQUEST one. It means that all
  GSIs related to this table will be doing the same and there's
  no need to hard code any provisioned throughput like it was done

* Allow passing empty indices list to CreateTableOperation (#3923)

* CreateTableRequest cannot handle empty list of indices of any type. It
  throws exception when given such a list. At the same time, it nicely
  handles the cases when indices lists are null. Make sure then that
  when empty indices list is passed CreateTableOperation, then in the
  CreateTableRequest it's just reflected as null.

---------

Co-authored-by: Adrian Chlebosz <[email protected]>
Co-authored-by: Olivier L Applin <[email protected]>
@debora-ito
Copy link
Member

Feature implemented and released in SDK version 2.20.86.

@github-actions
Copy link

⚠️COMMENT VISIBILITY WARNING⚠️

Comments on closed issues are hard for our team to see.
If you need more assistance, please open a new issue that references this one.
If you wish to keep having a conversation with other community members under this issue feel free to do so.

davidh44 added a commit that referenced this issue Jun 21, 2023
* Fixed issue with leased connection leaks when threads executing HTTP … (#4066)

* Fixed issue with leased connection leaks when threads executing HTTP connections with Apache HttpClient were interrupted while the connection was in progress.

* Added logic in MakeHttpRequestStage to check and abort request if interrupted

* Add test cases for UrlConnectionHttpClient

* Moved the fix to AfterTransmissionExecutionInterceptorsStage to just close the stream instaed of aborting the reqyest in MakeHttpRequestStage

* Removing test cases related to UrlConnectionHttp since adding depenency in protocol-test for urlConnectionClient cause failues since it uses default Client all the places

* Updated after Zoe's comments

* Now it's possible to configure NettyNioAsyncHttpClient for non blocking DNS (#3990)

* Now it's possible to configure NettyNioAsyncHttpClient in order to use a
non blocking DNS resolver.

* Add package mapping for netty-resolver-dns.

---------

Co-authored-by: Matthew Miller <[email protected]>

* Amazon Connect Service Update: This release adds search APIs for Prompts, Quick Connects and Hours of Operations, which can be used to search for those resources within a Connect Instance.

* AWS Certificate Manager Private Certificate Authority Update: Document-only update to refresh CLI documentation for AWS Private CA. No change to the service.

* Release 2.20.83. Updated CHANGELOG.md, README.md and all pom.xml.

* Add "unsafe" AsyncRequestBody constructors for byte[] and ByteBuffers (#3925)

* Update to next snapshot version: 2.20.84-SNAPSHOT

* Use WeakHashMap in IdleConenctionReaper  (#4087)

* Use WeakHashMap in IdleConenctionReaper to not prevent connection manager from getting GC'd

* Checkstyle fix

* Update S3IntegrationTestBase.java (#4079)

* Amazon Rekognition Update: This release adds support for improved accuracy with user vector in Amazon Rekognition Face Search. Adds new APIs: AssociateFaces, CreateUser, DeleteUser, DisassociateFaces, ListUsers, SearchUsers, SearchUsersByImage. Also adds new face metadata that can be stored: user vector.

* Amazon DynamoDB Update: Documentation updates for DynamoDB

* Amazon FSx Update: Amazon FSx for NetApp ONTAP now supports joining a storage virtual machine (SVM) to Active Directory after the SVM has been created.

* Amazon SageMaker Service Update: Sagemaker Neo now supports compilation for inferentia2 (ML_INF2) and Trainium1 (ML_TRN1) as available targets. With these devices, you can run your workloads at highest performance with lowest cost. inferentia2 (ML_INF2) is available in CMH and Trainium1 (ML_TRN1) is available in IAD currently

* AWS Amplify UI Builder Update: AWS Amplify UIBuilder is launching Codegen UI, a new feature that enables you to generate your amplify uibuilder components and forms.

* Amazon OpenSearch Service Update: This release adds support for SkipUnavailable connection property for cross cluster search

* Amazon DynamoDB Streams Update: Documentation updates for DynamoDB Streams

* Updated endpoints.json and partitions.json.

* Release 2.20.84. Updated CHANGELOG.md, README.md and all pom.xml.

* Update to next snapshot version: 2.20.85-SNAPSHOT

* docs: add scrocquesel as a contributor for code (#4091)

* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

---------

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
Co-authored-by: Debora N. Ito <[email protected]>

* AWS CloudTrail Update: This feature allows users to view dashboards for CloudTrail Lake event data stores.

* AWS WAFV2 Update: You can now detect and block fraudulent account creation attempts with the new AWS WAF Fraud Control account creation fraud prevention (ACFP) managed rule group AWSManagedRulesACFPRuleSet.

* AWS Well-Architected Tool Update: AWS Well-Architected now supports Profiles that help customers prioritize which questions to focus on first by providing a list of prioritized questions that are better aligned with their business goals and outcomes.

* Amazon Lightsail Update: This release adds pagination for the Get Certificates API operation.

* Amazon Verified Permissions Update: GA release of Amazon Verified Permissions.

* EC2 Image Builder Update: Change the Image Builder ImagePipeline dateNextRun field to more accurately describe the data.

* Amazon CodeGuru Security Update: Initial release of Amazon CodeGuru Security APIs

* Amazon Simple Storage Service Update: Integrate double encryption feature to SDKs.

* Elastic Disaster Recovery Service Update: Added APIs to support network replication and recovery using AWS Elastic Disaster Recovery.

* AWS SimSpace Weaver Update: This release fixes using aws-us-gov ARNs in API calls and adds documentation for snapshot APIs.

* AWS SecurityHub Update: Add support for Security Hub Automation Rules

* Amazon Elastic Compute Cloud Update: This release introduces a new feature, EC2 Instance Connect Endpoint, that enables you to connect to a resource over TCP, without requiring the resource to have a public IPv4 address.

* Updated endpoints.json and partitions.json.

* Release 2.20.85. Updated CHANGELOG.md, README.md and all pom.xml.

* Update to next snapshot version: 2.20.86-SNAPSHOT

* Create secondary indices based on table bean annotations (#3923) (#4004)

* Create secondary indices based on table bean annotations (#3923)

* detect and group indices present in table schema into LSIs and GSIs
* pass request with indices information appended further

* Remove specifying provisioned throughput for GSIs (#3923)

* If there's no information about the billing mode of the new table,
  then it'll be using the PAY_PER_REQUEST one. It means that all
  GSIs related to this table will be doing the same and there's
  no need to hard code any provisioned throughput like it was done

* Allow passing empty indices list to CreateTableOperation (#3923)

* CreateTableRequest cannot handle empty list of indices of any type. It
  throws exception when given such a list. At the same time, it nicely
  handles the cases when indices lists are null. Make sure then that
  when empty indices list is passed CreateTableOperation, then in the
  CreateTableRequest it's just reflected as null.

---------

Co-authored-by: Adrian Chlebosz <[email protected]>
Co-authored-by: Olivier L Applin <[email protected]>

* Add EnhancedType parameters to static builder methods of StaticTableSchema and StaticImmitableTableSchema (#4077)

* Amazon Elastic File System Update: Documentation updates for EFS.

* Amazon GuardDuty Update: Updated descriptions for some APIs.

* Amazon Location Service Update: Amazon Location Service adds categories to places, including filtering on those categories in searches. Also, you can now add metadata properties to your geofences.

* AWS Audit Manager Update: This release introduces 2 Audit Manager features: CSV exports and new manual evidence options. You can now export your evidence finder results in CSV format. In addition, you can now add manual evidence to a control by entering free-form text or uploading a file from your browser.

* Updated endpoints.json and partitions.json.

* Release 2.20.86. Updated CHANGELOG.md, README.md and all pom.xml.

* Update to next snapshot version: 2.20.87-SNAPSHOT

* EnumAttributeConverter: enums can be identified by toString() or name(). toString() is the default for backward compatibility (#3971)

Co-authored-by: Zoe Wang <[email protected]>

* AWS Application Discovery Service Update: Add Amazon EC2 instance recommendations export

* AWS Account Update: Improve pagination support for ListRegions

* Amazon Simple Storage Service Update: This release adds SDK support for request-payer request header and request-charged response header in the "GetBucketAccelerateConfiguration", "ListMultipartUploads", "ListObjects", "ListObjectsV2" and "ListObjectVersions" S3 APIs.

* Amazon Connect Service Update: Updates the *InstanceStorageConfig APIs to support a new ResourceType: SCREEN_RECORDINGS to enable screen recording and specify the storage configurations for publishing the recordings. Also updates DescribeInstance and ListInstances APIs to include InstanceAccessUrl attribute in the API response.

* AWS Identity and Access Management Update: Documentation updates for AWS Identity and Access Management (IAM).

* Release 2.20.87. Updated CHANGELOG.md, README.md and all pom.xml.

* Update to next snapshot version: 2.20.88-SNAPSHOT

* Fix the StackOverflowException in WaiterExecutor in case of large retries count. (#3956)

* Move checksum calculation from afterMarshalling to modifyHttpRequest (#4108)

* Update HttpChecksumRequiredInterceptor

* Update HttpChecksumInHeaderInterceptor

* Update tests and remove constant

* Add back constant to resolve japicmp

* Add back javadocs

* docs: add dave-fn as a contributor for code (#4092)

* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

* Removing unnecessary vscode file

---------

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
Co-authored-by: Debora N. Ito <[email protected]>

* Amazon Route 53 Domains Update: Update MaxItems upper bound to 1000 for ListPricesRequest

* Amazon EC2 Container Service Update: Documentation only update to address various tickets.

* AWS CloudFormation Update: Specify desired CloudFormation behavior in the event of ChangeSet execution failure using the CreateChangeSet OnStackFailure parameter

* AWS Price List Service Update: This release updates the PriceListArn regex pattern.

* AWS Glue Update: This release adds support for creating cross region table/database resource links

* Amazon Elastic Compute Cloud Update: API changes to AWS Verified Access to include data from trust providers in logs

* Amazon SageMaker Service Update: Amazon Sagemaker Autopilot releases CreateAutoMLJobV2 and DescribeAutoMLJobV2 for Autopilot customers with ImageClassification, TextClassification and Tabular problem type config support.

* Release 2.20.88. Updated CHANGELOG.md, README.md and all pom.xml.

* Update to next snapshot version: 2.20.89-SNAPSHOT

* AWS Lambda Update: This release adds RecursiveInvocationException to the Invoke API and InvokeWithResponseStream API.

* AWS Config Update: Updated ResourceType enum with new resource types onboarded by AWS Config in May 2023.

* Amazon Appflow Update: This release adds new API to reset connector metadata cache

* Amazon Elastic Compute Cloud Update: Adds support for targeting Dedicated Host allocations by assetIds in AWS Outposts

* Amazon Redshift Update: Added support for custom domain names for Redshift Provisioned clusters. This feature enables customers to create a custom domain name and use ACM to generate fully secure connections to it.

* Updated endpoints.json and partitions.json.

* Release 2.20.89. Updated CHANGELOG.md, README.md and all pom.xml.

* Update to next snapshot version: 2.20.90-SNAPSHOT

* Move QueryParametersToBodyInterceptor to front of interceptor chain (#4109)

* Move QueryParametersToBodyInterceptor to front of interceptor chain

* Move customization.config interceptors to front of interceptor chain - for query protocols

* Refactoring

* Add codegen tests

* Refactoring

* Refactoring

---------

Co-authored-by: John Viegas <[email protected]>
Co-authored-by: Martin <[email protected]>
Co-authored-by: Matthew Miller <[email protected]>
Co-authored-by: AWS <>
Co-authored-by: aws-sdk-java-automation <[email protected]>
Co-authored-by: Stephen Flavin <[email protected]>
Co-authored-by: Zoe Wang <[email protected]>
Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
Co-authored-by: Debora N. Ito <[email protected]>
Co-authored-by: Adrian Chlebosz <[email protected]>
Co-authored-by: Adrian Chlebosz <[email protected]>
Co-authored-by: Olivier L Applin <[email protected]>
Co-authored-by: Benjamin Maizels <[email protected]>
Co-authored-by: flitt <[email protected]>
L-Applin added a commit that referenced this issue Jul 24, 2023
* Create secondary indices based on table bean annotations (#3923)

* detect and group indices present in table schema into LSIs and GSIs
* pass request with indices information appended further

* Remove specifying provisioned throughput for GSIs (#3923)

* If there's no information about the billing mode of the new table,
  then it'll be using the PAY_PER_REQUEST one. It means that all
  GSIs related to this table will be doing the same and there's
  no need to hard code any provisioned throughput like it was done

* Allow passing empty indices list to CreateTableOperation (#3923)

* CreateTableRequest cannot handle empty list of indices of any type. It
  throws exception when given such a list. At the same time, it nicely
  handles the cases when indices lists are null. Make sure then that
  when empty indices list is passed CreateTableOperation, then in the
  CreateTableRequest it's just reflected as null.

---------

Co-authored-by: Adrian Chlebosz <[email protected]>
Co-authored-by: Olivier L Applin <[email protected]>
@sraji
Copy link

sraji commented Sep 11, 2024

I am running into an issue with creating secondary index. If anyone is familiar with the fix, can I get some help please.

Error:
Attempt to execute an operation that requires a secondary index without defining the index attributes in the table metadata. Index name: ByChannelContextId

UserBotDao.kt

@DynamoDbBean
data class UserBotDao(
    @get:DynamoDbPartitionKey
    @get:DynamoDbAttribute("userId")
    var userId: String? = null,

    @get:DynamoDbSortKey
    @get:DynamoDbAttribute("providerType")
    var providerType: String? = null,

    @get:DynamoDbSecondaryPartitionKey(indexNames = ["ByChannelContextId"])
    @get:DynamoDbAttribute("channelContextId")
    var channelContextId: String? = null,

    @get:DynamoDbUpdateBehavior(UpdateBehavior.WRITE_IF_NOT_EXISTS)
    @get:DynamoDbAttribute("create_at")
    var createdAt: Long = Instant.now().epochSecond,

    @get:DynamoDbUpdateBehavior(UpdateBehavior.WRITE_ALWAYS)
    @get:DynamoDbAttribute("update_at")
    var updatedAt: Long = Instant.now().epochSecond,

    @get:DynamoDbAttribute("created_by")
    var createdBy: String? = null,

    @get:DynamoDbAttribute("updated_by")
    var updatedBy: String? = null
)
val all = Projection.builder()
            .projectionType(ProjectionType.ALL)
            .build()

        // Define the table schema
        val tableSchema = TableSchema.fromBean(clazz)
        logger.info("Creating table $tableName with schema $tableSchema")
        val table = client.table(tableName, tableSchema)

        table.createTable { r: CreateTableEnhancedRequest.Builder ->
            r.globalSecondaryIndices(
                EnhancedGlobalSecondaryIndex.builder()
                    .indexName("ByChannelContextId")
                    .projection(all)
                    .build()
            )
        }
        ```

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug This issue is a bug. dynamodb-enhanced p2 This is a standard priority issue
Projects
None yet
Development

No branches or pull requests

4 participants