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

# Run a knn search


deprecated

Availability: 8.0+

## Paths

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

- [Api key auth](/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v8/authentication#apikeyauth)
- [Basic auth](/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v8/authentication#basicauth)
- [Bearer auth](/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v8/authentication#bearerauth)

#### Path Parameters

- `index` (union IndexName | [] IndexName)
  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 Routing)
  A comma-separated list of specific routing values.

## Request Body

`application/json`

- `_source` (SourceConfig · 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.
- `docvalue_fields` ([] FieldAndFormat) — 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 Field) — 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` (string Fields) — 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.
- `fields` (string Fields) — optional
  The request returns values for field names matching these patterns
in the `hits.fields` property of the response.
It accepts wildcard (`*`) patterns.
- `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: [`QueryContainer[]`](https://www.elastic.co/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v8/types/_types-query_dsl-querycontainer) or [`QueryContainer`](https://www.elastic.co/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v8/types/_types-query_dsl-querycontainer)
  See [QueryContainer](https://www.elastic.co/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v8/types/_types-query_dsl-querycontainer)
- `knn` ({} Query) — required
  The kNN query to run.
  - `field` (string Field) — required
    The name of the vector field to search against
  - `query_vector` (QueryVector) — 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` ({} ShardStatistics)
  A count of shards used for the request.
  - `failed` (number uint)
    The number of shards the operation or search attempted to run on but failed.
  - `successful` (number uint)
    The number of shards the operation or search succeeded on.
  - `total` (number uint)
    The number of shards the operation or search will run on overall.
  - `failures` ([] ShardFailure)
    - `index` (string IndexName)
    - `node` (string)
    - `reason` ({} ErrorCause)
      - `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` ({} ErrorCause) — recursive
        Same fields as `reason` in `failures`
      - `root_cause` ([] ErrorCause) — recursive
        Same fields as `reason` in `failures`
      - `suppressed` ([] ErrorCause) — recursive
        Same fields as `reason` in `failures`
    - `shard` (number)
    - `status` (string)
    - `primary` (boolean)
  - `skipped` (number uint)
- `hits` ({} HitsMetadata)
  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 TotalHitsRelation)
        

Supported values include:
  - `eq`: Accurate
  - `gte`: Lower bound, including returned events or sequences
        Values: `eq`, `gte`
      - `value` (number)
    - **number**
  - `hits` ([] Hit)
    - `_index` (string IndexName)
    - `_id` (string Id)
    - `_score` (union number | string) — nullable
    - `_explanation` ({} Explanation)
      - `description` (string)
      - `details` ([] ExplanationDetail)
        - `description` (string)
        - `details` ([] ExplanationDetail) — 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 InnerHitsResult)
      Map values ({} InnerHitsResult)
      - `hits` ({} HitsMetadata) — recursive
        Same fields as `hits`
    - `matched_queries` (union oneOf)
      One of: `string[]` or `string to number`
    - `_nested` ({} NestedIdentity)
      - `field` (string Field)
      - `offset` (number)
      - `_nested` ({} NestedIdentity) — recursive
        Same fields as `_nested` in `hits`
    - `_ignored` ([] string)
    - `ignored_field_values` (map string to FieldValue)
    - `_shard` (string)
    - `_node` (string)
    - `_routing` (string)
    - `_source` (object)
    - `_rank` (number)
    - `_seq_no` (number SequenceNumber)
    - `_primary_term` (number)
    - `_version` (number VersionNumber)
    - `sort` (SortResults)
  - `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
```

#### curl

```curl
curl -X POST "/{index}/_knn_search"
```

