Nodejs課堂筆記-第五課 在nodejs中使用DynamoDB Local

從博客園搬到了CSDN,具體原因就不明說了,簡單一句話就是原創被當抄襲,這種感覺很不爽。

好了,我們繼續開始學習歷程吧。在第四課中,我們介紹了DynamoDB Local版本的使用方式。這節課中,我們開始在nodejs中使用DynamoDB。

在Amazon的網站中,提供了一個DynamoDB的sample,請看下面:

// Load the SDK and UUID
var AWS = require('aws-sdk');
var uuid = require('node-uuid');

// Create an S3 client
var s3 = new AWS.S3();

// Create a bucket and upload something into it
var bucketName = 'node-sdk-sample-' + uuid.v4();
var keyName = 'hello_world.txt';

s3.createBucket({Bucket: bucketName}, function() {
  var params = {Bucket: bucketName, Key: keyName, Body: 'Hello World!'};
  s3.putObject(params, function(err, data) {
    if (err)
      console.log(err)
    else
      console.log("Successfully uploaded data to " + bucketName + "/" + keyName);
  });
});

這段示例代碼直接使用的DynamoDB Web Service,而不是DynamoDB Local服務。和我們的需求不太一樣,所以再次研究Amazon的API文檔。

看到dynamodb在使用之前需要配置amazon賬戶,點擊這裏查看配置說明。 按照文檔中的說明,我們補充下面的配置代碼:

/* Auth Config */
AWS.config.update({
    aws_access_key_id : "andy-aws-account",
    aws_secret_access_key : "andy-aws-account",
    region : "eu-west-1"
})

在第四課中提到過,當使用local模式時,賬戶信息都會被忽略。因此輸入任意賬戶信息都可以。

下一步就是創建一個指向local的endpoint,我們使用下面代碼進行創建:

dyn= new AWS.DynamoDB({ endpoint: new AWS.Endpoint('http://localhost:8000') });

當endpoint創建成功後,就相當於獲取了一個dynamodb的實例,下面就可以執行SQL操作了。我們首先做一個簡單的操作:創建一張表,再查詢所有表。

在dynamodb的api中,創建表的API是(點擊這裏,查看API文檔):

createTable(params = {}, callback) ⇒ AWS.Request

需要給createTable傳遞一個參數對象,這個參數對象有些複雜:

var params = {
  AttributeDefinitions: [ /* required */
    {
      AttributeName: 'STRING_VALUE', /* required */
      AttributeType: 'S | N | B' /* required */
    },
    /* more items */
  ],
  KeySchema: [ /* required */
    {
      AttributeName: 'STRING_VALUE', /* required */
      KeyType: 'HASH | RANGE' /* required */
    },
    /* more items */
  ],
  ProvisionedThroughput: { /* required */
    ReadCapacityUnits: 0, /* required */
    WriteCapacityUnits: 0 /* required */
  },
  TableName: 'STRING_VALUE', /* required */
  GlobalSecondaryIndexes: [
    {
      IndexName: 'STRING_VALUE', /* required */
      KeySchema: [ /* required */
        {
          AttributeName: 'STRING_VALUE', /* required */
          KeyType: 'HASH | RANGE' /* required */
        },
        /* more items */
      ],
      Projection: { /* required */
        NonKeyAttributes: [
          'STRING_VALUE',
          /* more items */
        ],
        ProjectionType: 'ALL | KEYS_ONLY | INCLUDE'
      },
      ProvisionedThroughput: { /* required */
        ReadCapacityUnits: 0, /* required */
        WriteCapacityUnits: 0 /* required */
      }
    },
    /* more items */
  ],
  LocalSecondaryIndexes: [
    {
      IndexName: 'STRING_VALUE', /* required */
      KeySchema: [ /* required */
        {
          AttributeName: 'STRING_VALUE', /* required */
          KeyType: 'HASH | RANGE' /* required */
        },
        /* more items */
      ],
      Projection: { /* required */
        NonKeyAttributes: [
          'STRING_VALUE',
          /* more items */
        ],
        ProjectionType: 'ALL | KEYS_ONLY | INCLUDE'
      }
    },
    /* more items */
  ],
  StreamSpecification: {
    StreamEnabled: true || false,
    StreamViewType: 'NEW_IMAGE | OLD_IMAGE | NEW_AND_OLD_IMAGES | KEYS_ONLY'
  }
};

