Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Lexical Search

Lexical search finds documents by matching keywords against an inverted index. Laurus provides a rich set of query types that cover exact matching, phrase matching, fuzzy matching, and more.

Basic Usage

#![allow(unused)]
fn main() {
use laurus::SearchRequestBuilder;
use laurus::lexical::TermQuery;
use laurus::lexical::search::searcher::LexicalSearchQuery;

let request = SearchRequestBuilder::new()
    .lexical_query(
        LexicalSearchQuery::Obj(
            Box::new(TermQuery::new("body", "rust"))
        )
    )
    .limit(10)
    .build();

let results = engine.search(request).await?.results;
}

Query Types

TermQuery

Matches documents containing an exact term in a specific field.

#![allow(unused)]
fn main() {
use laurus::lexical::TermQuery;

// Find documents where "body" contains the term "rust"
let query = TermQuery::new("body", "rust");
}

Note: Terms are matched after analysis. If the field uses StandardAnalyzer, both the indexed text and the query term are lowercased, so TermQuery::new("body", "rust") will match “Rust” in the original text.

PhraseQuery

Matches documents containing an exact sequence of terms.

#![allow(unused)]
fn main() {
use laurus::lexical::query::phrase::PhraseQuery;

// Find documents containing the exact phrase "machine learning"
let query = PhraseQuery::new("body", vec!["machine".to_string(), "learning".to_string()]);

// Or use the convenience method from a phrase string:
let query = PhraseQuery::from_phrase("body", "machine learning");
}

Phrase queries require term positions to be stored (the default for TextOption). On a multi-valued text field (multi_valued = true) the elements share one position sequence separated by the field’s position_increment_gap (default 100), so a phrase never spans two elements unless its slop reaches that gap — see Schema and Fields.

BooleanQuery

Combines multiple queries with boolean logic.

#![allow(unused)]
fn main() {
use laurus::lexical::query::boolean::{BooleanQuery, BooleanQueryBuilder, Occur};

let query = BooleanQueryBuilder::new()
    .must(Box::new(TermQuery::new("body", "rust")))       // AND
    .must(Box::new(TermQuery::new("body", "programming"))) // AND
    .must_not(Box::new(TermQuery::new("body", "python")))  // NOT
    .build();
}
OccurMeaningDSL Equivalent
MustDocument MUST match+term or AND
ShouldDocument SHOULD match (boosts score)term or OR
MustNotDocument MUST NOT match-term or NOT term
FilterMUST match, but does not affect score(no DSL equivalent)

A BooleanQuery without a Must or Should clause — filters alone, negations alone, or both — gives every match the score 0, whatever its boost, as Lucene and Elasticsearch score filters and Elasticsearch a negation alone. Inside another query it adds nothing, and with a min_score above 0 it finds nothing. Until Issue #1744 it scored each match as a term that one document has once, except for filters alone in a parallel search, which scored 0.

FuzzyQuery

Matches terms within a specified edit distance (Levenshtein distance).

#![allow(unused)]
fn main() {
use laurus::lexical::query::fuzzy::FuzzyQuery;

// Find documents matching "programing" within edit distance 2
// This will match "programming", "programing", etc.
let query = FuzzyQuery::new("body", "programing");  // default max_edits = 2
}

The closest terms are scored, 50 by default, as in Lucene. A term counts as close by 1 - distance / length of the shorter term, in characters and at least 0: 1 for the exact term, which is never dropped. Among equally close terms the most frequent come first. That value is also the factor of the term’s score, and every term is scored with the document frequency of the most frequent of them, so how rare a term is plays no part in its score.

max_expansions sets the number of terms, at least 1, and with_rewrite_method the scoring; they are one setting, of which the later call wins:

RewriteMethodScoreHits of a search for the query
TopTermsBlended { max_expansions } (default, with 50)BM25 of the closest terms, with the factor, as if each were as frequent as the most frequent of themThe documents that have one of these terms
TopTermsScoring { max_expansions }BM25 of the closest terms, with the factorThe documents that have one of these terms
ConstantScoreThe boostEvery match
BooleanQueryBM25 of every matching term, with the factorEvery match; see the cost below

A filter and a MustNot clause use the matches without their scores, so they cover every matching term with each method.

Until Issue #1740 every matching term was scored, whatever max_expansions and with_rewrite_method said, without a factor.

