High level API

mlogan edited this page Sep 27, 2012 · 9 revisions
Clone this wiki locally

High-level API

This API provides objects representing databases, tables, items, batches, queries, and scans.

Database

db.fetch(callback)

This populates the db.tables object with all of the tables in the database.

db.fetch(function(err) {
  if (err) return console.error(err)

  var tableCount = Object.keys(db.tables).length

  console.log("This database has %s tables.", tableCount)
})

db.put(tableName, item)

An alias for db.get(tableName).put(item).

db.add(table)

Returns a table on which .save() can be called

db.add({
    name: "myTable",
    schema: [ ['id', String], ['date', Number] ],
    throughput: {read: 10, write: 10}
  })
  .save(function(err, table){ ... })

The name is required, but schema will default to [ ['id', String] ] and throughput will default to the DynamoDB minimums of 3 for reads and 5 for writes. (Note: Versions 0.2.13 and earlier specified the schema with an object, such as { id: String, date: Number }. This method is still supported for backward-compatibility, but its use is discouraged, as it relied on v8 traversing object properties in the same order in which they were inserted.)

Note that the order in which the schema keys are defined is important; the first is required and is used as the hash key, while the second is optional and is used as the range key.

db.remove(tableName, callback)

An alias for db.get(tableName).destroy(callback)

table = db.get(tableName)

Returns a table.

item = db.get(tableName, itemKey)

An alias for db.get(_tableName_).get(_itemKey_).

batch = db.get([object])

batch = db.get([function])

Creates a batch for fetching multiple items from multiple tables.

Table

table.fetch(callback)

Fetches metadata about a table, including its schema, throughput, size, and other information.

table.fetch(function(err, table) {
  if (err) return console.error(err)

  console.log(
    "This table has %s items and was created at %s",
    table.ItemCount,
    table.CreationDateTime
  )
})

table.destroy(callback)

This deletes a table. Note that it may take up to a minute for DynamoDB to actually delete the table.

table.destroy(function(err) {
  if (err) return console.error(err)

  console.log("Table is now being deleted.")
})

table.watch(callback)

This uses .fetch() to poll the status of a table until it is stable (not ending in ING), and then calls back.

table.watch(function(err, table) {
  if (err) return console.error(err)

  console.log("Table is now %s.", table.TableStatus)
})

table.throughput.set(attrs).save(callback)

This updates the throughput of a table. Note that both a read and write property need to be specified, and some DynamoDB limitations exist regarding how often table throughput can be updated.

table.throughput
     .set({read: 10, write: 10})
     .save(function(err, data) {
        if (err) return console.error(err)

        console.log("Table throughput is now updating...")
     })

item = table.get(itemKey)

Returns a reference to the item specified by itemKey.

batch = table.get(function)

This is a table-specific alias for fetching a batch of multiple items from the same table.

table.get(function() {
        this.add("tags", ["foo"])
        this.put("status", "happy")
        this.remove("middleName")
      })
      .fetch(function(err, data){ ... })

table.put(item).save(callback)

This puts the specified item in the table, overwriting any existing item with the same key. Note that the specified item must contain the hash and range keys.

table.put({
        id: "123",
        name: "ralph"
      })
      .save(function(err, data){ ... })

table.scan(predicates)

Returns a scan for the given predicates.

table.query(predicates)

Returns a query for the given predicates.

Predicates

A predicates object represents one or more predicates to be satisfied, for query or scan keys, or item update expectations.

new Predicates(predicates)

This constructor is called automatically for the Table#scan(), Table#query(), and Update#when() methods, to convert shorthand predicates into the more verbose DynamoDB format.

Predicates take this format:

{
  attribute1: {comparisonOperator1: comparisonValue1},
  attribute2: {comparisonOperator2: comparisonValue2}
  ...
}

DynamoDB predicates are mapped to more JavaScript-friendly versions, as follows.

// NOT_NULL []
{ "!=" : null }

// NE [VAL]
{ "!=" : VAL }

