Run a knn search
- POST also GET /{index}/_knn_search
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
_scoreis determined by the similarity between the query and document vector. - The
hits.totalobject contains the total number of nearest neighbor candidates considered, which isnum_candidates * num_shards. Thehits.total.relationwill always beeq, indicating an exact value.
Request body
-
_sourceunion oneOf · default: true -
Indicates which source fields are returned for matching documents. These fields are returned in the
hits._sourceproperty of the search response. - One of:
-
docvalue_fieldsobject[] -
The request returns doc values for field names matching these patterns in the
hits.fieldsproperty of the response. It accepts wildcard (*) patterns. -
stored_fieldsunion oneOf -
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
_sourceparameter defaults tofalse. You can pass_source: trueto return both source fields and stored fields in the search response. -
One of:
string[]orstring -
fieldsunion oneOf -
The request returns values for field names matching these patterns in the
hits.fieldsproperty of the response. It accepts wildcard (*) patterns. -
One of:
string[]orstring -
filterunion oneOf -
A query to filter the documents that can match. The kNN search will return the top
kdocuments that also match this filter. The value can be a single query or a list of queries. Iffilterisn't provided, all documents are allowed to match. -
One of:
Query[]orQuery