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

Optimize prefix search #25

Merged
merged 3 commits into from
Dec 20, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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