嗯。 這裏感覺需要對amazon的文檔做些吐槽。爲啥這個文檔裏面的參數,比如S|B|N是什麼意思,NEW_IMAGE,OLD_IMAGE 是什麼意思也沒有說明。只看上面的說明,感覺跟沒說是一樣的。

再經歷了多次失敗之後,終於寫出了下面驗證通過的param:

/* Create A Table*/
var params = {
    AttributeDefinitions: [ /* required */
        {
            AttributeName: 'ID', /* required */
            AttributeType: 'S' /* required */
        },
        {
            AttributeName: 'NAME', /* required */
            AttributeType: 'S' /* required */
        }
        /* more items */
    ],
    TableName: 'DNMDB', /* required */
    KeySchema: [ /* required */
        {
            AttributeName: 'ID', /* required */
            KeyType: 'HASH' /* required */
        },
        {
            AttributeName: "NAME",
            KeyType: "RANGE"
        }
        /* more items */
    ],
    LocalSecondaryIndexes: [
        {
            IndexName: 'Index1', /* required */
            KeySchema: [ /* required */
                {
                    AttributeName: 'ID', /* required */
                    KeyType: 'HASH' /* required */
                },
                {
                    AttributeName: 'NAME', /* required */
                    KeyType: 'RANGE' /* required */
                }
                /* more items */
            ],
            Projection: { /* required */
                NonKeyAttributes: [
                    'ID'
                    /* more items */
                ],
                ProjectionType: 'INCLUDE'
            }
        }
        /* more items */
    ],
    StreamSpecification: {
        StreamEnabled: true,
        StreamViewType: 'NEW_IMAGE'
    },
    ProvisionedThroughput: { /* required */
        ReadCapacityUnits: 1, /* required */
        WriteCapacityUnits: 1 /* required */
    },
    GlobalSecondaryIndexes: [
        {
            IndexName: 'GIND1', /* required */
            KeySchema: [ /* required */
                {
                    AttributeName: 'ID', /* required */
                    KeyType: 'HASH' /* required */
                },
                /* more items */
            ],
            Projection: { /* required */
                NonKeyAttributes: [
                    'NAME'
                    /* more items */
                ],
                ProjectionType: 'INCLUDE'
            },
            ProvisionedThroughput: { /* required */
                ReadCapacityUnits: 1, /* required */
                WriteCapacityUnits: 1 /* required */
            }
        }
        /* more items */
    ]
};

然後我們將params傳遞給createTable函數,因爲創建表是異步操作,當開始創建表時,table的狀態會是CREATEING,只有創建完畢之後,纔會變成ACTIVE。
代碼如下:

dyn.createTable(params, function(err, data) {
    if (err) console.log(err, err.stack); // an error occurred
    else     console.log(data);           // successful response
})

而查詢表的API就顯得簡單了

listTables(params = {}, callback) ⇒ AWS.Request

代碼原樣拷貝過來:

dyn.listTables(function (err, data)
{
    console.log('listTables',err,data);
});

OK,一個非常簡單使用DynamoDB Local的demo就完成了,完整代碼如下:

/**
 * Created by andy on 2015/9/11.
 */
var AWS = require('aws-sdk');
var uuid = require('node-uuid');

/* Auth Config */
AWS.config.update({
    aws_access_key_id : "andy-aws-account",
    aws_secret_access_key : "andy-aws-account",
    region : "eu-west-1"
})

dyn= new AWS.DynamoDB({ endpoint: new AWS.Endpoint('http://localhost:8000') });

