Filters
Create filters on fields marked as Filterable. Filters must be created after Init() and Load() are complete.
Never filter results client-side. Always use server-side filters so the engine applies them during search.
Filter creation returns null on failure and reports the reason via an out string? error
parameter: the field is unknown, it is not Filterable, a bound can't be parsed, or
the filter is the wrong kind for the field's type. null means rejected, never "no filter" —
passing it on would widen the search to the whole dataset.
The field's type decides the filter kind. A range filter needs a field whose values are numbers; a value filter needs a field whose values are not. Both used to be accepted and answered by walking every document. A value filter on a number was not only slow but wrong, because it compares text: asked for
129it missed129.0. Theerrornames the alternative.For an exact match on a numeric field, use a range with equal limits —
CreateRangeFilter("item_id", id, id, out _). It compares as numbers and reads the field's posting index. Note that a number stored as a JSON string is a text field, so it refuses a range filter: store the values as numbers and load again.
Value Filters
Array fields (prices.amount, editions.format) hold one value per element, and a value or range filter matches a document if any element matches. Combine with OR to filter at variant level while results stay one document per work.
Filter? categoryFilter = engine.CreateValueFilter("category", "electronics", out string? error);
if (categoryFilter is null)
throw new InvalidOperationException(error); // e.g. "Field 'category' is not filterable"Matching is case-insensitive by default. An overload takes the flag:
Filter? exact = engine.CreateValueFilter("category", "Electronics", isCaseSensitive: true, out _);A facet count equals the count of a (case-insensitive) value filter on the value it shows. Both kinds of filter read the field's posting index: a case-sensitive filter takes the posting of its value lowercased and checks the exact spelling on those documents only.
IN Filters
Documents whose value is one of a set: one filter for the whole set, in place of a value filter per value combined with OR.
Filter? brands = engine.CreateInFilter("brand", ["nike", "puma", "adidas"], out string? error);
// On a numeric field the values compare as numbers: 129 matches 129.0
Filter? sizes = engine.CreateInFilter("size", [38, 39, 40], out error);
// Case-sensitive, as for a value filter: each value matches only its own spelling
Filter? exact = engine.CreateInFilter("brand", ["Nike", "Puma"], isCaseSensitive: true, out error);On an array field one element in the set is enough. Duplicates and order do not matter: the same set makes the same filter, and one cache entry where an OR of value filters is 2n - 1 of them.
It loads as the union of the values' postings where the field has an index, and as one pass over the documents where it has not - an array field, for instance. An OR of value filters on such a field walks the documents once per value: on 500 000 documents a first search with 100 tags took 5.7 s that way, and 0.1 s as an IN filter.
null with the reason for an empty list, a null among the values, a value that is not a number
on a numeric field, or case sensitivity asked of numbers.
Range Filters
Filter? priceFilter = engine.CreateRangeFilter("price", 10.0, 100.0, out string? error);
// Equal limits are numeric equality -- the right way to match one value on a numeric field
Filter? oneItem = engine.CreateRangeFilter("item_id", 129, 129, out _);Both limits are inclusive. A range has no culture: the limits are doubles and the values are JSON numbers.
Position Filters
Documents whose position lies within a distance of a given position: "a shop within 1 km". A position is an object with two numbers in decimal degrees,
{ "id": 1, "name": "Karl Johan", "location": { "latitude": 59.9133, "longitude": 10.7389 } }which the engine holds as the Number fields location.latitude and location.longitude. Mark
both Filterable, and name the object when you create the filter:
engine.GetField("location.latitude")!.Filterable = true;
engine.GetField("location.longitude")!.Filterable = true;
// ... Load, Index ...
var here = new GeoPosition(59.9133f, 10.7389f);
Filter? nearby = engine.CreatePositionFilter("location", here, withinMeter: 1000, out string? error);
// The same distance the filter tests, to show next to a result
float meters = here.DistanceMeter(new GeoPosition(59.9097f, 10.7266f));- The distance is measured on a sphere with the Earth's mean radius, along the shortest way round: across the antimeridian where that is shorter. Both ends are inclusive.
- A document without a position, or with one off the Earth, does not match. One position per document: a position in an array is refused.
- The filter reads the two coordinates' numeric indexes and measures only the documents in a box around the circle, so it costs about what a range filter does.
- Its key describes it, like a range filter's: it can be rebuilt from its key and used over HTTP
(
POST filters/position). CreatePositionFilterreturnsnullwith the reason for a latitude outside ±90, a longitude outside ±180, a negative distance, or a field that holds no position.
Custom Filters
When neither a value nor a range says what you mean, define the filter yourself: a reader that
turns the stored value into a T, and a test of that T. The field must be Filterable.
// Documents whose 'size' is an odd number
Filter? odd = engine.CreateCustomFilter<double>("size",
(ReadOnlySpan<char> text, out double value) =>
double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out value),
value => value % 2 == 1,
out string? error);A value the reader rejects does not pass, nor does a document without the field; on an array
field one element passing is enough. A custom filter combines with every other filter through
&, | and !, and is kept current through inserts and updates. What sets it apart follows from
the engine being unable to see inside your delegates:
- It is loaded by walking the documents. No field index can answer a test it cannot read.
- It is pinned. Its key is a GUID (
UF;field;guid), which cannot describe the filter, so the filter cache never evicts it and it does not count toward the cache's size. It stays untilDeleteFilter,DeleteAllFiltersor the nextInit(). A filter made for one search must be deleted after it, or the cache grows with every search. - Two filters made separately are two filters. Reuse one by keeping the object.
- It exists only in this engine while it runs.
GetFilterFromKeyfinds it while it is in the cache, but cannot rebuild it from the key - after a restart, or over HTTP, its key is an unknown filter. Custom filters are a library feature and are not available through the server's API. - Both delegates must be pure, thread-safe and must not throw. They are called from several
threads, during searches and during inserts and updates. A delegate that throws makes the search
return its reason on
Result.Reason.
Date Filters
For a field holding Unix time - seconds since 1970-01-01 UTC, stored as a JSON number - two
filters take DateTime arguments. Each is a range filter over the seconds, so it loads from the
field index, leaves the cache like any other filter, and its key and expression rebuild it - a date
that changes with every search costs nothing to keep.
// The same date: equal on the UTC calendar date, the time of day of the argument ignored
Filter? today = engine.CreateDateFilter("published", DateTime.UtcNow, out string? error);
// From one instant to another, both inclusive
Filter? october = engine.CreateDateRangeFilter("published",
new DateTime(2026, 10, 1, 0, 0, 0, DateTimeKind.Utc),
new DateTime(2026, 10, 31, 23, 59, 59, DateTimeKind.Utc), out error);
CreateDateFiltermatches the date, not the instant.2026-10-16 08:00and2026-10-16 23:59make the same filter, and both pass a document stored at2026-10-16 00:00:01.
Every DateTime is taken as UTC: one of kind Local is converted, one of kind Unspecified is
read as UTC already. A stored number outside the years 1 to 9999 passes nothing.
Filter Expressions
The same filters, written as one expression:
Filter? filter = engine.CreateFilter(
"brand IN [\"nike\", \"puma\"] AND price BETWEEN 100 AND 2000 AND NOT category = \"outlet\"",
out IReadOnlyList<FilterExpressionError> errors);=,!=,<,<=,>,>=,IN [ ... ],BETWEEN a AND bandwithin(location, 59.91, 10.75, 1000)for a position filter.AND,OR,NOTand parentheses; NOT binds tightest, OR loosest. Keywords in any case.- Text in double quotes with JSON's escapes inside (
\",\\,\n,\u00e5and the rest), so a value written byJSON.stringifyor any JSON serializer drops in as it is. Numbers with.,true/false. A field name as written - nested fields with.- or in backticks:`Produsent/Importør` = "Tine". - Case is folded;
MATCHCASEafter a value or a list matches it:brand = "Nike" MATCHCASE. - On a numeric field
=andINcompare as numbers; on any other field a value is text, socode = 7does not match007. On an array field one element is enough.!=andNOTinclude the documents that have no value.
What it makes is an ordinary filter - the one CreateValueFilter, CreateRangeFilter,
CreateInFilter, CreatePositionFilter and the operators make, with the same key and token - so
it combines with &, | and ! like any other. Other filters, a custom one included, go into an
expression as placeholders:
Filter? f = engine.CreateFilter("($region OR $near) AND brand = \"nike\"",
new Dictionary<string, Filter> { ["region"] = region, ["near"] = near }, out var errors);filter.ToExpression() writes any filter but a custom one back as an expression that makes the
same key.
A filter expression that makes no filter returns null, and errors say what and where: one
syntax error with what to write instead ("A text value is written in double quotes", "write 1.5,
not 1,5", "Did you forget AND or OR"), or every error of meaning - an unknown field with a near
name, a field not Filterable, a comparison that does not fit the field's type, an empty range.
Each has a Kind, a Message, and a Start and Length in the text.
Combining Filters
// AND — both conditions must match
Filter combined = categoryFilter & priceFilter;
// OR — either condition matches
Filter either = categoryFilter | priceFilter;
// NOT — negate a filter
Filter excluded = !categoryFilter;
// Any number at once: one filter for the whole list, where a chain of & or | is one per link
Filter all = Filter.And(categoryFilter, priceFilter, inStock);
Filter any = Filter.Or(red, green, blue);Filter.And and Filter.Or drop a filter given twice and ignore the order, so the same set is the
same filter. An AND holding a filter that would walk every document to load - an array field, a
custom filter - checks it only on the documents the other filters leave: next to a selective
filter it costs what that filter costs.
Using Filters in Queries
query.Filter = combined;
// Check how many documents match
int count = combined.NumberOfDocumentsInFilter;
// Reset filter
query.Filter = null;Preloading Filters
For large datasets where many filters are applied simultaneously:
engine.LoadFilters(new[] { categoryFilter, priceFilter }, maxThreadCount: 2);
// Or preload all: engine.LoadAllFilters(maxThreadCount: 4);Constructors
FilterExpressionError(FilterExpressionErrorKind Kind, string Message, int Start, int Length, string Suggestion = null)One mistake in a filter expression: its kind, a message that says what to write instead, where it is (andin UTF-16 code units, the same as a JavaScript string's), and for an unknown field a near name.
FilterExpressionErrorKindKindstringMessageintStartintLengthstringSuggestion— Default: null
Properties
| Name | Type | Access | Description |
|---|---|---|---|
IsArray | bool | get | Set during Analyze if JsonObject is an Array. |
NumberOfDocumentsInFilter | int | get | Returns the number of documents that are contained in the filter. |
SerializedKey | string | get | Used internally exposed for ease of debugging. |
NeedsLoading | bool | get/set | May be used in order to check if filter is loaded. |
IsCaseSensitive | bool | get | True when text is compared with its case; false when case is folded. |
Count | int | get | How many distinct values the set holds. |
Position | GeoPosition | get | The position distances are measured from. |
WithinMeter | float | get | PositionThe largest distance, in metres, a document's position may lie from. |
Kind | FilterExpressionErrorKind | get/set | |
Message | string | get/set | |
Start | int | get/set | |
Length | int | get/set | |
Suggestion | string | get/set |
Methods
ToExpression
FilterExpressionError}@)This filter as a filter expression: whatturns back into this filter, with this key. Written from the key alone, so it says exactly what the filter is: a chain in its order, nesting in parentheses, a range by its limits, a position as within(...). Null for a filter that holds a custom filter, which no text describes.
string ToExpression()Returns: string
And
filtersA filter matching the documents every one ofmatches: one filter, and one cache entry, where a chain ofis one per link. Loaded cost-aware: the operands that can load from a field index choose the candidates, and an operand that would walk every document (an array field, a custom filter) is checked on those candidates only. A filter given twice counts once, and the order does not matter - the same set is the same filter. One filter returns itself.
static Filter And(Filter[] filters)Filter[]filters
Returns: Filter
Or
filtersA filter matching the documents any one ofmatches: one filter, and one cache entry, where a chain ofis one per link. A filter given twice counts once, and the order does not matter. One filter returns itself.
static Filter Or(Filter[] filters)Filter[]filters
Returns: Filter
ToString
string ToString()Returns: string
GetHashCode
int GetHashCode()Returns: int
Equals
bool Equals(object obj)objectobj
Returns: bool
<Clone>$
FilterExpressionError <Clone>$()Returns: FilterExpressionError
Deconstruct
void Deconstruct(FilterExpressionErrorKind& Kind, String& Message, Int32& Start, Int32& Length, String& Suggestion)FilterExpressionErrorKind&KindString&MessageInt32&StartInt32&LengthString&Suggestion
Operands
keyThe operands of, in the order they stand.
static IEnumerable<FilterOperand> Operands(string key)stringkey
Returns: IEnumerable<FilterOperand>
GeoPositionstruct
A position on the Earth in decimal degrees: latitude from -90 (south) to 90 (north), longitude from -180 (west) to 180 (east). In a document it is an object with the two numbers,.
| Name | Type | Description |
|---|---|---|
Latitude | float | |
Longitude | float | |
IsValid | bool | True when both coordinates are numbers within their ranges: latitude within ±90,
longitude within ±180. |