> ## Documentation Index
> Fetch the complete documentation index at: https://docs.topk.io/llms.txt
> Use this file to discover all available pages before exploring further.

# topk_sdk.query

## Classes

### LogicalExpr

*Internal*

Instances of the `LogicalExpr` class are used to represent logical expressions in TopK.
Usually created using logical constructors such as [`field()`](#field), [`literal()`](#literal), etc.

**Methods**

#### is\_null()

```python theme={null}
is_null(self) -> LogicalExpr
```

Check if the expression is null.

**Returns**

[`LogicalExpr`](#logicalexpr)

***

#### is\_not\_null()

```python theme={null}
is_not_null(self) -> LogicalExpr
```

Check if the expression is not null.

**Returns**

[`LogicalExpr`](#logicalexpr)

***

#### abs()

```python theme={null}
abs(self) -> LogicalExpr
```

Compute the absolute value of the expression.

**Returns**

[`LogicalExpr`](#logicalexpr)

***

#### ln()

```python theme={null}
ln(self) -> LogicalExpr
```

Compute the natural logarithm of the expression.

**Returns**

[`LogicalExpr`](#logicalexpr)

***

#### exp()

```python theme={null}
exp(self) -> LogicalExpr
```

Compute the exponential of the expression.

**Returns**

[`LogicalExpr`](#logicalexpr)

***

#### sqrt()

```python theme={null}
sqrt(self) -> LogicalExpr
```

Compute the square root of the expression.

**Returns**

[`LogicalExpr`](#logicalexpr)

***

#### square()

```python theme={null}
square(self) -> LogicalExpr
```

Compute the square of the expression.

**Returns**

[`LogicalExpr`](#logicalexpr)

***

#### eq()

```python theme={null}
eq(self, other: FlexibleExpr) -> LogicalExpr
```

Check if the expression is equal to another expression.

**Parameters**

| Parameter | Type                            |
| --------- | ------------------------------- |
| `other`   | [`FlexibleExpr`](#flexibleexpr) |

**Returns**

[`LogicalExpr`](#logicalexpr)

***

#### ne()

```python theme={null}
ne(self, other: FlexibleExpr) -> LogicalExpr
```

Check if the expression is not equal to another expression.

**Parameters**

| Parameter | Type                            |
| --------- | ------------------------------- |
| `other`   | [`FlexibleExpr`](#flexibleexpr) |

**Returns**

[`LogicalExpr`](#logicalexpr)

***

#### lt()

```python theme={null}
lt(self, other: Ordered) -> LogicalExpr
```

Check if the expression is less than another expression.

**Parameters**

| Parameter | Type                  |
| --------- | --------------------- |
| `other`   | [`Ordered`](#ordered) |

**Returns**

[`LogicalExpr`](#logicalexpr)

***

#### lte()

```python theme={null}
lte(self, other: Ordered) -> LogicalExpr
```

Check if the expression is less than or equal to another expression.

**Parameters**

| Parameter | Type                  |
| --------- | --------------------- |
| `other`   | [`Ordered`](#ordered) |

**Returns**

[`LogicalExpr`](#logicalexpr)

***

#### gt()

```python theme={null}
gt(self, other: Ordered) -> LogicalExpr
```

Check if the expression is greater than another expression.

**Parameters**

| Parameter | Type                  |
| --------- | --------------------- |
| `other`   | [`Ordered`](#ordered) |

**Returns**

[`LogicalExpr`](#logicalexpr)

***

#### gte()

```python theme={null}
gte(self, other: Ordered) -> LogicalExpr
```

Check if the expression is greater than or equal to another expression.

**Parameters**

| Parameter | Type                  |
| --------- | --------------------- |
| `other`   | [`Ordered`](#ordered) |

**Returns**

[`LogicalExpr`](#logicalexpr)

***

#### add()

```python theme={null}
add(self, other: Numeric) -> LogicalExpr
```

Add another value to the expression.

**Parameters**

| Parameter | Type                  |
| --------- | --------------------- |
| `other`   | [`Numeric`](#numeric) |

**Returns**

[`LogicalExpr`](#logicalexpr)

***

#### sub()

```python theme={null}
sub(self, other: Numeric) -> LogicalExpr
```

Subtract another value from the expression.

**Parameters**

| Parameter | Type                  |
| --------- | --------------------- |
| `other`   | [`Numeric`](#numeric) |

**Returns**

[`LogicalExpr`](#logicalexpr)

***

#### mul()

```python theme={null}
mul(self, other: Numeric) -> LogicalExpr
```

Multiply the expression by another value.

**Parameters**

| Parameter | Type                  |
| --------- | --------------------- |
| `other`   | [`Numeric`](#numeric) |

**Returns**

[`LogicalExpr`](#logicalexpr)

***

#### div()

```python theme={null}
div(self, other: Numeric) -> LogicalExpr
```

Divide the expression by another value.

**Parameters**

| Parameter | Type                  |
| --------- | --------------------- |
| `other`   | [`Numeric`](#numeric) |

**Returns**

[`LogicalExpr`](#logicalexpr)

***

#### min()

```python theme={null}
min(self, other: Ordered) -> LogicalExpr
```

Compute the minimum of the expression and another value.

**Parameters**

| Parameter | Type                  |
| --------- | --------------------- |
| `other`   | [`Ordered`](#ordered) |

**Returns**

[`LogicalExpr`](#logicalexpr)

***

#### max()

```python theme={null}
max(self, other: Ordered) -> LogicalExpr
```

Compute the maximum of the expression and another value.

**Parameters**

| Parameter | Type                  |
| --------- | --------------------- |
| `other`   | [`Ordered`](#ordered) |

**Returns**

[`LogicalExpr`](#logicalexpr)

***

#### date\_part()

```python theme={null}
date_part(self, part: DatePart) -> LogicalExpr
```

Extract a part of a timestamp expression as an integer.

Supported parts:

* `"year"` — calendar year
* `"month"` — 1-12
* `"week"` — ISO week number
* `"day"` — day of month, 1-31
* `"day_of_year"` — 1-366
* `"day_of_week"` — 0-6, Monday = 0
* `"hour"` — 0-23
* `"minute"` — 0-59
* `"second"` — 0-59
* `"millisecond"` — 0-999

**Parameters**

| Parameter | Type                    |
| --------- | ----------------------- |
| `part`    | [`DatePart`](#datepart) |

**Returns**

[`LogicalExpr`](#logicalexpr)

***

#### and\_()

```python theme={null}
and_(self, other: Boolish) -> LogicalExpr
```

Compute the logical AND of the expression and another expression.

**Parameters**

| Parameter | Type                  |
| --------- | --------------------- |
| `other`   | [`Boolish`](#boolish) |

**Returns**

[`LogicalExpr`](#logicalexpr)

***

#### or\_()

```python theme={null}
or_(self, other: Boolish) -> LogicalExpr
```

Compute the logical OR of the expression and another expression.

**Parameters**

| Parameter | Type                  |
| --------- | --------------------- |
| `other`   | [`Boolish`](#boolish) |

**Returns**

[`LogicalExpr`](#logicalexpr)

***

#### starts\_with()

```python theme={null}
starts_with(self, other: Stringy) -> LogicalExpr
```

Check if the expression starts with the provided string expression.
Can be applied on a string field or a list of strings field.

```python theme={null}
# Example:
from topk_sdk.query import field, starts_with

client.collection("books").query(
  filter(field("title").starts_with("The") | field("tags").starts_with("fiction"))
)
```

**Parameters**

| Parameter | Type                  |
| --------- | --------------------- |
| `other`   | [`Stringy`](#stringy) |

**Returns**

[`LogicalExpr`](#logicalexpr)

***

#### contains()

```python theme={null}
contains(self, other: FlexibleExpr) -> LogicalExpr
```

Check if the expression contains another value.

**Parameters**

| Parameter | Type                            |
| --------- | ------------------------------- |
| `other`   | [`FlexibleExpr`](#flexibleexpr) |

**Returns**

[`LogicalExpr`](#logicalexpr)

***

#### in\_()

```python theme={null}
in_(self, other: Iterable) -> LogicalExpr
```

Check if the expression is in the provided iterable expression.

**Parameters**

| Parameter | Type                    |
| --------- | ----------------------- |
| `other`   | [`Iterable`](#iterable) |

**Returns**

[`LogicalExpr`](#logicalexpr)

***

#### match\_all()

```python theme={null}
match_all(self, other: StringyWithList) -> LogicalExpr
```

Check if the expression matches all terms against the field with keyword index.

**Parameters**

| Parameter | Type                                  |
| --------- | ------------------------------------- |
| `other`   | [`StringyWithList`](#stringywithlist) |

**Returns**

[`LogicalExpr`](#logicalexpr)

***

#### match\_any()

```python theme={null}
match_any(self, other: StringyWithList) -> LogicalExpr
```

Check if the expression matches any term against the field with keyword index.

**Parameters**

| Parameter | Type                                  |
| --------- | ------------------------------------- |
| `other`   | [`StringyWithList`](#stringywithlist) |

**Returns**

[`LogicalExpr`](#logicalexpr)

***

#### coalesce()

```python theme={null}
coalesce(self, other: Numeric) -> LogicalExpr
```

Coalesce nulls in the expression with another value.

**Parameters**

| Parameter | Type                  |
| --------- | --------------------- |
| `other`   | [`Numeric`](#numeric) |

**Returns**

[`LogicalExpr`](#logicalexpr)

***

#### choose()

```python theme={null}
choose(self, x: FlexibleExpr, y: FlexibleExpr) -> LogicalExpr
```

Choose between two values based on the expression.

**Parameters**

| Parameter | Type                            |
| --------- | ------------------------------- |
| `x`       | [`FlexibleExpr`](#flexibleexpr) |
| `y`       | [`FlexibleExpr`](#flexibleexpr) |

**Returns**

[`LogicalExpr`](#logicalexpr)

***

#### boost()

```python theme={null}
boost(self, condition: FlexibleExpr, boost: Numeric) -> LogicalExpr
```

Multiply the scoring expression by the provided `boost` value if the `condition` is true.

**Parameters**

| Parameter   | Type                            |
| ----------- | ------------------------------- |
| `condition` | [`FlexibleExpr`](#flexibleexpr) |
| `boost`     | [`Numeric`](#numeric)           |

**Returns**

[`LogicalExpr`](#logicalexpr)

***

#### elapsed()

```python theme={null}
elapsed(self, end: FlexibleExpr, interval: Interval) -> LogicalExpr
```

Compute the number of `interval` units elapsed between the expression and `end`.

**Parameters**

| Parameter  | Type                            |
| ---------- | ------------------------------- |
| `end`      | [`FlexibleExpr`](#flexibleexpr) |
| `interval` | [`Interval`](#interval)         |

**Returns**

[`LogicalExpr`](#logicalexpr)

***

#### regexp\_match()

```python theme={null}
regexp_match(self, pattern: str, flags: Optional[str] = None) -> LogicalExpr
```

Check if the expression matches the provided regexp pattern.

**Parameters**

| Parameter | Type           |
| --------- | -------------- |
| `pattern` | str            |
| `flags`   | Optional\[str] |

**Returns**

[`LogicalExpr`](#logicalexpr)

***

### FunctionExpr

*Internal*

Instances of the `FunctionExpr` class are used to represent function expressions in TopK.
Usually created using function constructors such as [`fn.vector_distance()`](#vector-distance), [`fn.semantic_similarity()`](#semantic-similarity) or [`fn.bm25_score()`](#bm25-score).

### AggregateExpr

*Internal*

Instances of the `AggregateExpr` class are used to represent aggregate expressions in TopK.
Usually created using aggregate constructors such as [`agg.count()`](#count), [`agg.sum()`](#sum), [`agg.min()`](#min-2), [`agg.max()`](#max-2) or [`agg.avg()`](#avg).

### TextExpr

*Internal*

Instances of the `TextExpr` class are used to represent text expressions in TopK.

### Query

**Methods**

#### select()

```python theme={null}
select(self) -> Query
```

Adds a select stage to the query.

**Returns**

[`Query`](#query)

***

#### filter()

```python theme={null}
filter(self, expr: LogicalExpr | TextExpr) -> Query
```

Adds a filter stage to the query.

**Parameters**

| Parameter | Type                                                     |
| --------- | -------------------------------------------------------- |
| `expr`    | [`LogicalExpr`](#logicalexpr) \| [`TextExpr`](#textexpr) |

**Returns**

[`Query`](#query)

***

#### sort()

```python theme={null}
sort(self, expr: LogicalExpr, asc: bool = True) -> Query
sort(self, expr: Sequence[tuple[LogicalExpr, Literal['asc', 'desc']]]) -> Query
```

Adds a sort stage to the query.

**Parameters**

| Parameter | Type                                                                                                       |
| --------- | ---------------------------------------------------------------------------------------------------------- |
| `expr`    | [`LogicalExpr`](#logicalexpr) \| Sequence\[tuple\[[`LogicalExpr`](#logicalexpr), Literal\['asc', 'desc']]] |
| `asc`     | bool                                                                                                       |

**Returns**

[`Query`](#query)

***

#### limit()

```python theme={null}
limit(self, k: int) -> Query
```

Adds a limit stage to the query.

**Parameters**

| Parameter | Type |
| --------- | ---- |
| `k`       | int  |

**Returns**

[`Query`](#query)

***

#### offset()

```python theme={null}
offset(self, offset: int) -> Query
```

Adds an offset stage to the query.

**Parameters**

| Parameter | Type |
| --------- | ---- |
| `offset`  | int  |

**Returns**

[`Query`](#query)

***

#### count()

```python theme={null}
count(self) -> Query
```

Adds a count stage to the query.

**Returns**

[`Query`](#query)

***

#### group\_by()

```python theme={null}
group_by(self, keys: dict[str, LogicalExpr], aggs: dict[str, AggregateExpr]) -> Query
```

Adds a group-by stage to the query.

Groups documents by one or more key expressions and computes aggregations for each group.

**Parameters**

| Parameter | Type                                          |
| --------- | --------------------------------------------- |
| `keys`    | dict\[str, [`LogicalExpr`](#logicalexpr)]     |
| `aggs`    | dict\[str, [`AggregateExpr`](#aggregateexpr)] |

**Returns**

[`Query`](#query)

***

#### topk()

<Warning>**Deprecated** — Use `.sort(expr, asc).limit(k)` instead.</Warning>

```python theme={null}
topk(self, expr: LogicalExpr, k: int, asc: bool = False) -> Query
```

Adds a top-k stage to the query.

**Parameters**

| Parameter | Type                          |
| --------- | ----------------------------- |
| `expr`    | [`LogicalExpr`](#logicalexpr) |
| `k`       | int                           |
| `asc`     | bool                          |

**Returns**

[`Query`](#query)

***

### fn

The `query.fn` submodule exposes functions for creating function expressions such as [`fn.vector_distance()`](#vector-distance), [`fn.semantic_similarity()`](#semantic-similarity) or [`fn.bm25_score()`](#bm25-score).

**Methods**

#### vector\_distance()

```python theme={null}
vector_distance(
   field: str,
   vector: list[int] | list[float] | dict[int, float] | dict[int, int] | numpy.ndarray | topk_sdk.data.SparseVector | topk_sdk.data.List,
   skip_refine: bool = False
)
```

Calculate the vector distance between a field and a query vector.

```python theme={null}
# Example:

from topk_sdk.query import field, fn, select

client.collection("books").query(
  select(
    "title",
    title_similarity=fn.vector_distance(
      "title_embedding",
      [0.1, 0.2, 0.3, ...] # embedding for "animal"
    )
  )
  .sort(field("title_similarity"), asc=False).limit(10)
)
```

**Parameters**

| Parameter     | Type                                                                                                                                                                                                    |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `field`       | str                                                                                                                                                                                                     |
| `vector`      | list\[int] \| list\[float] \| dict\[int, float] \| dict\[int, int] \| numpy.ndarray \| [`topk_sdk.data.SparseVector`](/sdk/topk-py/data#sparsevector) \| [`topk_sdk.data.List`](/sdk/topk-py/data#list) |
| `skip_refine` | bool                                                                                                                                                                                                    |

**Returns**

[`FunctionExpr`](#functionexpr)

***

#### semantic\_similarity()

```python theme={null}
semantic_similarity(field: str, query: str) -> FunctionExpr
```

Calculate the semantic similarity between a field and a query string.

```python theme={null}
# Example:

from topk_sdk.query import field, fn, select

client.collection("books").query(
  select(
    "title",
    title_similarity=fn.semantic_similarity("title", "animal")
  )
  .sort(field("title_similarity"), asc=False).limit(10)
)
```

**Parameters**

| Parameter | Type |
| --------- | ---- |
| `field`   | str  |
| `query`   | str  |

**Returns**

[`FunctionExpr`](#functionexpr)

***

#### bm25\_score()

```python theme={null}
bm25_score(b: Optional[float] = None, k1: Optional[float] = None) -> FunctionExpr
```

Calculate the BM25 score for a keyword search.

Optional parameters: b (0-1), k1 (>=0) to override BM25 scoring behavior.

```python theme={null}
# Example:

from topk_sdk.query import field, fn, select

client.collection("books").query(
  select(
    "title",
    text_score=fn.bm25_score()
  )
  .filter(match("animal"))
  .sort(field("text_score"), asc=False).limit(10)
)
```

**Parameters**

| Parameter | Type             |
| --------- | ---------------- |
| `b`       | Optional\[float] |
| `k1`      | Optional\[float] |

**Returns**

[`FunctionExpr`](#functionexpr)

***

#### multi\_vector\_distance()

```python theme={null}
multi_vector_distance(
   field: str,
   matrix: topk_sdk.data.Matrix | numpy.ndarray | list[list[float]] | list[list[int]],
   candidates: Optional[int] = None
)
```

Calculate the multi-vector distance between a field and a query matrix.

The query matrix can be a list of lists (defaults to f32), a [numpy array](https://numpy.org/doc/stable/reference/generated/numpy.array.html) (type inferred from dtype),
or a [`Matrix`](/sdk/topk-py/data#Matrix) instance. To specify a different matrix type,
use [`matrix()`](/sdk/topk-py/data#matrix-2) with `value_type` or a 2-D numpy array with the
corresponding dtype.

The optional `candidates` parameter limits the number of candidate vectors considered during search.

```python theme={null}
from topk_sdk.query import field, fn, select

client.collection("books").query(
  select(
    "title",
    title_distance=fn.multi_vector_distance(
      "title_embedding",
      [[0.1, 0.2, 0.3, ...], [0.4, 0.5, 0.6, ...]],
      candidates=100
    )
  )
  .sort(field("title_distance"), asc=False).limit(10)
)
```

**Parameters**

| Parameter    | Type                                                                                                            |
| ------------ | --------------------------------------------------------------------------------------------------------------- |
| `field`      | str                                                                                                             |
| `matrix`     | [`topk_sdk.data.Matrix`](/sdk/topk-py/data#matrix) \| numpy.ndarray \| list\[list\[float]] \| list\[list\[int]] |
| `candidates` | Optional\[int]                                                                                                  |

**Returns**

[`FunctionExpr`](#functionexpr)

***

### agg

The `query.agg` submodule exposes functions for creating aggregate expressions used in
[`group_by()`](#group-by)'s `aggs` argument, such as [`agg.count()`](#count), [`agg.sum()`](#sum),
[`agg.min()`](#min-2), [`agg.max()`](#max-2) or [`agg.avg()`](#avg).

**Methods**

#### count()

```python theme={null}
count(field: str | None = None) -> AggregateExpr
```

Count the number of documents in the group.

If `field` is provided, counts only the documents where that field is non-null.
If omitted, counts every document in the group.

```python theme={null}
# Example:
from topk_sdk.query import group_by, field, agg

client.collection("books").query(
  group_by(
    {"is_old": field("published_year") < 1940},
    {"count": agg.count()},
  )
)
```

**Parameters**

| Parameter | Type        |
| --------- | ----------- |
| `field`   | str \| None |

**Returns**

[`AggregateExpr`](#aggregateexpr)

***

#### sum()

```python theme={null}
sum(field: str) -> AggregateExpr
```

Sum the values of `field` across the group.

**Parameters**

| Parameter | Type |
| --------- | ---- |
| `field`   | str  |

**Returns**

[`AggregateExpr`](#aggregateexpr)

***

#### min()

```python theme={null}
min(field: str) -> AggregateExpr
```

Find the minimum value of `field` across the group.

**Parameters**

| Parameter | Type |
| --------- | ---- |
| `field`   | str  |

**Returns**

[`AggregateExpr`](#aggregateexpr)

***

#### max()

```python theme={null}
max(field: str) -> AggregateExpr
```

Find the maximum value of `field` across the group.

**Parameters**

| Parameter | Type |
| --------- | ---- |
| `field`   | str  |

**Returns**

[`AggregateExpr`](#aggregateexpr)

***

#### avg()

```python theme={null}
avg(field: str) -> AggregateExpr
```

Calculate the average value of `field` across the group.

**Parameters**

| Parameter | Type |
| --------- | ---- |
| `field`   | str  |

**Returns**

[`AggregateExpr`](#aggregateexpr)

***

## Functions

### field()

```python theme={null}
field(name: str) -> LogicalExpr
```

Select a field from the document.

**Parameters**

| Parameter | Type |
| --------- | ---- |
| `name`    | str  |

**Returns**

[`LogicalExpr`](#logicalexpr)

***

### select()

```python theme={null}
select() -> Query
```

Creates a new query with a select stage.

```python theme={null}
# Example:
from topk_sdk.query import select, field

client.collection("books").query(
  select("title", year=field("published_year"))
)
```

**Returns**

[`Query`](#query)

***

### filter()

```python theme={null}
filter(expr: LogicalExpr | TextExpr) -> Query
```

Creates a new query with a filter stage.

```python theme={null}
# Example:

from topk_sdk.query import filter, field

client.collection("books").query(
  filter(field("published_year") > 1980)
)
```

**Parameters**

| Parameter | Type                                                     |
| --------- | -------------------------------------------------------- |
| `expr`    | [`LogicalExpr`](#logicalexpr) \| [`TextExpr`](#textexpr) |

**Returns**

[`Query`](#query)

***

### group\_by()

```python theme={null}
group_by(keys: dict[str, LogicalExpr], aggs: dict[str, AggregateExpr]) -> Query
```

Creates a new query with a group-by stage.

Groups documents by one or more key expressions and computes aggregations for each group.

```python theme={null}
# Example:
from topk_sdk.query import group_by, field, agg

client.collection("books").query(
  group_by(
    {"is_old": field("published_year") < 1940},
    {"count": agg.count()},
  )
)
```

**Parameters**

| Parameter | Type                                          |
| --------- | --------------------------------------------- |
| `keys`    | dict\[str, [`LogicalExpr`](#logicalexpr)]     |
| `aggs`    | dict\[str, [`AggregateExpr`](#aggregateexpr)] |

**Returns**

[`Query`](#query)

***

### literal()

```python theme={null}
literal(value: Any) -> LogicalExpr
```

Create a literal expression.

**Parameters**

| Parameter | Type |
| --------- | ---- |
| `value`   | Any  |

**Returns**

[`LogicalExpr`](#logicalexpr)

***

### match()

```python theme={null}
match(token: str, field: str | None = None, weight: float = 1.0, all: bool = False) -> TextExpr
```

Perform a BM25 keyword search using TopK's built-in tokenizer.

The `token` argument is a raw query string — TopK tokenizes it automatically,
removes stop words, and scores documents using BM25. Pass the full query string
directly; tokenization and stop-word removal happen server-side.

* `field`: restrict matching to a specific keyword-indexed field (default: all).
* `weight`: scale the BM25 contribution of this expression (default: 1.0).
* `all`: if True, require all tokens to match (AND); default is any-token (OR).

**Parameters**

| Parameter | Type        |
| --------- | ----------- |
| `token`   | str         |
| `field`   | str \| None |
| `weight`  | float       |
| `all`     | bool        |

**Returns**

[`TextExpr`](#textexpr)

***

### should()

```python theme={null}
should(token: str, field: str | None = None, weight: float = 1.0) -> TextExpr
```

Adds an optional BM25 scoring term without filtering documents from the result set.

Documents containing the term receive a higher BM25 score, while documents that
do not contain it remain eligible for the results. Use `should()` together with
`match()` when some terms are required and others should only influence ranking.

When used on its own, `should()` matches the entire collection and ranks
documents according to how well they match the term.

```python theme={null}
match("hobbit rings", field="title") & should("lord", field="title")
```

This returns only documents matching `hobbit` or `rings`, while boosting
documents that also match `lord`.

* `field`: Keyword-indexed field used for scoring. Searches all eligible fields when omitted.
* `weight`: Multiplier applied to the term's BM25 contribution. Defaults to `1.0`.

**Parameters**

| Parameter | Type        |
| --------- | ----------- |
| `token`   | str         |
| `field`   | str \| None |
| `weight`  | float       |

**Returns**

[`TextExpr`](#textexpr)

***

### match\_tokens()

```python theme={null}
match_tokens(
   tokens: Sequence[str | tuple[str, float]],
   field: str | None = None,
   all: bool = False
)
```

Filters documents that match the provided tokens with optional per-token weights.

Each token can be a string (with the default weight of 1.0) or a (token, weight) tuple.

When `field` is provided, matches only against that field (must have a keyword index).
When `field` is None (default), matches against all keyword-indexed fields.

When `all` is False (default), matches documents containing any of the tokens (OR).
When `all` is True, matches only documents containing all tokens (AND).

**Parameters**

| Parameter | Type                                 |
| --------- | ------------------------------------ |
| `tokens`  | Sequence\[str \| tuple\[str, float]] |
| `field`   | str \| None                          |
| `all`     | bool                                 |

**Returns**

[`TextExpr`](#textexpr)

***

### not\_()

```python theme={null}
not_(expr: LogicalExpr) -> LogicalExpr
```

Negate a logical expression.

```python theme={null}
# Example:

from topk_sdk.query import field, not_

.filter(
    not_(field("title").contains("Catcher"))
)
```

**Parameters**

| Parameter | Type                          |
| --------- | ----------------------------- |
| `expr`    | [`LogicalExpr`](#logicalexpr) |

**Returns**

[`LogicalExpr`](#logicalexpr)

***

### abs()

```python theme={null}
abs(expr: LogicalExpr) -> LogicalExpr
```

Compute the absolute value of a logical expression.

```python theme={null}
# Example:

from topk_sdk.query import field, abs

client.collection("books").query(
  filter(abs(field("rating")) > 4.5)
)
```

**Parameters**

| Parameter | Type                          |
| --------- | ----------------------------- |
| `expr`    | [`LogicalExpr`](#logicalexpr) |

**Returns**

[`LogicalExpr`](#logicalexpr)

***

### all()

```python theme={null}
all(exprs: Sequence[LogicalExpr]) -> LogicalExpr
```

Create a logical AND expression.

```python theme={null}
# Example:

from topk_sdk.query import field, all

client.collection("books").query(
  filter(all([
    field("published_year") >= 1900,
    field("published_year") <= 2000,
    field("title").is_not_null()
  ]))
)
```

**Parameters**

| Parameter | Type                                     |
| --------- | ---------------------------------------- |
| `exprs`   | Sequence\[[`LogicalExpr`](#logicalexpr)] |

**Returns**

[`LogicalExpr`](#logicalexpr)

***

### any()

```python theme={null}
any(exprs: Sequence[LogicalExpr]) -> LogicalExpr
```

Create a logical OR expression.

```python theme={null}
# Example:

from topk_sdk.query import field, any

client.collection("books").query(
  filter(any([
    field("genre") == "fiction",
    field("genre") == "mystery",
    field("genre") == "thriller"
  ]))
)
```

**Parameters**

| Parameter | Type                                     |
| --------- | ---------------------------------------- |
| `exprs`   | Sequence\[[`LogicalExpr`](#logicalexpr)] |

**Returns**

[`LogicalExpr`](#logicalexpr)

***

### min()

```python theme={null}
min(left: Ordered, right: Ordered) -> LogicalExpr
```

Create a logical MIN expression.

```python theme={null}
# Example:

from topk_sdk.query import field, min

client.collection("books").query(
  filter(min(field("rating"), field("published_year")))
)
```

**Parameters**

| Parameter | Type                  |
| --------- | --------------------- |
| `left`    | [`Ordered`](#ordered) |
| `right`   | [`Ordered`](#ordered) |

**Returns**

[`LogicalExpr`](#logicalexpr)

***

### max()

```python theme={null}
max(left: Ordered, right: Ordered) -> LogicalExpr
```

Create a logical MAX expression.

```python theme={null}
from topk_sdk.query import field, max

client.collection("books").query(
  filter(max(field("rating"), field("published_year")))
)
```

**Parameters**

| Parameter | Type                  |
| --------- | --------------------- |
| `left`    | [`Ordered`](#ordered) |
| `right`   | [`Ordered`](#ordered) |

**Returns**

[`LogicalExpr`](#logicalexpr)

***

## Type Aliases

### DatePart

```python theme={null}
DatePart = Literal['year', 'month', 'week', 'day', 'day_of_year', 'day_of_week', 'hour', 'minute', 'second', 'millisecond']
```

**Type**

Literal\['year', 'month', 'week', 'day', 'day\_of\_year', 'day\_of\_week', 'hour', 'minute', 'second', 'millisecond']

***

### Interval

```python theme={null}
Interval = Literal['millisecond', 'second', 'minute', 'hour', 'day', 'week']
```

**Type**

Literal\['millisecond', 'second', 'minute', 'hour', 'day', 'week']

***

### FlexibleExpr

```python theme={null}
FlexibleExpr = str | int | float | bool | None | LogicalExpr
```

**Type**

str | int | float | bool | None | [`LogicalExpr`](#logicalexpr)

***

### Numeric

```python theme={null}
Numeric = int | float | LogicalExpr
```

**Type**

int | float | [`LogicalExpr`](#logicalexpr)

***

### Ordered

```python theme={null}
Ordered = int | float | str | LogicalExpr
```

**Type**

int | float | str | [`LogicalExpr`](#logicalexpr)

***

### Boolish

```python theme={null}
Boolish = bool | LogicalExpr
```

**Type**

bool | [`LogicalExpr`](#logicalexpr)

***

### Stringy

```python theme={null}
Stringy = str | LogicalExpr
```

**Type**

str | [`LogicalExpr`](#logicalexpr)

***

### StringyWithList

```python theme={null}
StringyWithList = str | list[str] | LogicalExpr
```

**Type**

str | list\[str] | [`LogicalExpr`](#logicalexpr)

***

### Iterable

```python theme={null}
Iterable = str | list[int] | list[float] | list[str] | topk_sdk.data.List | LogicalExpr
```

**Type**

str | list\[int] | list\[float] | list\[str] | [`topk_sdk.data.List`](/sdk/topk-py/data#list) | [`LogicalExpr`](#logicalexpr)

***