/* Create A Table*/
var params = {
    AttributeDefinitions: [ /* required */
        {
            AttributeName: 'ID', /* required */
            AttributeType: 'S' /* required */
        },
        {
            AttributeName: 'NAME', /* required */
            AttributeType: 'S' /* required */
        }
        /* more items */
    ],
    TableName: 'DNMDB', /* required */
    KeySchema: [ /* required */
        {
            AttributeName: 'ID', /* required */
            KeyType: 'HASH' /* required */
        },
        {
            AttributeName: "NAME",
            KeyType: "RANGE"
        }
        /* more items */
    ],
    LocalSecondaryIndexes: [
        {
            IndexName: 'Index1', /* required */
            KeySchema: [ /* required */
                {
                    AttributeName: 'ID', /* required */
                    KeyType: 'HASH' /* required */
                },
                {
                    AttributeName: 'NAME', /* required */
                    KeyType: 'RANGE' /* required */
                }
                /* more items */
            ],
            Projection: { /* required */
                NonKeyAttributes: [
                    'ID'
                    /* more items */
                ],
                ProjectionType: 'INCLUDE'
            }
        }
        /* more items */
    ],
    StreamSpecification: {
        StreamEnabled: true,
        StreamViewType: 'NEW_IMAGE'
    },
    ProvisionedThroughput: { /* required */
        ReadCapacityUnits: 1, /* required */
        WriteCapacityUnits: 1 /* required */
    },
    GlobalSecondaryIndexes: [
        {
            IndexName: 'GIND1', /* required */
            KeySchema: [ /* required */
                {
                    AttributeName: 'ID', /* required */
                    KeyType: 'HASH' /* required */
                },
                /* more items */
            ],
            Projection: { /* required */
                NonKeyAttributes: [
                    'NAME'
                    /* more items */
                ],
                ProjectionType: 'INCLUDE'
            },
            ProvisionedThroughput: { /* required */
                ReadCapacityUnits: 1, /* required */
                WriteCapacityUnits: 1 /* required */
            }
        }
        /* more items */
    ]
};
dyn.createTable(params, function(err, data) {
    if (err) console.log(err, err.stack); // an error occurred
    else     console.log(data);           // successful response
})

dyn.listTables(function (err, data)
{
    console.log('listTables',err,data);
});

第一次執行時,因爲createtable是異步操作,所以查詢表會報空. 而createTable會返回所創建表的信息:

listTables null { TableNames: [] }
{ TableDescription: 
   { AttributeDefinitions: [ [Object], [Object] ],
     TableName: 'DNMDB',
     KeySchema: [ [Object], [Object] ],
     TableStatus: 'ACTIVE',
     CreationDateTime: Fri Sep 11 2015 19:49:41 GMT+0800 (China Standard Time),
     ProvisionedThroughput: 
      { LastIncreaseDateTime: Thu Jan 01 1970 08:00:00 GMT+0800 (China Standard Time),
        LastDecreaseDateTime: Thu Jan 01 1970 08:00:00 GMT+0800 (China Standard Time),
        NumberOfDecreasesToday: 0,
        ReadCapacityUnits: 1,
        WriteCapacityUnits: 1 },
     TableSizeBytes: 0,
     ItemCount: 0,
     TableArn: 'arn:aws:dynamodb:ddblocal:000000000000:table/DNMDB',
     LocalSecondaryIndexes: [ [Object] ],
     GlobalSecondaryIndexes: [ [Object] ],
     StreamSpecification: { StreamEnabled: true, StreamViewType: 'NEW_IMAGE' },
     LatestStreamLabel: '2015-09-11T11:49:41.684',
     LatestStreamArn: 'arn:aws:dynamodb:ddblocal:000000000000:table/DNMDB/stream/2015-09-11T11:49:41.684' } }

第二次執行,就可以查詢表名了。如下:

listTables null { TableNames: [ 'DNMDB' ] }

雖然表創建成功了,但創建表的各項參數還是沒搞明白。功夫不負有心人,終於找到了相關參數說明。
可今天是週五了,還是早點下課過週末吧。 各項參數說明,留待下節課再講。OK,下課,起立~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章