---
type: api
title: Run a knn search
description: **All methods and paths for this operation:**
url: https://www.elastic.co/elastic/docs-builder/docs/4641/api/doc/elasticsearch/v8/operation/operation-knn-search
resource: https://www.elastic.co/elastic/docs-builder/docs/4641/api/doc/elasticsearch/v8/operation/operation-knn-search
products:
  - Elasticsearch
---

# Run a knn search

deprecated

Authentication: required

Availability: Preview since 8.0

## Paths

- `POST` (also `GET`) `/{index}/_knn_search`

#### Path parameters

- `index` (union string | string[]) — required
  A comma-separated list of index names to search;
use `_all` or to perform the operation on all indices.

## Description

NOTE: The kNN search API has been replaced by the `knn` option in the search API.

Perform a k-nearest neighbor (kNN) search on a dense_vector field and return the matching documents.
Given a query vector, the API finds the k closest vectors and returns those documents as search hits.

Elasticsearch uses the HNSW algorithm to support efficient kNN search.
Like most kNN algorithms, HNSW is an approximate method that sacrifices result accuracy for improved search speed.
This means the results returned are not always the true k closest neighbors.

The kNN search API supports restricting the search using a filter.
The search will return the top k documents that also match the filter query.

A kNN search response has the exact same structure as a search API response.
However, certain sections have a meaning specific to kNN search:

* The document `_score` is determined by the similarity between the query and document vector.
* The `hits.total` object contains the total number of nearest neighbor candidates considered, which is `num_candidates * num_shards`. The `hits.total.relation` will always be `eq`, indicating an exact value.

## Query string parameters

- `routing` (string) — optional
  A comma-separated list of specific routing values.

## Request body

`application/json`

- `_source` (union oneOf · default: true) — optional
  Indicates which source fields are returned for matching documents. These
fields are returned in the `hits._source` property of the search response.
  - **boolean**
  - **SourceFilter**
    - `exclude_vectors` (boolean) — optional
      If `true`, vector fields are excluded from the returned source.

This option takes precedence over `includes`: any vector field will
remain excluded even if it matches an `includes` rule.
    - `excludes` (union oneOf) — optional
      A list of fields to exclude from the returned source.
      One of: `string[]` or `string`
    - `includes` (union oneOf) — optional
      A list of fields to include in the returned source.
      One of: `string[]` or `string`
- `docvalue_fields` (object[]) — optional
  The request returns doc values for field names matching these patterns
in the `hits.fields` property of the response.
It accepts wildcard (`*`) patterns.
  - `field` (string) — required
    A wildcard pattern. The request returns values for field names matching this pattern.
  - `format` (string) — optional
    The format in which the values are returned.
  - `include_unmapped` (boolean) — optional
- `stored_fields` (union oneOf) — optional
  A list of stored fields to return as part of a hit. If no fields are specified,
no stored fields are included in the response. If this field is specified, the `_source`
parameter defaults to `false`. You can pass `_source: true` to return both source fields
and stored fields in the search response.
  One of: `string[]` or `string`
- `fields` (union oneOf) — optional
  The request returns values for field names matching these patterns
in the `hits.fields` property of the response.
It accepts wildcard (`*`) patterns.
  One of: `string[]` or `string`
- `filter` (union oneOf) — optional
  A query to filter the documents that can match. The kNN search will return the top
