Take Step
The take
step restricts a traversal to return at most a specified number of elements, helping to control result size
and improve performance.
In this diagram:
- An Input Stream contains elements A, B, C, D.
- The
.take(2)
step acts like a gate, processing elements sequentially. - Only the first two elements, A and B, pass through to the Output Stream.
- Elements C and D are Discarded because the limit of 2 was reached. The traversal stops after yielding the second element.
Syntax
walker.take(n)
Parameters
n
: Ausize
value specifying the maximum number of elements the traversal should return
Return Value
Returns a new walker that will yield at most n
elements.
Examples
Basic Usage
// Get the first 2 people in the graph
println!("First 2 people in the graph:");
let people = graph
.walk()
.vertices(Vertex::person())
.take(2) // Only take the first 2 vertices
.collect::<Vec<_>>();
for person in &people {
println!(" - {:?}", person);
}
println!("Found {} people (limited to 2)", people.len());
With Filtering
// Get up to 3 people over the age of 30
println!("\nUp to 3 people over 30:");
let older_people = graph
.walk()
.vertices(Vertex::person()) // Get all Person vertices
.filter_by_person(|person, _| {
// Using the typed projection with accessor methods
person.age() > 30
})
.take(3) // Only take up to 3 matches
.collect::<Vec<_>>();
for person in &older_people {
println!(" - {:?}", person);
}
println!("Found {} people (limited to 3)", older_people.len());
Edge Traversal Example
// Find the first 2 connections from the first person
if let Some(first_person) = graph.walk().vertices(Vertex::person()).first() {
println!("\nFirst 2 connections from a person:");
let connections = graph
.walk()
.vertices_by_id([first_person])
.edges(EdgeSearch::scan()) // All edge types
.take(2) // Only take the first 2 edges
.collect::<Vec<_>>();
for edge in &connections {
println!(" - {:?}", edge);
}
println!("Found {} connections (limited to 2)", connections.len());
}
Best Practices
- Use
take
early in the traversal chain to reduce computation on intermediate steps - Combine with ordered indexes when sequence matters to ensure consistent results
- For single element retrieval, prefer the more idiomatic
first()
overtake(1)
- Set conservative limits when exploring large graphs to prevent memory issues
Common Use Cases
- Performance optimization: Restricting result size for large graph traversals
- Pagination: Implementing "page-by-page" data retrieval when combined with skip/offset mechanisms
- Top-N queries: Getting the first N elements matching certain criteria
- Resource control: Preventing excessive memory or processing use in production systems