Skip to content
This repository has been archived by the owner on Mar 23, 2023. It is now read-only.

Commit

Permalink
perf: optimize prefix search (#25)
Browse files Browse the repository at this point in the history
* feat: optimise prefix search

Signed-off-by: Carson Farmer <carson.farmer@gmail.com>

* style: fix linter issue

Signed-off-by: Carson Farmer <carson.farmer@gmail.com>

* chore: remove avoid reaching into internal db

Signed-off-by: Carson Farmer <carson.farmer@gmail.com>
  • Loading branch information
carsonfarmer authored and achingbrain committed Dec 20, 2019
1 parent 75ff645 commit 8efa812
Showing 1 changed file with 16 additions and 9 deletions.
25 changes: 16 additions & 9 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -105,12 +105,23 @@ class LevelDatastore {
values = !q.keysOnly
}

const opts = {
keys: true,
values: values,
keyAsBuffer: true
}

// Let the db do the prefix matching
if (q.prefix != null) {
const prefix = q.prefix.toString()
// Match keys greater than or equal to `prefix` and
opts.gte = prefix
// less than `prefix` + \xFF (hex escape sequence)
opts.lt = prefix + '\xFF'
}

let it = levelIteratorToIterator(
this.db.db.iterator({
keys: true,
values: values,
keyAsBuffer: true
})
this.db.iterator(opts)
)

it = map(it, ({ key, value }) => {
Expand All @@ -121,10 +132,6 @@ class LevelDatastore {
return res
})

if (q.prefix != null) {
it = filter(it, e => e.key.toString().startsWith(q.prefix))
}

if (Array.isArray(q.filters)) {
it = q.filters.reduce((it, f) => filter(it, f), it)
}
Expand Down

0 comments on commit 8efa812

Please sign in to comment.