// NULL []
{ "==" : null }

// EQ [VAL]
{ "==" : VAL }

// GT [VAL]
{ ">"  : VAL }

// LT [VAL]
{ "<"  : VAL }

// LE [VAL]
{ "<=" : VAL }

// GE [VAL]
{ ">=" : VAL }

// BETWEEN [VAL1, VAL2]
{ "<=" : [VAL1, VAL2] }
{ ">=" : [VAL1, VAL2] }

// CONTAINS [VAL]
{ "contains" : VAL }

// NOT_CONTAINS [VAL]
{ "!contains" : [VAL] }

// BEGINS_WITH [VAL]
{ "startsWith" : [VAL] }

// IN [VAL1, VAL2, VAL3]
{ "in" : [VAL1, VAL2, VAL3] }

Note also that ("attributeName") resolves to {attributeName: {"!=": null}} and ("attributeName", "value") resolves to {attributeName: {"==": "value"}}.

Scan

scan = table.scan(predicates)

Scans are created from tables, using a predicates object. Note that DynamoDB supports multiple predicates for a scan.

table.scan({
        name: "dynamo",
        iq: {">=": 100}
      })
      .get(["name", "iq", "status"])
      .fetch(function(err, count){ ... })

scan.get(attributeNames)

This fetches only the attribute names in the provided array. If this is not called, all attributes are returned.

scan.count()

This returns the number of items scanned, and cannot be used if Scan#get() is called.

scan.fetch(callback)

This performs the scan, calling back with an array of all items that matched the scan.

Query

query = table.query(predicates)

Queries are created from tables, using a predicates object. Note that only two predicates can be specified: the first using == for the hash key, and the second using a one of the predicates supported for queries for the range key.

query.get(attributeNames)

This fetches only the attribute names in the provided array. If this is not called, all attributes are returned.

query.count()

This returns the number of items scanned, and cannot be used if Query#get() is called.

query.reverse()

This performs the query in reverse order.

query.fetch(callback)

This performs the query, calling back with an array of all items that matched the query.

Item

item = db.get(tableName, itemKey)

item = table.get(itemKey)

An can be obtained from a database or table, by specifying the item key. To uniquely identify an item, the item key must have values for both the hash and range keys.

item.get(attributeNames)

This fetches only the attribute names in the provided array. If this is not called, all attributes are returned.

item.fetch([options], callback)

This fetches the item. {consistent: true} can be specified as the options object to return a consistent read.

item.update(function)

This specifies multiple attribute updates to be performed in a single transaction. The provided function is called with an update object as its this context, allowing PUT, ADD, and REMOVE operations to be performed for each attribute.

item.update(function() {
  this.add("tags", ["foo"])
  this.put("status", "happy")
  this.remove("middleName")
})

item.destroy(callback)

This deletes an item.

item.destroy(function(err) {
  if (err) return console.error(err)

  console.log("Item has been deleted.")
})

item.when(predicates)

This specifies that update is only performed when the given predicate is satisfied. Only {"==": value}, {"==": null}, and {"!=": null} are allowed.

item.returning(type)

This specifies whether the information returned should be before or after the update. The type can be ALL_OLD for puts, or ALL_OLD, UPDATED_OLD, ALL_NEW, or UPDATED_NEW for updates.

item.save(callback)

This performs a put or update, and calls back with the results.

Batch

DynamoDB allows up to 100 items across multiple tables to be returned with a single call.

batch = db.get(function)

batch = table.get(function)

A batch can be created from a database, or a table (in which case all Batch#get() calls are scoped to the table). The provided function is executed with the batch as its this context.

db.get(function() {
  this.get("table1", [{id: "123"},{id: "456"}], ["id", "name", "status"])
  this.get("table2", [{id: "123", date: 1329925897205}])
})

batch.get(tableName, itemKey, [attributeNames])

This adds item to the batch. If attributeNames is specified, only those attributes are returned.

batch.fetch(callback)

This fetches the batch and calls back with the results.