WildcardQuery

Matches terms using wildcard patterns.

#![allow(unused)]
fn main() {
use laurus::lexical::query::wildcard::WildcardQuery;

// '?' matches exactly one character, '*' matches zero or more
let query = WildcardQuery::new("filename", "*.pdf")?;
let query = WildcardQuery::new("body", "pro*")?;
let query = WildcardQuery::new("body", "col?r")?;  // matches "color", not "colour"
let query = WildcardQuery::new("body", r"why\?")?;  // matches "why?"
}

A pattern reads as in Lucene’s WildcardQuery. * and ? match any characters, line breaks included. A backslash takes the next character literally, whatever it is (\*, \? and \\ match *, ? and \, and \d matches d), and at the end of a pattern is a backslash itself. Every other character matches itself, . and + too, so no pattern is an error, short of one too long for the regexp engine (100,000 ?, for example). Until Issue #1745 the backslash went to the regexp with the next character: te\dt matched te1t, and a\pb was an error.

PrefixQuery

Matches documents containing terms that start with a specific prefix.

#![allow(unused)]
fn main() {
use laurus::lexical::query::prefix::PrefixQuery;

// Find documents where "body" contains terms starting with "pro"
// This matches "programming", "program", "production", etc.
let query = PrefixQuery::new("body", "pro");
}

RegexpQuery

Matches documents containing terms that match a regular expression pattern.

#![allow(unused)]
fn main() {
use laurus::lexical::query::regexp::RegexpQuery;

// Find documents where "body" contains terms matching the regex
let query = RegexpQuery::new("body", "^pro.*ing$")?;

// Match version-like patterns
let query = RegexpQuery::new("version", r"^v\d+\.\d+")?;
}

Note: RegexpQuery::new() returns Result because the regex pattern is validated at construction time. Invalid patterns will produce an error.

Matches and scores of wildcard, prefix and regexp queries

A WildcardQuery, PrefixQuery or RegexpQuery matches every document that has a matching term, however many terms match. Until Issue #1740 it found only the documents of 50 of the terms, the least frequent ones, and as a MustNot clause excluded only those.

They are constant-scored, as in Lucene: every match receives the query’s boost (1.0 by default), since how frequent a term is says little about how well it fits a pattern. with_rewrite_method selects another scoring:

RewriteMethodScoreHits of a search for the query
ConstantScore (default)The boostEvery match
TopTermsScoring { max_expansions }BM25 of the max_expansions most frequent matching termsThe documents that have one of these terms
TopTermsBlended { max_expansions }The same, as if each were as frequent as the most frequent of themThe documents that have one of these terms
BooleanQueryBM25 of every matching termEvery match; the cost grows faster than the number of terms, to minutes for 10,000 terms in a large segment

A filter and a MustNot clause use the matches without their scores, so they cover every matching term with each method.

The cost of a search grows with the number of terms that match and of the documents that have them. A wildcard that starts with ? or *, and a regexp with no literal text after a leading ^, are compared with every term of the field.

NumericRangeQuery

Matches documents with numeric field values within a range.

#![allow(unused)]
fn main() {
use laurus::lexical::NumericRangeQuery;
use laurus::lexical::core::field::NumericType;

// Find documents where "price" is between 10.0 and 100.0 (inclusive)
let query = NumericRangeQuery::new(
    "price",
    NumericType::Float,
    Some(10.0),   // min
    Some(100.0),  // max
    true,         // include min
    true,         // include max
);

// Open-ended range: price >= 50
let query = NumericRangeQuery::new(
    "price",
    NumericType::Float,
    Some(50.0),
    None,     // no upper bound
    true,
    false,
);
}

Numeric range queries are constant-scored: every matching document receives the same score (the query’s boost, 1.0 by default, finite and at least 0), following Lucene’s PointRangeQuery semantics. Matching uses the field’s BKD tree when the segment has one; segments without a BKD tree for the field (for example, segments none of whose documents carry the field, or a field configured indexed = false, stored = true) fall back to scanning only the stored documents actually present in that segment. The scan compares the values as numbers, as the BKD tree does: negative values and bounds match, -0.0 equals 0.0, and a NaN value matches no range.

A bound compares as an f64 too: f64::NEG_INFINITY as the lower bound or f64::INFINITY as the upper bound finds what None finds. A NaN bound would match nothing, so a search with one, as the query, a filter or a clause of another query, fails with InvalidArgument. For NumericType::Integer a bound is truncated to an i64, an infinity to i64::MIN or i64::MAX.

DateTimeRangeQuery

Matches documents whose DateTime field value falls within a range.

#![allow(unused)]
fn main() {
use chrono::{TimeZone, Utc};
use laurus::lexical::DateTimeRangeQuery;

// Find documents where "created_at" is within 2024 (both bounds inclusive)
let query = DateTimeRangeQuery::between(
    "created_at",
    Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap(),
    Utc.with_ymd_and_hms(2024, 12, 31, 23, 59, 59).unwrap(),
);

// Open-ended range: created_at > 2024-06-15T12:00:00Z (exclusive)
let query = DateTimeRangeQuery::after(
    "created_at",
    Utc.with_ymd_and_hms(2024, 6, 15, 12, 0, 0).unwrap(),
);

// From textual bounds, using the same literal grammar as the query DSL
let query = DateTimeRangeQuery::from_literals(
    "created_at",
    Some("2024-01-01"),            // min (date only = midnight UTC)
    Some("2024-12-31T23:59:59Z"),  // max
    true,                          // include min
    true,                          // include max
)?;
}

new(field, lower, upper, lower_inclusive, upper_inclusive) takes Option<DateTime<Utc>> bounds; on_or_after, before and on_or_before complete the one-sided helpers, and .with_boost() sets the constant score (finite and at least 0). The query is evaluated against the field’s one-dimensional BKD point (seconds with a microsecond fraction, so sub-second bounds compare exactly) with the same constant scoring and stored-document fallback as NumericRangeQuery. from_literals accepts RFC 3339, naive YYYY-MM-DDTHH:MM:SS[.fff] (UTC) and YYYY-MM-DD (midnight UTC) — the query the DSL builds for created_at:[2024-01-01 TO 2024-12-31] (see Query DSL). A NumericRangeQuery over a DateTime field with epoch-second bounds keeps working.

GeoDistanceQuery / GeoBoundingBoxQuery

Match documents by 2D geographic location (WGS84 latitude / longitude).

#![allow(unused)]
fn main() {
use laurus::lexical::query::geo::{GeoBoundingBoxQuery, GeoDistanceQuery};

// Find documents within 10 km (= 10 000 m) of Tokyo Station (35.6812, 139.7671)
let query = GeoDistanceQuery::within_radius("location", 35.6812, 139.7671, 10_000.0)?; // distance in metres

// Find documents within a bounding box (min_lat, min_lon, max_lat, max_lon)
let query = GeoBoundingBoxQuery::within_bounding_box(
    "location",
    35.0, 139.0,  // min (lat, lon)
    36.0, 140.0,  // max (lat, lon)
)?;
}

Both queries score by distance (closer documents rank higher: linear decay from the circle’s centre, or from the box’s centre). Matching uses the field’s BKD tree when the segment has one, reading the coordinates directly from the tree — so an index-only field (indexed = true, stored = false) works without stored documents. Segments without a BKD tree for the field (for example, segments none of whose documents carry the field, or a field configured indexed = false, stored = true) fall back to scanning only the stored documents actually present in that segment.

GeoDistanceQuery is exact on the sphere: the circle is bounded by the lat/lon extent of its spherical cap before the haversine test, so a circle that crosses the antimeridian (±180° longitude), contains a pole, or is large at high latitude still matches every document within the radius. GeoBoundingBoxQuery is a rectangle of latitudes and longitudes, edges included. With min_lon > max_lon the box crosses the antimeridian (±180° longitude), as in GeoJSON (RFC 7946): within_bounding_box("location", -20.0, 175.0, -15.0, -175.0) covers 175° east to 175° west. An edge on exactly ±180° also matches points stored with the other sign, which is the same meridian, and a box with zero width or height matches the points on its line or point. min_lat > max_lat is an error.

GeoPolygonQuery

Match documents with a point of a Geo field inside a polygon, which may have holes (Issue #1596).

#![allow(unused)]
fn main() {
use laurus::lexical::query::geo::{GeoPolygon, GeoPolygonQuery};

// A square with a square hole: the exterior ring first, then the holes,
// each a list of (lat, lon), closed or not
let query = GeoPolygonQuery::within_polygon(
    "location",
    &[(35.0, 139.0), (35.0, 140.0), (36.0, 140.0), (36.0, 139.0)],
    &[&[(35.4, 139.4), (35.4, 139.6), (35.6, 139.6), (35.6, 139.4)]],
)?;

// Or from a GeoPolygon of GeoPoints
let polygon = GeoPolygon::new(exterior, holes)?;
let query = GeoPolygonQuery::new("location", polygon).with_boost(2.0);
}

Every hit scores the boost (1.0 unless set), as Lucene’s polygon query does, and a multi-valued field matches when any of its points is inside. Its edges are straight lines in latitude and longitude. A point on an edge or vertex of the exterior matches, and one on an edge or vertex of a hole does not, as in Lucene.

An edge takes the shorter way between its two vertices: the way whose longitudes differ by 180 degrees or less. An edge from 170 to -170 degrees is 20 degrees wide and crosses the antimeridian, so a polygon over the Pacific needs no splitting, and a point on ±180° matches whichever sign it is stored with. An edge wider than 180 degrees needs a vertex in between. GeoPolygon::new rejects a ring with fewer than 3 distinct points, a coordinate out of range, an edge across exactly 180 degrees of longitude, which could go either way, and a ring around a pole. Self-intersection is not checked, as in Lucene.

Through the BKD tree, a cell inside the polygon is taken whole, without testing its points one by one; only the points of the cells an edge passes through are tested. Segments without a BKD tree for the field scan the stored documents, as the other geo queries do.

GeoPolylineQuery

Match documents with a point of a Geo field within a distance of a polyline, its vertices joined in order: along a road, a railway, a river or a route (Issue #1596).

#![allow(unused)]
fn main() {
use laurus::lexical::query::geo::{GeoPolyline, GeoPolylineQuery};

// Within 2 km of a route from Tokyo through Nagoya to Osaka, (lat, lon)
let query = GeoPolylineQuery::within_distance(
    "location",
    &[(35.68, 139.76), (35.17, 136.91), (34.69, 135.50)],
    2_000.0,
)?;

// Or from a GeoPolyline of GeoPoints
let polyline = GeoPolyline::new(vertices)?;
let query = GeoPolylineQuery::new("location", polyline, 2_000.0).with_boost(2.0);
}

The distance is on the surface, as GeoDistanceQuery’s: each edge is the shorter great-circle arc between its vertices, and a point is measured to the arc’s closest point, or to the nearer end past it, so the ends and corners are round. A polygon’s edges are straight lines in latitude and longitude; a polyline’s follow great circles, so the arc from (10, 0) to (10, 170) rises to about 63.7 degrees north midway. The score is 1 - d / distance_m by the closest point of a document, as GeoDistanceQuery’s, and a single vertex finds what GeoDistanceQuery finds, with the same scores. GeoPolyline::new takes one vertex or more, repeated vertices included (an edge of length 0 is its point), and rejects a coordinate out of range and an edge between antipodal points, or points within about 640 m of them, which no single shortest arc joins. An edge across the antimeridian needs nothing special.

Through the BKD tree, a cell is pruned when it is apart from every edge’s bounds: the edge’s latitudes, including the arc’s highest between its vertices, and its longitudes the shorter way, widened by the distance; the points of the other cells are measured one by one, as the score needs each one’s distance. The edges are kept in a tree of caps of the sphere, so a cell and a point reach only the edges near them, with the results of checking every edge (Issue #1783). Segments without a BKD tree for the field scan the stored documents.

Geo3dDistanceQuery / Geo3dBoundingBoxQuery / Geo3dNearestQuery

Three queries target 3D Geo3d fields backed by ECEF Cartesian coordinates (metres). Use them when altitude matters or when a 2D Geo field would introduce pole singularities. See 3D Geographic Search for the coordinate system, WGS84 conversion helpers, and worked examples.

#![allow(unused)]
fn main() {
use laurus::GeoEcefPoint;
use laurus::lexical::query::geo3d::{
    Geo3dDistanceQuery, Geo3dBoundingBoxQuery, Geo3dNearestQuery,
};

let centre = GeoEcefPoint::new(-3_955_182.0, 3_350_553.0, 3_700_276.0);

// Sphere: docs within 5 km of `centre`
let q = Geo3dDistanceQuery::new("position", centre, 5_000.0);

// Axis-aligned 3D bounding box (constructor validates min ≤ max per axis)
let min = GeoEcefPoint::new(-4_000_000.0, 3_300_000.0, 3_650_000.0);
let max = GeoEcefPoint::new(-3_900_000.0, 3_400_000.0, 3_750_000.0);
let q = Geo3dBoundingBoxQuery::new("position", min, max)?;

// k-NN: 10 nearest neighbours, with a custom radius schedule
let q = Geo3dNearestQuery::new("position", centre, 10)
    .with_initial_radius(500.0)
    .with_max_radius(1_000_000.0);
}
QueryScore
Geo3dDistanceQuery1 - distance / radius, clamped to [0, 1].
Geo3dBoundingBoxQueryConstant 1.0 for every match.
Geo3dNearestQueryNormalised so the closest hit is 1.0, the farthest in the returned set is 0.0.

Geo3d queries require the field to be indexed (indexed = true, the default): they run entirely on the field’s BKD tree and return no hits from segments that lack one — there is no stored-document fallback for 3D queries.

Geo3dPolylineQuery

Match documents with a point of a Geo3d field within a distance of the straight segments through a polyline’s vertices, in order: a flight path, a tunnel or a cable (Issue #1596).

#![allow(unused)]
fn main() {
use laurus::lexical::query::geo3d::{Geo3dPolyline, Geo3dPolylineQuery};
use laurus::util::ecef::wgs84_to_ecef;

// Within 500 m of a flight path at 1,000 m
let path = Geo3dPolyline::new(vec![
    wgs84_to_ecef(35.0, 139.0, 1_000.0),
    wgs84_to_ecef(35.4, 139.6, 1_000.0),
])?;
let query = Geo3dPolylineQuery::new("position", path, 500.0);
}

The distance is Euclidean in ECEF and the score 1 - distance / radius, clamped to [0, 1], by the closest point of a document, as Geo3dDistanceQuery’s; a single vertex finds what Geo3dDistanceQuery finds, with the same scores. An edge is a chord: between two points on the surface it runs below it, by about L² / 8R midway for an edge of length L (196 m for 100 km, about 20 km for 1,000 km), so a path that should follow the surface over long distances needs more vertices, or a Geo field and GeoPolylineQuery. Geo3dPolyline::new takes one vertex or more, repeated vertices included, and rejects a NaN or infinite coordinate. Like the other 3D queries it reads the field’s BKD tree only; a cell is pruned when no segment meets it widened by the distance on every side. The segments are kept in a tree of boxes, so a cell and a point reach only the segments near them, with the results of checking every segment (Issue #1783).

SpanQuery

Matches terms based on their proximity within a document. Use SpanTermQuery and SpanNearQuery to build proximity queries:

#![allow(unused)]
fn main() {
use laurus::lexical::query::span::{SpanQuery, SpanQueryWrapper, SpanTermQuery, SpanNearQuery};

// Find documents where "quick" appears near "fox" (within 3 positions)
let near = SpanNearQuery::new(
    "body",
    vec![
        Box::new(SpanTermQuery::new("body", "quick")) as Box<dyn SpanQuery>,
        Box::new(SpanTermQuery::new("body", "fox")) as Box<dyn SpanQuery>,
    ],
    3,    // slop (max distance between terms)
    true, // in_order (terms must appear in order)
);

// The query to search: a SpanQueryWrapper, which carries the boost
let query = SpanQueryWrapper::new(Box::new(near)).boost(2.0);
}

A span query is searched through a SpanQueryWrapper, and its boost goes there: it multiplies the score. The span queries inside (SpanTermQuery, SpanNearQuery, SpanContainingQuery, SpanWithinQuery) have no boost of their own, as in Lucene, since they only supply positions. They had a boost setter that changed nothing until Issue #1569 removed it.

Scoring

Lexical search results are scored using BM25. The score reflects how relevant a document is to the query:

  • Higher term frequency in the document increases the score
  • Rarer terms across the index increase the score
  • Shorter documents are boosted relative to longer ones

Wildcard, prefix, regexp and range queries are constant-scored instead: every match receives the query’s boost.

Hits with the same score are returned in ascending order of their internal document ids, the order in which the documents were written, so the pages of a search do not overlap while the index does not change (Issue #1740).

Field Boosts

You can boost specific fields to influence relevance using the SearchRequestBuilder:

#![allow(unused)]
fn main() {
use laurus::SearchRequestBuilder;
use laurus::lexical::TermQuery;
use laurus::lexical::search::searcher::LexicalSearchQuery;

let request = SearchRequestBuilder::new()
    .lexical_query(LexicalSearchQuery::Obj(Box::new(TermQuery::new("body", "rust"))))
    .add_field_boost("title", 2.0)  // title matches count double
    .add_field_boost("body", 1.0)
    .build();
}

Lexical Search Options

Lexical search behavior is controlled via LexicalSearchOptions on the SearchRequest, or by using builder methods on SearchRequestBuilder:

OptionDefaultDescription
field_boostsemptyPer-field score multipliers, each finite and at least 0 (-0.0 is rejected); 0 keeps a match with a score of 0 (a CombinedFields multi-field query still rejects 0)
min_score0.0Minimum score threshold; must be finite. A search rejects a negative boost, so scores are never negative and a negative threshold is the same as 0.0
timeout_msNoneSearch time budget in milliseconds (see note below)
parallelfalseEnable parallel search across segments
sort_byScoreSort by relevance score, or by a field (asc / desc)
highlightNoneFields (and configuration) to highlight in each hit’s SearchResult::highlights; see Highlighting

Field-sorted searches (sort_by: Field { .. }) always scan every candidate document — there is no early termination for field sorts, unlike the block-max-driven early termination available for score sorts. This guarantees the returned hits are the true top-K by field value rather than an early-terminated approximation, and it means a total, when one is asked for with track_total_hits, is exact below its threshold however many segments the index has. A score-sorted search counts exactly up to the threshold too, by not pruning until it is reached (see Total hits).

When timeout_ms is set, the time budget is enforced cooperatively during the search: the scan loops (including each segment of a multi-segment fanout) check the deadline periodically and abort as soon as the budget is used up, returning a timeout error rather than running the query to completion first. The check is batched (every few thousand scanned documents), so an unset timeout_ms and the common in-budget case pay no measurable overhead.

Builder Methods

SearchRequestBuilder provides convenience methods for lexical options:

#![allow(unused)]
fn main() {
use laurus::SearchRequestBuilder;
use laurus::lexical::TermQuery;
use laurus::lexical::search::searcher::{LexicalSearchQuery, SortField, SortOrder};

let request = SearchRequestBuilder::new()
    .lexical_query(LexicalSearchQuery::Obj(Box::new(TermQuery::new("body", "rust"))))
    .lexical_min_score(0.5)
    .lexical_timeout_ms(5000)
    .lexical_parallel(true)
    .sort_by(SortField::Field { name: "date".to_string(), order: SortOrder::Desc })
    .add_field_boost("title", 2.0)
    .add_field_boost("body", 1.0)
    .limit(20)
    .build();
}

.highlight(fields) and .highlight_config(config) request highlighted fragments per hit — see Highlighting.

Using the Query DSL

Instead of building queries programmatically, you can use the text-based Query DSL:

#![allow(unused)]
fn main() {
use laurus::lexical::QueryParser;
use laurus::analysis::analyzer::standard::StandardAnalyzer;
use std::sync::Arc;

let analyzer = Arc::new(StandardAnalyzer::default());
let parser = QueryParser::new(analyzer).with_default_field("body");

// Simple term
let query = parser.parse("rust")?;

// Boolean
let query = parser.parse("rust AND programming")?;

// Phrase
let query = parser.parse("\"machine learning\"")?;

// Field-specific
let query = parser.parse("title:rust AND body:programming")?;

// Fuzzy
let query = parser.parse("programing~2")?;

// Range
let query = parser.parse("year:[2020 TO 2024]")?;

// DateTime range (date-only bounds are midnight UTC)
let query = parser.parse("created_at:[2024-01-01 TO 2024-12-31]")?;
}

See Query DSL for the complete syntax reference.

Filter Result Cache

Filter clauses — tenancy, category, status flags, and similar — are frequently reused across many requests. Re-evaluating them from scratch every time re-walks the same posting lists. Laurus memoises the set of document ids a filter matches so a repeated filter becomes a single lookup instead of a full posting walk.

  • Snapshot-scoped, self-invalidating. The cache lives on the reader, which is rebuilt on every commit() / optimize() / refresh(). Each reader is a point-in-time snapshot, so the cache needs no manual invalidation: after the index changes, the next search starts from a fresh, empty cache and always reflects committed data.
  • Score-independent. A filter selects documents without affecting relevance, so the cached value is a plain doc-id set (a Roaring bitmap). It is used for the filter_query of a hybrid / filtered search and feeds both the lexical and vector sides.
  • Reused inside boolean queries. An Occur::Filter clause within a BooleanQuery (e.g. must(user_query).filter(tenant_filter)) also draws its matched set from the cache instead of re-walking postings — including the per-segment fan-out path on multi-segment indexes, where each segment takes from the cached set only the documents it holds. Until Issue #1743 each segment took the whole set: a BooleanQuery of filters without a Must clause returned a document once per segment, and its MustNot clauses excluded only the segment’s own documents.
  • Safe by construction. Only queries with a canonical key are cached. Term, phrase, prefix, wildcard, regexp, fuzzy, range, geo, and geo3d queries are cacheable, as are boolean queries composed entirely of cacheable clauses with at least one positive (Must / Should / Filter) clause. Boolean queries with no positive clause, span queries, and multi-field queries are evaluated fresh (never cached), so results are always correct.

The cache is enabled by default. Tune or disable it via the index config; without it, a filter clause is matched against each segment’s postings on every search:

#![allow(unused)]
fn main() {
use laurus::lexical::store::config::LexicalIndexConfig;

let config = LexicalIndexConfig::builder()
    .query_filter_cache_capacity(4096) // entries per snapshot; 0 disables the cache
    .build();
}

Parsed Query Cache

Searching with a DSL string (SearchRequest::from_dsl, or a LexicalSearchQuery::Dsl) parses the string with the pest grammar and re-tokenises its terms with the analyzer on every call. Autocomplete and popular-query workloads repeat the same strings, so Laurus memoises dsl string → parsed query: a repeated DSL string is parsed once and then reused (a cheap clone of the parsed query tree).

Like the filter cache, it is snapshot-scoped: the cache lives on the searcher, which is rebuilt on every commit() / optimize() / refresh(). The analyzer and default fields are fixed for that searcher, so the DSL string alone is the key; a schema/analyzer change yields a fresh, empty cache. Enabled by default; tune or disable via the index config:

#![allow(unused)]
fn main() {
use laurus::lexical::store::config::LexicalIndexConfig;

let config = LexicalIndexConfig::builder()
    .parsed_query_cache_capacity(2048) // entries per snapshot; 0 disables the cache
    .build();
}

Posting Cache

Evaluating a term reads its posting list from the segment’s .post file and decodes it (varint doc-ids, deletion filtering, skip table). Without caching, every query for the same term repeats that read + decode — and on cloud/remote storage the read dominates. Each segment reader keeps a small cache of decoded, deletion-filtered posting lists, so a repeated (field, term) lookup within a snapshot reuses the decoded list. The per-term iterator shares the cached list directly (a reference-count bump, not a copy), so evaluating a term never duplicates its posting arrays — this removed the dominant allocation cost on the multi-segment scoring path.

A segment reader’s deletions are fixed for its life, so a cached list is always consistent with them. A commit that leaves a segment unchanged keeps its reader, and the cache with it; a segment whose deletions changed gets a new reader with an empty cache (see Reading After a Commit). The cache is byte-budget bounded (posting lists vary widely in size) — least-recently-used lists are evicted once the budget is exceeded, and a single list larger than the whole budget is not cached. It is enabled by default, and each segment’s cache gets its own max_cache_memory budget (default 128 MiB, which also bounds the reader’s term-info cache), so the worst case grows with the segment count. Control it via the index config:

#![allow(unused)]
fn main() {
use laurus::lexical::store::config::LexicalIndexConfig;

let config = LexicalIndexConfig::builder()
    .enable_posting_cache(false) // disable entirely
    .build();

let config = LexicalIndexConfig::builder()
    .max_cache_memory(256 * 1024 * 1024) // or resize the per-segment budget (bytes)
    .build();
}

Next Steps