> ## 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)

***

#### 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)

***

#### 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).

### 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
```

Adds a sort stage to the query.

**Parameters**

| Parameter | Type                          |
| --------- | ----------------------------- |
| `expr`    | [`LogicalExpr`](#logicalexpr) |
| `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)

***

#### count()

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

Adds a count stage to the query.

**Returns**

[`Query`](#query)

***

#### topk()

```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] | 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"
    )
  )
  .topk(field("title_similarity"), 10)
)
```

**Parameters**

| Parameter     | Type                                                                                                                                                                                   |
| ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `field`       | str                                                                                                                                                                                    |
| `vector`      | list\[int] \| list\[float] \| dict\[int, float] \| dict\[int, int] \| [`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")
  )
  .topk(field("title_similarity"), 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"))
  .topk(field("text_score"), 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 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
    )
  )
  .topk(field("title_distance"), 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)

***

## 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)

***

### 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 keyword search for documents that contain specific keywords or phrases.

This function should be used in the filter stage of a query. You can configure
the match() function to:

* Match on multiple terms
* Match only on specific fields
* Use weights to prioritize certain terms

**Parameters**

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

**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

### 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)

***
