简体   繁体   中英

One to Many relationship in DynamoDB

I have the following data I want to save in a DynamoDB and I'm not quite sure how to do it in the most smart way.

My clients are connecting to my app via websocket and then "subscribe" to one ticker. But one ticker can have multiple clients subscribed to it.

The problem is: I need to be able to query both ways. My app has to query 1. to which ticker a specific client is subscribed (for example for reconnection purposes or to handle the disconnect script) and 2. which clients are connected to a ticker (to send infos to these clients)

Do I need to use two tables for that or is it possible in one?

Im thankful for every answer. Right now I'm using two tables, one with the columns connectionId (PK), ticker and one with ticker(PK) and clients

You could follow the Single-Table Design and design your table in the following way:

[
    {
        "PK": "SUBSCRIBER#USER_123",
        "SK": "TICKER#TICKER_987",
        [...]
    },
    {
        "PK": "SUBSCRIBER#USER_123",
        "SK": "TICKER#TICKER_654",
        [...]
    },
    {
        "PK": "TICKER#TICKER_999",
        "SK": "CONNECTED#USER_123",
        [...]
    },
    {
        "PK": "TICKER#TICKER_999",
        "SK": "CONNECTED#USER_456",
        [...]
    }
]

The query part could look like that

  1. to which ticker a specific client is subscribed
{
    TableName: 'TABLE',
    KeyConditionExpression: 'PK = :PK',
    ExpressionAttributeValues: {
        ':PK': `SUBSCRIBER#${userId}`
    }
}
  1. which clients are connected to a ticker
{
    TableName: 'TABLE',
    KeyConditionExpression: 'PK = :PK',
    ExpressionAttributeValues: {
        ':PK': `TICKER#${tickerId}`
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM