LoginSignup
13
16

More than 5 years have passed since last update.

[Ruby]LevelDBでお手軽にKVS

Last updated at Posted at 2015-05-27

Rubyで触ってみたメモです。

データの永続化、データの個数が多くなるほどファイル保存では苦しくなってきて、データベースを使うべきなんだけど、SQLiteのSQL文はつらく、KVSのお手軽さが嬉しいけどサーバーを立てたくないし、「鯖不要で動く手軽なKVSないかな………」と思ってたらありました。世界は優しい。

LevelDBはSQLiteのKVS版、といったところ。なんといってもサーバーが不要です。

OSXにインストール
$ brew install leveldb
$ brew uninstall snappy # やらないとエラー http://shokai.org/blog/archives/7078
$ gem install leveldb-ruby

Example

leveldb-ruby gemのおかげで、LevelDBを文字列専用のHashのように触ることができます。実にお手軽です。

example.rb
require 'leveldb'

db = LevelDB::DB.new("test.db") # なければカレントディレクトリにtest.dbフォルダが作成される

db["first"] = "first text"      # Put
db["first"]      #=> "first text" Get
db.to_h          #=> {"first"=>"first text"}

db.delete("first") # Delete
db["first"]        #=> nil

# key valueは文字列しか使えないよ
db[123]         #=> TypeError
db["123"] = 789 #=> TypeError

他のオブジェクトが使いたいなら、シリアライズするとかJSON使うとか。

関連

13
16
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
16