Skip to main content

Overview

The Filter trait defines how candidates are evaluated and partitioned into kept and removed sets. Filters run sequentially and reduce the candidate pool based on various criteria.

Trait Definition

Type Parameters

generic
The query type that contains request context and parametersConstraints: Clone + Send + Sync + 'static
generic
The candidate type to filterConstraints: Clone + Send + Sync + 'static

FilterResult

Vec<C>
Candidates that passed the filter criteria and continue to the next stage
Vec<C>
Candidates that were filtered out and are excluded from further processing

Methods

enable

fn
Determines whether this filter should run for the given query
&Q
Reference to the query object
bool
Returns true if this filter should run, false to skip. Default implementation returns true.

filter

async fn
Evaluates candidates and partitions them into kept and removed sets
&Q
Reference to the query object containing filtering parameters
Vec<C>
Vector of candidates to evaluate (takes ownership)
Result<FilterResult<C>, String>
Returns a FilterResult with kept and removed candidates, or an error message on failure

name

fn
Returns a stable name for logging and metrics
&'static str
A short type name derived from the implementing struct

Example Implementation

Here’s a real example that filters tweets based on their age:

Usage Notes

  • Filters run sequentially in the order they are configured
  • Each filter receives the kept candidates from the previous filter
  • The removed candidates can be tracked for metrics and debugging
  • Filters take ownership of the candidate vector for efficient partitioning
  • Use partition for simple boolean criteria, or build custom logic for complex rules

Common Filter Types

Quality Filters

  • Remove low-quality or spam content
  • Filter by content safety scores
  • Remove candidates missing required fields

Business Logic Filters

  • Apply user preferences and settings
  • Enforce diversity constraints
  • Remove already-seen content

Performance Filters

  • Limit candidate pool size before expensive operations
  • Remove candidates that would fail downstream validation

Best Practices

  1. Sequential Ordering: Place cheap filters before expensive ones
  2. Descriptive Names: Override name() to provide meaningful filter identifiers
  3. Track Removed: Log removed candidate counts for monitoring
  4. Error Handling: Return descriptive errors for debugging
  5. Conditional Execution: Use enable() to skip filters based on query parameters
  6. Efficient Partitioning: Use Iterator::partition for simple boolean criteria

Performance Considerations

  • Filters run sequentially, so order matters for performance
  • Place filters that remove many candidates early in the chain
  • Avoid expensive async operations if possible; defer to scorers
  • Consider batch operations when accessing external services

See Also