---
title: Query an AI Search index
description: Query a Databricks AI Search index with the Python SDK, REST API, or SQL using ANN, hybrid, or full-text search, plus filters, pagination, and reranking.
canonical_url: https://docs.databricks.com/aws/en/ai-search/query-ai-search
---

# Query an AI Search index

You can query an AI Search index with the Python SDK, the REST API, or the SQL `vector_search()` function. AI Search supports ANN, hybrid, and full-text query types, along with pagination, filters, and reranking to tune retrieval quality.

For example notebooks illustrating how to create and query AI Search endpoints and indexes, see [AI Search example notebooks](https://docs.databricks.com/aws/en/ai-search/example-notebooks.md). For reference information, see the [Python SDK reference](https://api-docs.databricks.com/python/ai-search/databricks.ai_search.html).

Databricks AI Search was formerly known as Databricks Vector Search. The REST API and several other tools use Vector Search in paths and identifiers, such as `/api/2.0/vector-search/indexes`. See [API and tool names](https://docs.databricks.com/aws/en/ai-search/ai-search.md#vector-search-names).

## Installation

To use the AI Search SDK, you must install it in your notebook. Use the following code to install the package:

```
%pip install databricks-ai-search
dbutils.library.restartPython()
```

Then use the following command to import `AISearchClient`:

```
from databricks.ai_search.client import AISearchClient
```

For information about authentication, see [Data protection and authentication](https://docs.databricks.com/aws/en/ai-search/ai-search.md#authentication).

## <a id="query" />How to query an AI Search index

You can only query the AI Search index using the Python SDK, the REST API, or the SQL `vector_search()` AI function.

> [!NOTE]
>
> The user or service principal querying the index must have the following Unity Catalog privileges:
>
> * USE CATALOG on the catalog that contains the AI Search index.
> * USE SCHEMA on the schema that contains the AI Search index.
> * SELECT on the AI Search index. The index owner already has this privilege.
>
> Users must also have the **Workspace access** entitlement. Users with only the consumer access entitlement receive a 403 error. See [Manage entitlements](https://docs.databricks.com/aws/en/security/auth/entitlements.md).
>
> For an index that uses a Databricks-managed embedding model, the calling identity might also need permissions on its embedding model serving endpoints. See [Set up a service principal](https://docs.databricks.com/aws/en/ai-search/high-qps.md#service-principal), which also covers setting up a service principal for production queries.

The default query type is `ann` (approximate nearest neighbor). For details about the different retrieval algorithms, see [Retrieval algorithms](https://docs.databricks.com/aws/en/ai-search/query-ai-search.md#retrieval).

* To perform a hybrid keyword-similarity search, set the parameter `query_type` to `hybrid`. By default, hybrid search includes all text metadata columns and returns a maximum of 200 results.
* To use the reranker in a query, see [Use the reranker in a query](https://docs.databricks.com/aws/en/ai-search/query-ai-search.md#rerank).

> [!NOTE]
> **Beta**
>
> Full-text search is available as a beta feature. To perform a full-text search, set the parameter `query_type` to `FULL_TEXT`. With full-text search, you can retrieve up to 10,000 results based on keyword matching without using vector embeddings. Full-text queries are supported on both standard and storage-optimized endpoints. On storage-optimized endpoints, you can also create a dedicated full-text search index without embeddings. See [Create a full-text search index (Beta)](https://docs.databricks.com/aws/en/ai-search/create-ai-search.md#create-full-text-index). To search selected text columns, sort results, or return aggregate counts for full-text and hybrid queries, see [Search selected text columns, sort results, and return aggregations (Beta)](https://docs.databricks.com/aws/en/ai-search/query-ai-search.md#search-sort-facet-results).
>
> For a full-text query, `manifest.total_hit_count` reports the number of matching documents independently of `num_results`. Counts of 10,000 or fewer are exact. For a larger match set, AI Search might report a lower bound.
>
> The `manifest.total_hit_count_lower_bound` field indicates how to interpret the count. A value of `false` means that `total_hit_count` is exact. A value of `true` means that it is a lower bound.

### Python SDK standard endpoint

For details, see the [Python SDK reference](https://api-docs.databricks.com/python/ai-search/databricks.ai_search.html).

```python
# Delta Sync Index with embeddings computed by Databricks
results = index.similarity_search(
    query_text="Greek myths",
    columns=["id", "field2"],
    num_results=2
    )

# Delta Sync Index using hybrid search, with embeddings computed by Databricks
results3 = index.similarity_search(
    query_text="Greek myths",
    columns=["id", "field2"],
    num_results=2,
    query_type="hybrid"
    )

# Delta Sync Index using full-text search (Beta)
results4 = index.similarity_search(
    query_text="Greek myths",
    columns=["id", "field2"],
    num_results=2,
    query_type="FULL_TEXT"
    )

# Delta Sync Index with pre-calculated embeddings
results2 = index.similarity_search(
    query_vector=[0.9] * 1024,
    columns=["id", "text"],
    num_results=2
    )
```

### Python SDK storage-optimized endpoint

For details, see the [Python SDK reference](https://api-docs.databricks.com/python/ai-search/databricks.ai_search.html).

The existing filter interface has been re-designed for storage-optimized AI Search indexes to adopt a more SQL-like filter string instead of the filter dictionary used in standard AI Search endpoints.

```python
client = AISearchClient()
index = client.get_index(index_name="vector_search_demo.vector_search.en_wiki_index")

# similarity search with query vector
results = index.similarity_search(
    query_vector=[0.2, 0.33, 0.19, 0.52],
    columns=["id", "text"],
    num_results=2
)

# similarity search with query vector and filter string
results = index.similarity_search(
    query_vector=[0.2, 0.33, 0.19, 0.52],
    columns=["id", "text"],
    # this is a single filter string similar to SQL WHERE clause syntax
    filters="language = 'en' AND country = 'us'",
    num_results=2
)
```

### REST API

See the REST API reference documentation: [POST /api/2.0/vector-search/indexes/\{index\_name}/query](https://docs.databricks.com/api/workspace/vectorsearchindexes/queryindex).

For production applications, Databricks recommends using service principals instead of personal access tokens. In addition to improved security and access management, using service principals can improve performance by up to 100 msec per query.

The following code example illustrates how to query an index using a service principal.

```sh
export SP_CLIENT_ID=...
export SP_CLIENT_SECRET=...
export INDEX_NAME=...
export WORKSPACE_URL=https://...
export WORKSPACE_ID=...

# Set authorization details to generate OAuth token
export AUTHORIZATION_DETAILS='{"type":"unity_catalog_permission","securable_type":"table","securable_object_name":"'"$INDEX_NAME"'","operation": "ReadVectorIndex"}'
# If you are using an route_optimized embedding model endpoint, then you need to have additional authorization details to invoke the serving endpoint
# export EMBEDDING_MODEL_SERVING_ENDPOINT_ID=...
# export AUTHORIZATION_DETAILS="$AUTHORIZATION_DETAILS"',{"type":"workspace_permission","object_type":"serving-endpoints","object_path":"/serving-endpoints/'"$EMBEDDING_MODEL_SERVING_ENDPOINT_ID"'","actions": ["query_inference_endpoint"]}'

# Generate OAuth token
export TOKEN=$(curl -X POST  --url $WORKSPACE_URL/oidc/v1/token -u "$SP_CLIENT_ID:$SP_CLIENT_SECRET" --data 'grant_type=client_credentials' --data 'scope=all-apis' --data-urlencode 'authorization_details=['"$AUTHORIZATION_DETAILS"']' | jq .access_token | tr -d '"')

# Get index URL
export INDEX_URL=$(curl -X GET -H 'Content-Type: application/json' -H "Authorization: Bearer $TOKEN" --url $WORKSPACE_URL/api/2.0/vector-search/indexes/$INDEX_NAME | jq -r '.status.index_url' | tr -d '"')

# Query AI Search index.
curl -X GET -H 'Content-Type: application/json' -H "Authorization: Bearer $TOKEN" --url https://$INDEX_URL/query --data '{"num_results": 3, "query_vector": [...], "columns": [...], "debug_level": 1}'

# Query AI Search index.
curl -X GET -H 'Content-Type: application/json' -H "Authorization: Bearer $TOKEN" --url https://$INDEX_URL/query --data '{"num_results": 3, "query_text": "...", "columns": [...], "debug_level": 1}'
```

To get an OAuth token for the index URL from a notebook instead of a service principal, see [Get an OAuth token from a notebook](https://docs.databricks.com/aws/en/ai-search/query-ai-search.md#token-exchange).

The following code example illustrates how to query an index using a personal access token (PAT).

```sh
export TOKEN=...
export INDEX_NAME=...
export WORKSPACE_URL=https://...

# Query AI Search index with `query_vector`
curl -X GET -H 'Content-Type: application/json' -H "Authorization: Bearer $TOKEN" --url $WORKSPACE_URL/api/2.0/vector-search/indexes/$INDEX_NAME/query --data '{"num_results": 3, "query_vector": [...], "columns": [...], "debug_level": 1}'

# Query AI Search index with `query_text`
curl -X GET -H 'Content-Type: application/json' -H "Authorization: Bearer $TOKEN" --url $WORKSPACE_URL/api/2.0/vector-search/indexes/$INDEX_NAME/query --data '{"num_results": 3, "query_text": "...", "columns": [...], "debug_level": 1}'
```

### SQL

> [!IMPORTANT]
>
> The `vector_search()` AI function is in [Public Preview](https://docs.databricks.com/aws/en/release-notes/release-types.md).

To use this [AI function](https://docs.databricks.com/aws/en/large-language-models/ai-functions.md), see [`vector_search` function](https://docs.databricks.com/aws/en/sql/language-manual/functions/vector_search.md).

### <a id="token-exchange" />Get an OAuth token from a notebook

In a notebook that runs on Databricks compute, you can get an OAuth token for querying an index without a service principal. To do so, exchange the notebook's token for an OAuth token at the workspace `/oidc/v1/token` endpoint using OAuth 2.0 Token Exchange ([RFC 8693](https://www.rfc-editor.org/rfc/rfc8693.html)). As with the service principal example in the REST API tab, the exchanged token has `authorization_details` for the index, and you use it with the index URL.

> [!NOTE]
>
> This exchange works only from a notebook on Databricks compute in the same workspace. You can't use it with a personal access token that you create in user settings, or from outside Databricks compute, such as from your laptop. Outside Databricks compute, use [OAuth user-to-machine (U2M) authorization](https://docs.databricks.com/aws/en/dev-tools/auth/oauth-u2m.md) or a [service principal with an OAuth token](https://docs.databricks.com/aws/en/ai-search/high-qps.md#service-principal) instead.
>
> To query a Delta Sync index that uses a [Databricks-managed embedding model](https://docs.databricks.com/aws/en/ai-search/ai-search.md#options-for-providing-vector-embeddings) with `query_text` on the index URL, use a [service principal OAuth token](https://docs.databricks.com/aws/en/ai-search/high-qps.md#service-principal). The embedding model serving endpoint might reject an exchanged token with a 403 error.

The token exchange request uses the following fields:

* `grant_type`: `urn:ietf:params:oauth:grant-type:token-exchange`.
* `subject_token`: The notebook's token.
* `subject_token_type`: `urn:databricks:params:oauth:token-type:personal-access-token`.
* `requested_token_type`: `urn:ietf:params:oauth:token-type:access_token`.
* `scope`: `all-apis`.
* `authorization_details`: A JSON array that allows the `ReadVectorIndex` operation on the index. Also add one `workspace_permission` entry that allows `query_inference_endpoint` for each route-optimized embedding serving endpoint. Use the serving endpoint ID, not its name.

The identity that runs the notebook must have the Unity Catalog privileges listed in [How to query an AI Search index](https://docs.databricks.com/aws/en/ai-search/query-ai-search.md#query) on the index, and the serving endpoint permissions in [Set up a service principal](https://docs.databricks.com/aws/en/ai-search/high-qps.md#service-principal).

The exchanged token grants access to the index as that identity. Don't print, log, or share it.

#### Python

The following example runs in a notebook. It reads the notebook's token from the notebook context.

```python
import json
import requests

WORKSPACE_URL = "https://<workspace-url>"
INDEX_NAME = "<catalog>.<schema>.<index>"
TIMEOUT_SECONDS = 30

AUTHORIZATION_DETAILS = [
    {
        "type": "unity_catalog_permission",
        "securable_type": "table",
        "securable_object_name": INDEX_NAME,
        "operation": "ReadVectorIndex",
    },
    # If the index uses a route-optimized embedding model serving endpoint, also allow querying it:
    # {
    #     "type": "workspace_permission",
    #     "object_type": "serving-endpoints",
    #     "object_path": "/serving-endpoints/<serving-endpoint-id>",
    #     "actions": ["query_inference_endpoint"],
    # },
]

def get_oauth_token():
    # Read the notebook token on each call so that a refresh uses a current token.
    notebook_token = dbutils.notebook.entry_point.getDbutils().notebook().getContext().apiToken().get()
    response = requests.post(
        f"{WORKSPACE_URL}/oidc/v1/token",
        data={
            "grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
            "subject_token": notebook_token,
            "subject_token_type": "urn:databricks:params:oauth:token-type:personal-access-token",
            "requested_token_type": "urn:ietf:params:oauth:token-type:access_token",
            "scope": "all-apis",
            "authorization_details": json.dumps(AUTHORIZATION_DETAILS),
        },
        timeout=TIMEOUT_SECONDS,
    )
    if response.ok:
        return response.json()["access_token"]
    try:
        error = response.json().get("error")
    except ValueError:
        error = None
    # Report the status and OAuth error code, not the full response.
    raise RuntimeError(f"Token exchange failed: status {response.status_code}, error {error}")

headers = {"Authorization": f"Bearer {get_oauth_token()}"}

# Get the index URL, then query the index
index_response = requests.get(
    f"{WORKSPACE_URL}/api/2.0/vector-search/indexes/{INDEX_NAME}", headers=headers, timeout=TIMEOUT_SECONDS
)
index_response.raise_for_status()
index_url = index_response.json()["status"]["index_url"]

query_response = requests.post(
    f"https://{index_url}/query",
    headers=headers,
    json={"num_results": 3, "query_text": "...", "columns": ["id", "text"]},
    timeout=TIMEOUT_SECONDS,
)
query_response.raise_for_status()
results = query_response.json()
```

#### curl

The following example does the same exchange with curl. Run it in a notebook on Databricks compute. Use this example if you already have the notebook's token in the `SUBJECT_TOKEN` environment variable. To get the notebook's token, use the Python example.

```sh
set -uo pipefail

export INDEX_NAME=...
export WORKSPACE_URL=https://...

export AUTHORIZATION_DETAILS='{"type":"unity_catalog_permission","securable_type":"table","securable_object_name":"'"$INDEX_NAME"'","operation":"ReadVectorIndex"}'

# Tokens are passed on stdin, which keeps them out of the process list.
RESPONSE=$(printf '%s' "$SUBJECT_TOKEN" | curl -sS -X POST --url "$WORKSPACE_URL/oidc/v1/token" \
  --write-out '\n%{http_code}' \
  --data 'grant_type=urn:ietf:params:oauth:grant-type:token-exchange' \
  --data-urlencode 'subject_token@-' \
  --data 'subject_token_type=urn:databricks:params:oauth:token-type:personal-access-token' \
  --data 'requested_token_type=urn:ietf:params:oauth:token-type:access_token' \
  --data 'scope=all-apis' \
  --data-urlencode 'authorization_details=['"$AUTHORIZATION_DETAILS"']')
STATUS=${RESPONSE##*$'\n'}
BODY=${RESPONSE%$'\n'*}
TOKEN=$(printf '%s' "$BODY" | jq -r '.access_token // empty' 2>/dev/null)
if [ -z "$TOKEN" ]; then
  ERROR=$(printf '%s' "$BODY" | jq -r '.error // empty' 2>/dev/null)
  # Report the status and OAuth error code, not the full response.
  echo "Token exchange failed: status $STATUS, error ${ERROR:-none}" >&2
  exit 1
fi

# Get index URL
INDEX_URL=$(printf 'Authorization: Bearer %s\n' "$TOKEN" | curl -sS -H @- --url "$WORKSPACE_URL/api/2.0/vector-search/indexes/$INDEX_NAME" | jq -r '.status.index_url')
if [ -z "$INDEX_URL" ] || [ "$INDEX_URL" = null ]; then
  echo "Failed to get the index URL" >&2
  exit 1
fi

# Query AI Search index
printf 'Authorization: Bearer %s\n' "$TOKEN" | curl -sS -X POST -H @- -H 'Content-Type: application/json' --url "https://$INDEX_URL/query" --data '{"num_results": 3, "query_text": "...", "columns": [...]}'
```

The exchanged token is short-lived, typically one hour. The `expires_in` field of the token response gives its lifetime in seconds. To refresh the token, repeat the exchange before the token expires.

> [!NOTE]
>
> For production applications, Databricks recommends a [service principal with an OAuth token](https://docs.databricks.com/aws/en/ai-search/high-qps.md#service-principal) instead of a token exchanged from a notebook.

### <a id="query-payload-logging" />Log query payloads (Beta)

Query payload logging writes AI Search query requests and responses to the `system.telemetry.otel_logs` system table for monitoring and retrieval quality analysis. It is available for indexes on standard and storage-optimized endpoints. When you create an index in Catalog Explorer with the **AI Search Quality Mode** preview enabled, query payload logging is on by default.

Databricks bills query payload logging by log volume at the [Zerobus Ingest OpenTelemetry rate](https://www.databricks.com/product/pricing/lakeflow-connect). These charges are separate from AI Search endpoint and index charges. Normal compute charges apply when you query or analyze the logs.

To use query payload logging, your workspace must be Unity Catalog-enabled and enrolled in the **AI Search Quality Mode** beta on the **Previews** page. To change the setting, you must have `USE CATALOG` on the index's catalog, `USE SCHEMA` on its schema, and `MODIFY` on the index.

On the index page in Catalog Explorer, use **Query payload logging** in the right sidebar to turn logging on or off.

To turn query payload logging on or off with the Python SDK, use `update_index_payload_logging()`. Indexes created with the SDK have query payload logging off unless you pass `payload_logging_enabled=True` when you create the index.

```python
from databricks.ai_search.client import AISearchClient

client = AISearchClient()
client.update_index_payload_logging(
    index_name="catalog.schema.index_name",
    payload_logging_enabled=True,
)
```

Set `payload_logging_enabled=False` to turn off logging.

By default, only account admins who are also metastore admins can read query payload logs. To grant another user access, see [Grant access to system tables](https://docs.databricks.com/aws/en/admin/system-tables/index.md#grant-access).

The following query returns AI Search payload logs for an index:

```sql
SELECT time, attributes, body
FROM system.telemetry.otel_logs
WHERE service_name = 'ai-search'
  AND attributes:['index_id']::STRING = '<index-id>'
ORDER BY time DESC;
```

For endpoint-level query rate, latency, and errors, see [Monitor AI Search endpoints](https://docs.databricks.com/aws/en/ai-search/monitor-endpoints.md).

### <a id="pagination" />Pagination

When a query requests more than 1,000 results, the results are automatically returned in pages of up to 1,000. The maximum number of results that a single query can return across all pages is 10,000. Both standard and storage-optimized endpoints support pagination.

Pagination works with all query types.

#### Python SDK

The Python SDK handles pagination transparently. When you set `num_results` to a value greater than 1,000, the SDK automatically retrieves all pages and returns the complete result set. No additional code is required.

```python
# The SDK automatically paginates and returns all 5000 results
results = index.similarity_search(
    query_text="Greek myths",
    columns=["id", "text"],
    num_results=5000
)
```

#### REST API

When you use the REST API directly, you must handle pagination manually. If more results are available, the response includes a `next_page_token` field. To retrieve the next page of results, pass this token to the query-next-page endpoint.

See the REST API reference documentation: [POST /api/2.0/vector-search/indexes/\{index\_name}/query-next-page](https://docs.databricks.com/api/workspace/vectorsearchindexes/querynextpage).

```sh
export TOKEN=...
export INDEX_NAME=...
export WORKSPACE_URL=https://...

# Initial query - if num_results exceeds 1000, the response includes next_page_token
curl -X GET -H 'Content-Type: application/json' -H "Authorization: Bearer $TOKEN" \
  --url $WORKSPACE_URL/api/2.0/vector-search/indexes/$INDEX_NAME/query \
  --data '{"num_results": 5000, "query_text": "...", "columns": ["id", "text"]}'

# Use next_page_token from the response to get the next page
curl -X GET -H 'Content-Type: application/json' -H "Authorization: Bearer $TOKEN" \
  --url $WORKSPACE_URL/api/2.0/vector-search/indexes/$INDEX_NAME/query-next-page \
  --data '{"page_token": "<next_page_token from previous response>"}'
```

Continue calling the query-next-page endpoint with the `next_page_token` from each response until the token is empty or absent, which indicates that all results have been returned.

### <a id="filters" />Use filters on queries

A query can define filters based on any indexed column in the Delta table. `similarity_search` returns only rows that match the specified filters.

The following table lists the supported filters.

> [!NOTE]
>
> For storage-optimized endpoints, results are overfetched. If you set `num_results` to `k`, more than `k` results are fetched, and the filter is applied to the fetched results. It is possible that no results will be returned even if there are results in the dataset that match the filter condition, if the score of these documents are not among the top.

| Filter operator                                   | Behavior                                                                                                                                                                                                                                                                                                                                                                                        | Examples                                                                                                                |
| ------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `NOT`                                             | **Standard**: Negates the filter. The key must end with “NOT”. For example, “color NOT” with value “red” matches documents where the color is not red.<br />**Storage-optimized**: See [`!=` (bangeq sign) operator](https://docs.databricks.com/aws/en/sql/language-manual/functions/bangeqsign.md).                                                                                           | **Standard**: `{"id NOT": 2}` `{“color NOT”: “red”}`<br />**Storage-optimized**: `"id != 2" "color != 'red'"`           |
| `<`                                               | **Standard**: Checks if the field value is less than the filter value. The key must end with ` <`. For example, `price <` with value 200 matches documents where the price is less than 200.<br />**Storage-optimized**: See [`<` (lt sign) operator](https://docs.databricks.com/aws/en/sql/language-manual/functions/ltsign.md).                                                              | **Standard**: `{"id <": 200}`<br />**Storage-optimized**: `"id < 200"`                                                  |
| `<=`                                              | **Standard**: Checks if the field value is less than or equal to the filter value. The key must end with ` <=`. For example, `price <=` with value 200 matches documents where the price is less than or equal to 200.<br />**Storage-optimized**: See [`<=` (lt eq sign) operator](https://docs.databricks.com/aws/en/sql/language-manual/functions/lteqsign.md).                              | **Standard**: `{"id <=": 200}`<br />**Storage-optimized**: `"id <= 200"`                                                |
| `>`                                               | **Standard**: Checks if the field value is greater than the filter value. The key must end with ` \>`. For example, `price \>` with value 200 matches documents where the price is greater than 200.<br />**Storage-optimized**: See [`>` (gt sign) operator](https://docs.databricks.com/aws/en/sql/language-manual/functions/gtsign.md).                                                      | **Standard**: `{"id >": 200}`<br />**Storage-optimized**: `"id > 200"`                                                  |
| `>=`                                              | **Standard**: Checks if the field value is greater than or equal to the filter value. The key must end with ` \>=`. For example, `price \>=` with value 200 matches documents where the price is greater than or equal to 200.<br />**Storage-optimized**: See [`>=` (gt eq sign) operator](https://docs.databricks.com/aws/en/sql/language-manual/functions/gteqsign.md).                      | **Standard**: `{"id >=": 200}`<br />**Storage-optimized**: `"id >= 200"`                                                |
| `OR`                                              | **Standard**: Checks if the field value matches any of the filter values. The key must contain `OR` to separate multiple subkeys. For example, `color1 OR color2` with value `["red", "blue"]` matches documents where either `color1` is `red` or `color2` is `blue`.<br />**Storage-optimized**: See [`or` operator](https://docs.databricks.com/aws/en/sql/language-manual/functions/or.md). | **Standard**: `{"color1 OR color2": ["red", "blue"]}`<br />**Storage-optimized**: `"color1 = 'red' OR color2 = 'blue'"` |
| `LIKE`                                            | **Standard**: Matches whitespace-separated tokens in a string.<br />**Storage-optimized**: See [`like` operator](https://docs.databricks.com/aws/en/sql/language-manual/functions/like.md).                                                                                                                                                                                                     | See [Notes on usage of `LIKE`](https://docs.databricks.com/aws/en/ai-search/query-ai-search.md#like).                   |
| No filter operator specified                      | **Standard**: Filter checks for an exact match. If multiple values are specified, it matches any of the values.<br />**Storage-optimized**: See [`=` (eq sign) operator](https://docs.databricks.com/aws/en/sql/language-manual/functions/eqsign.md) and [`in` predicate](https://docs.databricks.com/aws/en/sql/language-manual/functions/in.md).                                              | **Standard**: `{"id": 200}` `{"id": [200, 300]}`<br />**Storage-optimized**: `"id = 200"` `"id IN (200, 300)"`          |
| `to_timestamp` (storage-optimized endpoints only) | **Storage-optimized**: Filter on a timestamp. See [`to_timestamp` function](https://docs.databricks.com/aws/en/sql/language-manual/functions/to_timestamp.md)                                                                                                                                                                                                                                   | **Storage-optimized**: `"date > TO_TIMESTAMP('1995-01-01')"`                                                            |

#### <a id="like" />Notes on usage of `LIKE`

**`LIKE` examples for standard endpoints**

`{"column LIKE": "apple"}`: matches the strings "apple" and "apple pear" but does not match "pineapple". Note that it does not match "pineapple" even though it contains a substring "apple" – it looks for an exact match over whitespace separated tokens like in "apple pear".

`{"column NOT LIKE": "apple"}` does the opposite. It matches "pineapple" and "pear" but does not match "apple" or "apple pear".

**`LIKE` examples for storage-optimized endpoints**

| Format                    | Matches                                                                                                                               |
| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `"column LIKE 'apple'"`   | Equivalent to [`=`](https://docs.databricks.com/aws/en/sql/language-manual/functions/eqsign.md) operator. Returns only exact matches. |
| `"column LIKE 'apple%'"`  | Returns rows where a prefix matches `apple`, such as `applepie`.                                                                      |
| `"column LIKE '%apple'"`  | Returns rows where a suffix matches `apple`, such as `pineapple`.                                                                     |
| `"column LIKE '%apple%'"` | Returns rows that have a substring that matches `apple`, such as `pineapplecake`.                                                     |

#### Code examples

##### Python SDK standard endpoint

```python
# Match rows where `title` exactly matches `Athena` or `Ares`
results = index.similarity_search(
    query_text="Greek myths",
    columns=["id", "text"],
    filters={"title": ["Ares", "Athena"]},
    num_results=2
    )

# Match rows where `title` or `id` exactly matches `Athena` or `Ares`
results = index.similarity_search(
    query_text="Greek myths",
    columns=["id", "text"],
    filters={"title OR id": ["Ares", "Athena"]},
    num_results=2
    )

# Match only rows where `title` is not `Hercules`
results = index.similarity_search(
    query_text="Greek myths",
    columns=["id", "text"],
    filters={"title NOT": "Hercules"},
    num_results=2
    )
```

##### Python SDK storage-optimized endpoint

```python
# Match rows where `title` exactly matches `Athena` or `Ares`
results = index.similarity_search(
    query_text="Greek myths",
    columns=["id", "text"],
    filters='title IN ("Ares", "Athena")',
    num_results=2
    )

# Match rows where `title` or `id` exactly matches `Athena` or `Ares`
results = index.similarity_search(
    query_text="Greek myths",
    columns=["id", "text"],
    filters='title = "Ares" OR id = "Athena"',
    num_results=2
    )

# Match only rows where `title` is not `Hercules`
results = index.similarity_search(
    query_text="Greek myths",
    columns=["id", "text"],
    filters='title != "Hercules"',
    num_results=2
    )
```

##### REST API

See [POST /api/2.0/vector-search/indexes/\{index\_name}/query](https://docs.databricks.com/api/workspace/vectorsearchindexes/queryindex).

#### <a id="complex-column-filters" />Filter struct fields and map values

Filter a primitive struct field by using a dot-separated path. Filter a primitive map value by using bracket notation for the map key.

The following examples filter the `age` field in the `profile` struct and the `voltage` key in the `attrs` map:

##### Standard endpoint

```python
results = index.similarity_search(
    query_text="Greek myths",
    columns=["id", "text"],
    filters={"profile.age": 18, "attrs['voltage']": 9},
    num_results=10
)
```

##### Storage-optimized endpoint

```python
results = index.similarity_search(
    query_text="Greek myths",
    columns=["id", "text"],
    filters="profile.age = 18 AND attrs['voltage'] = 9",
    num_results=10
)
```

### <a id="search-sort-facet-results" />Search selected text columns, sort results, and return aggregations (Beta)

> [!NOTE]
> **Beta**
>
> The options for searching selected text columns, sorting, and returning aggregations are part of the **AI Search: Full-Text Search** beta. To use `query_columns`, `sort_columns`, or `facets`, enable **AI Search: Full-Text Search** in **Previews**. Contact your account team or see [Manage Databricks previews](https://docs.databricks.com/aws/en/admin/workspace-settings/manage-previews.md) to enable previews.

Use these options to search selected text fields, apply an explicit result order, or return aggregations for matching results.

These options are supported for full-text and hybrid queries. They are not supported for ANN queries.

**Search selected text columns**

Use `query_columns` to search only the specified text columns. If you omit it, the query searches all text columns.

```python
query_columns=["title", "text"]
```

**Sort results**

Use `sort_columns` to order results by column values instead of the default relevance order. Entries use the format `"<column> ASC"` or `"<column> DESC"`.

```python
sort_columns=["rating DESC", "publication_year DESC"]
```

**Return aggregations**

Use `facets` to return aggregate counts for matching results.

Value facets count matching results by distinct values in a column, such as language or category. `TOP` limits how many values are returned, and defaults to 10 if omitted.

```python
facets=["language TOP 5"]
```

Example response:

```json
{
  "facet_result": {
    "facet_array": [
      ["language", "en", 28],
      ["language", "el", 14]
    ]
  }
}
```

Numeric buckets count matching results that fall into specified numeric ranges, such as publication years or prices. Bucket bounds are inclusive.

```python
facets=["publication_year BUCKETS [[1900,1949],[1950,1999],[2000,2025]]"]
```

Example response:

```json
{
  "facet_result": {
    "facet_array": [
      ["publication_year", "[1900,1949]", 8],
      ["publication_year", "[1950,1999]", 14],
      ["publication_year", "[2000,2025]", 20]
    ]
  }
}
```

For full-text queries, AI Search computes aggregations over all results that match the query and filters, not only the rows returned in the response. For hybrid queries, AI Search applies sorting and aggregations to the bounded candidate set that hybrid search produces, not to every row in the index.

For REST API request fields and response schema, see [POST /api/2.0/vector-search/indexes/\{index\_name}/query](https://docs.databricks.com/api/workspace/vectorsearchindexes/queryindex).

### <a id="rerank" />Use the reranker in a query

Agent performance depends on retrieving the most relevant information for a query. Reranking is a technique that improves retrieval quality by evaluating the retrieved documents to identify the ones that are semantically most relevant. Databricks has developed a research-based compound AI system to identify these documents. You can also specify columns containing metadata that you want the reranker to use for additional context as it assesses each document's relevance.

Reranking incurs a small latency delay but can significantly improve retrieval quality and agent performance. Databricks recommends trying out reranking for any RAG agent use case.

The AI Search reranker is a [Databricks Designated Service](https://docs.databricks.com/aws/en/resources/designated-services.md) that uses [Databricks Geos](https://docs.databricks.com/aws/en/resources/databricks-geos.md) to manage data residency. Customers outside the US, EU, and Australia and New Zealand might need to [enable cross-Geo processing](https://docs.databricks.com/aws/en/resources/databricks-geos.md#cross-geo-processing) to use the reranker.

The examples in this section show how to use the AI Search reranker. When you use the reranker, you set the columns to return (`columns`) and the metadata columns to use for reranking (`columns_to_rerank`) separately. `num_results` is the final number of results to return. This does not affect the number of results used for reranking.

The query debug message includes information about how long the reranking step took. For example:

```Output
'debug_info': {'response_time': 693.0, 'ann_time': 29.0, 'reranker_time': 619.0}
```

If the reranker call fails, that information is included in the debug message:

```Output
'debug_info': {'response_time': 587.0, 'ann_time': 331.0, 'reranker_time': 246.0, 'warnings': [{'status_code': 'RERANKER_TEMPORARILY_UNAVAILABLE', 'message': 'The reranker is temporarily unavailable. Results returned have not been processed by the reranker. Please try again later for reranked results.'}]}
```

> [!NOTE]
>
> The order that columns are listed in `columns_to_rerank` is important. The reranking calculation takes the columns in the order they are listed, and considers only the first 2000 characters it finds.

#### Python SDK

```python
# Install the most recent version.
# Databricks SDK version 0.57 or above is required to use the reranker.
%pip install databricks-ai-search --force-reinstall
dbutils.library.restartPython()
```

```python
from databricks.ai_search.reranker import DatabricksReranker

results = index.similarity_search(
    query_text = "How to create an AI Search index",
    columns = ["id", "text", "parent_doc_summary", "date"],
    num_results = 10,
    query_type = "hybrid",
    reranker=DatabricksReranker(columns_to_rerank=["text", "parent_doc_summary", "other_column"])
    )
```

#### REST API

To ensure that you get latency information, set `debug_level` to at least 1.

```bash
export TOKEN=...
export INDEX_NAME=...
export WORKSPACE_URL=https://...

curl -X GET -H 'Content-Type: application/json' -H "Authorization: Bearer $TOKEN" --url $WORKSPACE_URL/api/2.0/vector-search/indexes/$INDEX_NAME/query --data '{"num_results": 10, "query_text": "How to create an AI Search index", "columns": ["id", "text", "parent_doc_summary", "date"], "reranker": {"model": "databricks_reranker",
             "parameters": {
               "columns_to_rerank":
                 ["text", "parent_doc_summary"]
              }
             },
"debug_level": 1}'
```

### <a id="filter-only" />Filter-only queries and point lookups

A filter-only query returns rows that match a filter without performing vector or keyword retrieval. Omit `query_text`, `query_vector`, and `query_type`, and specify `filters`. Filter-only queries support any indexed, filterable column on standard and storage-optimized endpoints.

The following examples return rows where `status` is `active`:

#### Standard endpoint

```python
results = index.similarity_search(
    columns=["id", "status"],
    filters={"status": "active"},
    num_results=100
)
```

#### Storage-optimized endpoint

```python
results = index.similarity_search(
    columns=["id", "status"],
    filters="status = 'active'",
    num_results=100
)
```

The `num_results` and pagination limits apply to filter-only queries. For a point lookup, filter on a primary key column.

## <a id="retrieval" />Retrieval algorithms

This section describes the different retrieval algorithms or query types and when each might be used. Use the `query_type` parameter to specify the retrieval algorithm to use. To automatically compare the performance of different algorithms for your index, see [Evaluate AI Search retrieval quality](https://docs.databricks.com/aws/en/ai-search/retrieval-quality-eval.md).

| Strategy                           | How it works                                                                    | Best for                                                                              |
| ---------------------------------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
| ANN (approximate nearest neighbor) | Searches using vector embeddings to find semantically similar documents.        | Conceptual and semantic queries where meaning matters more than exact wording.        |
| Full-text                          | Keyword search that matches on exact terms.                                     | Queries with specific terms, proper nouns, product IDs, or technical jargon.          |
| Hybrid                             | Combines ANN and full-text results using Reciprocal Rank Fusion (RRF).          | General-purpose retrieval. The recommended starting point for most use cases.         |
| Hybrid + reranker                  | Runs hybrid search, then re-scores results with a cross-encoder reranker model. | Higher precision when latency allows (typically under 1 second additional per query). |

### ANN (vector search)

ANN search converts a query into a vector embedding and finds documents whose embeddings are most similar. This is effective for understanding *meaning*. For example, a query like "how to fix a broken pipe" matches documents about plumbing even if they don't contain those exact words.

* **When ANN performs well**: Queries are conceptual, conversational, or use different vocabulary than the documents.
* **When ANN might underperform**: Queries rely on exact keywords, proper nouns, or domain-specific terminology that embeddings may not capture precisely.

### Full-text (keyword search)

Full-text search matches documents containing the query terms. Full-text search has high precision. When users search for specific names, codes, or technical terms, keyword matching finds exact hits that vector search might miss.

Use full-text or hybrid query options to search selected text columns, sort results, or return aggregate counts. See [Search selected text columns, sort results, and return aggregations (Beta)](https://docs.databricks.com/aws/en/ai-search/query-ai-search.md#search-sort-facet-results).

* **When full-text performs well**: Queries contain specific identifiers, product names, error codes, or domain-specific terminology.
* **When full-text might underperform**: Queries are phrased differently from the documents or use synonyms and paraphrases.

### Hybrid search

Hybrid search runs both ANN and full-text searches in parallel, then merges the results using Reciprocal Rank Fusion (RRF). This combines the semantic understanding of vector search with the precision of keyword matching.

* **When hybrid search performs well**: The query workload is a mix of conceptual and keyword-heavy queries. Hybrid is the most robust general-purpose strategy.

### Reranker

The reranker is an optional second pass applied on top of any strategy. After initial retrieval, a cross-encoder model re-evaluates each result in the context of the query, producing more accurate relevance ordering.

The reranker typically improves quality by approximately 10% but adds latency. It's suitable for applications where quality matters most such as RAG chatbots, but potentially less suitable for high-throughput, low-latency search applications.
