First Step
The first
step consumes the walker and returns the ID of the very first element encountered in the traversal stream, wrapped in an Option
. If the stream is empty, it returns None
. This is a terminal operation that efficiently short-circuits the traversal as soon as the first element is found.
In this diagram:
- Input Elements: The walker starts with elements A, B, C, D.
- The
.first()
step processes the stream, immediately takes element A, and consumes the walker. Elements B, C, and D are never processed or considered. - Returns: Option<ID>: The step returns
Some(ID(A))
, containing the ID of the first element found. - Terminates Walker: This step ends the Graph API walker chain.
Syntax
walker.first()
Parameters
This step takes no parameters.
Return Value
Returns an Option
containing the first element from the traversal, or None
if the traversal is empty.
Examples
Basic Usage
Retrieve the first person vertex from the graph:
// Get the first person in the graph (if any)
let first_person = graph.walk().vertices(Vertex::person()).first();
match first_person {
Some(person) => println!("Found a person: {:?}", person),
None => println!("No people in the graph"),
}
With Filtering
Get the first person matching specific criteria:
// Get the first person with a specific name
let first_bryn = graph
.walk()
.vertices(Vertex::person()) // Get all Person vertices
.filter_by_person(|person, _| {
// Using the typed projection with accessor methods
person.name().contains("Bryn")
})
.first();
match first_bryn {
Some(bryn) => println!("Found Bryn: {:?}", bryn),
None => println!("No one named Bryn in the graph"),
}
Existence Check
Check if any elements match a condition:
// Use first to check if any element matches a condition
let has_young_person = graph
.walk()
.vertices(Vertex::person())
.filter_by_person(|person, _| {
// Using type-safe accessor methods
person.age() < 30
})
.first()
.is_some();
println!(
"Graph {} people under 30",
if has_young_person {
"contains"
} else {
"doesn't contain"
}
);
Best Practices
- Always handle the
None
case when usingfirst()
on potentially empty traversals - Use filtering before
first()
to ensure you get the element you want - For deterministic results, combine with ordered indexes or explicit sorting
- Prefer
first()
overlimit(1).collect::<Vec<_>>()
for better performance
Common Use Cases
- Single element retrieval: Getting exactly one element matching specific criteria
- Existence checking: Determining if any elements match a condition with
is_some()
- Quick lookup: Finding a representative example of a vertex or edge type
- Early termination: Efficiently stopping traversal after finding the first match