ryoakg
8/13/2017 - 1:51 AM

leveldb.clj

(set-env! :dependencies '[[factual/clj-leveldb "0.1.1"]])

(require '[clj-leveldb :as db]
         'byte-streams                  ;https://github.com/ztellman/byte-streams
         '[clojure.java.io :as io])

;;; Creates a directory named `leveldb-test` if not exists.
(def db (db/create-db (io/file "leveldb-test")
                      {:key-decoder byte-streams/to-string
                       :val-decoder byte-streams/to-string}))

;;; Basic usage
(db/put db "a" "b")
(db/get db "a")
;; => "b"


;;; Keys & values must be able to convert to convert into [B
;;; https://github.com/dain/leveldb/blob/master/leveldb-api/src/main/java/org/iq80/leveldb/DB.java
;;;
;;; java.lang.IllegalArgumentException: Don't know how to convert class java.lang.Long into class [B
(db/put db "a" 1)
;;; java.lang.IllegalArgumentException: Don't know how to convert a sequence of class java.lang.Long into class [B
(db/put db "a" [1 2])


;;; Put multiple keys & values.
(db/put db
        "a" "b"
        "c" "d"
        "e" "f")

(db/get db "a")
;; => "b"
(db/get db "c")
;; => "d"
(db/get db "e")
;; => "f"


;;; Default value
(db/get db "g")                         ; the value is not found
;; => nil
(db/get db "g" :none)                   ; :none as default
;; => :none


;;; Iteration
(db/iterator db)
;; => (["a" "b"] ["c" "d"] ["e" "f"])


;;; Delete values by keys
(db/delete db "a" "c" "e")

(db/get db "a")
;; => nil

(db/iterator db)
;; => nil


;;; Tear down: Delete the directory recursively.
(ns-unmap *ns* 'db)
((fn re [^java.io.File f]
   (when (.isDirectory f)
     (dorun (map re (.listFiles f))))
   (io/delete-file f))
 (io/file "leveldb-test"))