NoSQL LevelDB

NoSQLSQL を使わずにデータを操作するデータベース。次のように分類できる。

  • KVS

  • ドキュメントストア

  • ワイドカラムストア

  • グラフデータベース

書籍「ハンズオン Node.js」では、環境構築が容易な LevelDB を取り組む。

level

Fast & simple storage. A Node.js-style LevelDB wrapper for Node.js, Electron and browsers.

Tips

書籍「ハンズオン Node.js」より

リレーショナルデータベースのテーブルに相当する概念がないため、キーには ID だけでなく名前空間のようなものを付けたほうがよいでしょう。

levelDB を使う

levelDB Google Chromeのために開発された NoSQL とのこと。書籍とバージョンを合わせておく。

$ npm i level@6.0.1

db = level()

The main entry point for creating a new levelup instance.

db.isOpen()

isOpen() will return true only when the state is "open".

db.put()

put() is the primary method for inserting data into the store.

db.get()

get() is the primary method for fetching data from the store.

db.createReadStream()

Returns a Readable Stream of key-value pairs.

Use the options described below to control the range, direction and results.

db.batch()

batch(), when called with no arguments will return a Batch object which can be used to build,

$  node --experimental-repl-await

  

> const  db = level('levelDB');

> console.log(db.isOpen())

true

> const  todo1 = JSON.stringify({ id:  '1', title:  '表紙', completed:  false });

> await  db.put('todo:1', todo1);

> await  db.get('todo:1');

'{"id":"1","title":"表紙","completed":false}'

> await  db.get('todo:2'); # 存在しないキーを指定

Uncaught  Error [NotFoundError]: Key  not  found  in  database [todo:2]

> await  db.get('todos:1'); # 存在しない名前空間を指定

Uncaught  Error [NotFoundError]: Key  not  found  in  database [todos:1]

> .editor

for  await (const  data  of  db.createReadStream()) {

console.log(data.key, data.value);

}

todo:1 {"id":"1","title":"表紙","completed":false}

# 名前空間として  `todo`  をつけたこと及び
# UTF-16コードで  `:`  の次の文字が  `;`  であることを利用して
# 必要なデータのみを取得
> .editor

for  await (const  data  of  db.createReadStream({ gt:  'todo:', lt:  'todo;' })) {

console.log(data.key, data.value);

}

todo:1 {"id":"1","title":"表紙","completed":false}

await  db.batch([

{ type:  'put', key:  'city:2021', value:  '東京' },

{ type:  'put', key:  'city:2016', value:  'リオ' },

{ type:  'put', key:  'city:2012', value:  'ロンドン' },

{ type:  'del', key:  'city:2021' },

]);

for  await (const  data  of  db.createReadStream({ gt:  'city:', lt:  'city;' })) {

console.log(data.key, data.value);

}

city:2012  ロンドン

city:2016  リオ

undefined

await  db

.batch()

.put('city:2008', '北京')

.put('city:2004', 'アテネ')

.put('city:2000', 'シドニー')

.del('city:2016')

.write();

for  await (const  data  of  db.createReadStream({ gt:  'city:', lt:  'city;' })) {

console.log(data.key, data.value);

}

city:2000  シドニー

city:2004  アテネ

city:2008  北京

city:2012  ロンドン

undefined

await  db.close();

値による検索を可能にするには、検索対象としたい値( completed )をキーに含むデータを元のデータとは別に保存する必要があります。