`k` documents that also match this filter. The value can be a single query or a
list of queries. If `filter` isn't provided, all documents are allowed to match.
  One of: [`Query[]`](https://www.elastic.co/elastic/docs-builder/docs/4641/api/doc/elasticsearch/v8/types/_types-query_dsl-querycontainer) or [`Query`](https://www.elastic.co/elastic/docs-builder/docs/4641/api/doc/elasticsearch/v8/types/_types-query_dsl-querycontainer)
  See [Query](https://www.elastic.co/elastic/docs-builder/docs/4641/api/doc/elasticsearch/v8/types/_types-query_dsl-querycontainer)
- `knn` (object) — required
  The kNN query to run.
  - `field` (string) — required
    The name of the vector field to search against
  - `query_vector` (number[]) — required
    The query vector
  - `k` (number) — required
    The final number of nearest neighbors to return as top hits
  - `num_candidates` (number) — required
    The number of nearest neighbor candidates to consider per shard

## Response

`application/json`

- `took` (number)
  The milliseconds it took Elasticsearch to run the request.
- `timed_out` (boolean)
  If true, the request timed out before completion;
returned results may be partial or empty.
- `_shards` (object)
  A count of shards used for the request.
  - `failed` (number)
    The number of shards the operation or search attempted to run on but failed.
  - `successful` (number)
    The number of shards the operation or search succeeded on.
  - `total` (number)
    The number of shards the operation or search will run on overall.
  - `failures` (object[])
    - `index` (string)
    - `node` (string)
    - `reason` (object)
      - `type` (string)
        The type of error
      - `reason` (union string) — nullable
        A human-readable explanation of the error, in English.
        One of: `string`
      - `stack_trace` (string)
        The server stack trace. Present only if the `error_trace=true` parameter was sent with the request.
      - `caused_by` (object) — recursive
        Same fields as `reason` in `failures`
      - `root_cause` (object[]) — recursive
        Same fields as `reason` in `failures`
      - `suppressed` (object[]) — recursive
        Same fields as `reason` in `failures`
    - `shard` (number)
    - `status` (string)
    - `primary` (boolean)
  - `skipped` (number)
- `hits` (object)
  The returned documents and metadata.
  - `total` (union oneOf)
    Total hit count information, present only if `track_total_hits` wasn't `false` in the search request.
    - **TotalHits**
      - `relation` (enum)
        

Supported values include:
  - `eq`: Accurate
  - `gte`: Lower bound, including returned events or sequences
        Values: `eq`, `gte`
      - `value` (number)
    - **number**
  - `hits` (object[])
    - `_index` (string)
    - `_id` (string)
    - `_score` (union number | string) — nullable
    - `_explanation` (object)
      - `description` (string)
      - `details` (object[])
        - `description` (string)
        - `details` (object[]) — recursive
          Same fields as `details` in `_explanation`
        - `value` (number)
      - `value` (number)
    - `fields` (map string to object)
    - `highlight` (map string to string)
    - `inner_hits` (map string to object)
      Map values (object)
      - `hits` (object) — recursive
        Same fields as `hits`
    - `matched_queries` (union oneOf)
      One of: `string[]` or `string to number`
    - `_nested` (object)
      - `field` (string)
      - `offset` (number)
      - `_nested` (object) — recursive
        Same fields as `_nested` in `hits`
    - `_ignored` (string[])
    - `ignored_field_values` (map string to oneOf)
    - `_shard` (string)
    - `_node` (string)
    - `_routing` (string)
    - `_source` (object)
    - `_rank` (number)
    - `_seq_no` (number)
    - `_primary_term` (number)
    - `_version` (number)
    - `sort` (union[])
  - `max_score` (union number | string) — nullable
- `fields` (map string to object)
  The field values for the documents. These fields
must be specified in the request using the `fields` parameter.
- `max_score` (number)
  The highest returned document score. This value is null for requests
that do not sort by score.
## Code examples

#### Console

```console
POST /INDEX/_knn_search
{
  "knn": {
    "field": "string",
    "query_vector": [
      0
    ],
    "k": 0,
    "num_candidates": 0
  }
}
```

#### curl

```curl
curl -X POST "${ELASTICSEARCH_URL}/${INDEX}/_knn_search" \
  -H "Authorization: ApiKey ${API_KEY}" \
  -H "Content-Type: application/json" \
  -d '{
    "knn": {
      "field": "string",
      "query_vector": [
        0
      ],
      "k": 0,
      "num_candidates": 0
    }
  }'
```

## Response examples

#### 200

`application/json`

Generated from the API spec. Values are representative. Unions use the first variant; deeply nested or large bodies may omit fields.

```json
{
  "took": 0,
  "timed_out": false,
  "_shards": {
    "failed": 0,
    "successful": 0,
    "total": 0,
    "failures": [
      {
        "index": "string",
        "node": "string",
        "reason": {
          "type": "string",
          "reason": "string",
          "stack_trace": "string",
          "caused_by": {
            "type": "string",
            "stack_trace": "string"
          },
          "root_cause": [],
          "suppressed": []
        },
        "shard": 0,
        "status": "string",
        "primary": false
      }
    ],
    "skipped": 0
  },
  "hits": {
    "total": {
      "relation": "eq",
      "value": 0
    },
    "hits": [
      {
        "_index": "string",
        "_id": "string",
        "_score": 0,
        "_explanation": {
          "description": "string",
          "details": [],
          "value": 0
        },
        "fields": {
          "key": {}
        },
        "highlight": {
          "key": [
            "string"
          ]
        },
        "inner_hits": {
          "key": {}
        },
        "matched_queries": [
          "string"
        ],
        "_nested": {
          "field": "string",
          "offset": 0,
          "_nested": {
            "offset": 0
          }
        },
        "_ignored": [
          "string"
        ],
        "ignored_field_values": {
          "key": []
        },
        "_shard": "string",
        "_node": "string",
        "_routing": "string",
        "_source": {},
        "_rank": 0,
        "_seq_no": 0,
        "_primary_term": 0,
        "_version": 0,
        "sort": []
      }
    ],
    "max_score": 0
  },
  "fields": {
    "key": {}
  },
  "max_score": 0
}
```

