|
7 | 7 | //! - [Advanced Multithreaded Access of Entries](#advanced-multithreaded-access-of-entries) |
8 | 8 | //! - [Use Custom Key Comparator](#use-custom-key-comparator) |
9 | 9 | //! - [Use Custom Dupsort Comparator](#use-custom-dupsort-comparator) |
| 10 | +//! - [Use Bytes as Cursor Ranges](#use-bytes-as-cursor-ranges) |
10 | 11 | //! |
11 | 12 | //! # Decode Values on Demand |
12 | 13 | //! |
|
580 | 581 | //! } |
581 | 582 | //! ``` |
582 | 583 | //! |
| 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 | +//! |
583 | 644 |
|
584 | 645 | // To let cargo generate doc links |
585 | 646 | #![allow(unused_imports)] |
|
0 commit comments