Skip to content

Commit b82e9df

Browse files
authored
Merge pull request #347 from andunieee/bytes-range-custom-rangebounds
add custom bytes range query to cookbook
2 parents bd96d8f + d6c8aea commit b82e9df

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

heed/src/cookbook.rs

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
//! - [Advanced Multithreaded Access of Entries](#advanced-multithreaded-access-of-entries)
88
//! - [Use Custom Key Comparator](#use-custom-key-comparator)
99
//! - [Use Custom Dupsort Comparator](#use-custom-dupsort-comparator)
10+
//! - [Use Bytes as Cursor Ranges](#use-bytes-as-cursor-ranges)
1011
//!
1112
//! # Decode Values on Demand
1213
//!
@@ -580,6 +581,66 @@
580581
//! }
581582
//! ```
582583
//!
584+
//! # Use Bytes as Cursor Ranges
585+
//!
586+
//! When working with databases that have sorted keys, you might want to iterate over a specific range
587+
//! of keys starting from a particular key. Heed provides the [`Database::range`] method that accepts
588+
//! any type implementing [`std::ops::RangeBounds`].
589+
//!
590+
//! Specifically, if your keys are of type [`heed::types::Bytes`] and you have a `Vec<u8>` as your starting key,
591+
//! because a tuple of [`std::ops::Bound`] implements such trait you can just use that:
592+
//!
593+
//! ```
594+
//! use std::error::Error;
595+
//!
596+
//! use heed::byteorder::NativeEndian;
597+
//! use heed::types::*;
598+
//! use heed::EnvOpenOptions;
599+
//!
600+
//! fn main() -> Result<(), Box<dyn Error>> {
601+
//! let path = tempfile::tempdir()?;
602+
//!
603+
//! let env = unsafe {
604+
//! EnvOpenOptions::new()
605+
//! .map_size(1 << 34)
606+
//! .max_dbs(1)
607+
//! .open(&path)?
608+
//! };
609+
//!
610+
//! let mut wtxn = env.write_txn()?;
611+
//!
612+
//! let db = env
613+
//! .database_options()
614+
//! .types::<Bytes, U64<NativeEndian>>()
615+
//! .name("index")
616+
//! .create(&mut wtxn)?;
617+
//!
618+
//! db.put(&mut wtxn, &vec![1, 2, 3, 3], &55555u64)?;
619+
//! db.put(&mut wtxn, &vec![1, 2, 3, 4], &66666u64)?;
620+
//! db.put(&mut wtxn, &vec![1, 2, 3, 5], &77777u64)?;
621+
//!
622+
//! wtxn.commit()?;
623+
//!
624+
//! let txn = env.read_txn()?;
625+
//! let key: Vec<u8> = vec![1, 2, 3, 4];
626+
//!
627+
//! for result in db
628+
//! .range(
629+
//! &txn,
630+
//! &(
631+
//! std::ops::Bound::Included(key.as_slice()),
632+
//! std::ops::Bound::Unbounded,
633+
//! ),
634+
//! )? {
635+
//! let (k, v) = result?;
636+
//! println!("Key: {:?}, Value: {}", k, v);
637+
//! }
638+
//!
639+
//! Ok(())
640+
//! }
641+
//! ```
642+
//!
643+
//!
583644
584645
// To let cargo generate doc links
585646
#![allow(unused_imports)]

0 commit comments

Comments
 (0)