knn-query.asciidoc 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. [[query-dsl-knn-query]]
  2. === Knn query
  3. ++++
  4. <titleabbrev>Knn</titleabbrev>
  5. ++++
  6. Finds the _k_ nearest vectors to a query vector, as measured by a similarity
  7. metric. _knn_ query finds nearest vectors through approximate search on indexed
  8. dense_vectors. The preferred way to do approximate kNN search is through the
  9. <<knn-search,top level knn section>> of a search request. _knn_ query is reserved for
  10. expert cases, where there is a need to combine this query with other queries.
  11. [[knn-query-ex-request]]
  12. ==== Example request
  13. [source,console]
  14. ----
  15. PUT my-image-index
  16. {
  17. "mappings": {
  18. "properties": {
  19. "image-vector": {
  20. "type": "dense_vector",
  21. "dims": 3,
  22. "index": true,
  23. "similarity": "l2_norm"
  24. },
  25. "file-type": {
  26. "type": "keyword"
  27. },
  28. "title": {
  29. "type": "text"
  30. }
  31. }
  32. }
  33. }
  34. ----
  35. . Index your data.
  36. +
  37. [source,console]
  38. ----
  39. POST my-image-index/_bulk?refresh=true
  40. { "index": { "_id": "1" } }
  41. { "image-vector": [1, 5, -20], "file-type": "jpg", "title": "mountain lake" }
  42. { "index": { "_id": "2" } }
  43. { "image-vector": [42, 8, -15], "file-type": "png", "title": "frozen lake"}
  44. { "index": { "_id": "3" } }
  45. { "image-vector": [15, 11, 23], "file-type": "jpg", "title": "mountain lake lodge" }
  46. ----
  47. //TEST[continued]
  48. . Run the search using the `knn` query, asking for the top 10 nearest vectors
  49. from each shard, and then combine shard results to get the top 3 global results.
  50. +
  51. [source,console]
  52. ----
  53. POST my-image-index/_search
  54. {
  55. "size" : 3,
  56. "query" : {
  57. "knn": {
  58. "field": "image-vector",
  59. "query_vector": [-5, 9, -12],
  60. "k": 10
  61. }
  62. }
  63. }
  64. ----
  65. //TEST[continued]
  66. [[knn-query-top-level-parameters]]
  67. ==== Top-level parameters for `knn`
  68. `field`::
  69. +
  70. --
  71. (Required, string) The name of the vector field to search against. Must be a
  72. <<index-vectors-knn-search, `dense_vector` field with indexing enabled>>.
  73. --
  74. `query_vector`::
  75. +
  76. --
  77. (Optional, array of floats or string) Query vector. Must have the same number of dimensions
  78. as the vector field you are searching against. Must be either an array of floats or a hex-encoded byte vector.
  79. Either this or `query_vector_builder` must be provided.
  80. --
  81. `query_vector_builder`::
  82. +
  83. --
  84. (Optional, object) Query vector builder.
  85. include::{es-ref-dir}/rest-api/common-parms.asciidoc[tag=knn-query-vector-builder]
  86. --
  87. `k`::
  88. +
  89. --
  90. (Optional, integer) The number of nearest neighbors to return from each shard.
  91. {es} collects `k` results from each shard, then merges them to find the global top results.
  92. This value must be less than or equal to `num_candidates`. Defaults to `num_candidates`.
  93. --
  94. `num_candidates`::
  95. +
  96. --
  97. (Optional, integer) The number of nearest neighbor candidates to consider per shard
  98. while doing knn search. Cannot exceed 10,000. Increasing `num_candidates` tends to
  99. improve the accuracy of the final results.
  100. Defaults to `1.5 * k` if `k` is set, or `1.5 * size` if `k` is not set.
  101. --
  102. `filter`::
  103. +
  104. --
  105. (Optional, query object) Query to filter the documents that can match.
  106. The kNN search will return the top documents that also match this filter.
  107. The value can be a single query or a list of queries. If `filter` is not provided,
  108. all documents are allowed to match.
  109. The filter is a pre-filter, meaning that it is applied **during** the approximate
  110. kNN search to ensure that `num_candidates` matching documents are returned.
  111. --
  112. `similarity`::
  113. +
  114. --
  115. (Optional, float) The minimum similarity required for a document to be considered
  116. a match. The similarity value calculated relates to the raw
  117. <<dense-vector-similarity, `similarity`>> used. Not the document score. The matched
  118. documents are then scored according to <<dense-vector-similarity, `similarity`>>
  119. and the provided `boost` is applied.
  120. --
  121. `boost`::
  122. +
  123. --
  124. (Optional, float) Floating point number used to multiply the
  125. scores of matched documents. This value cannot be negative. Defaults to `1.0`.
  126. --
  127. `_name`::
  128. +
  129. --
  130. (Optional, string) Name field to identify the query
  131. --
  132. [[knn-query-filtering]]
  133. ==== Pre-filters and post-filters in knn query
  134. There are two ways to filter documents that match a kNN query:
  135. . **pre-filtering** – filter is applied during the approximate kNN search
  136. to ensure that `k` matching documents are returned.
  137. . **post-filtering** – filter is applied after the approximate kNN search
  138. completes, which results in fewer than k results, even when there are enough
  139. matching documents.
  140. Pre-filtering is supported through the `filter` parameter of the `knn` query.
  141. Also filters from <<filter-alias,aliases>> are applied as pre-filters.
  142. All other filters found in the Query DSL tree are applied as post-filters.
  143. For example, `knn` query finds the top 3 documents with the nearest vectors
  144. (k=3), which are combined with `term` filter, that is
  145. post-filtered. The final set of documents will contain only a single document
  146. that passes the post-filter.
  147. [source,console]
  148. ----
  149. POST my-image-index/_search
  150. {
  151. "size" : 10,
  152. "query" : {
  153. "bool" : {
  154. "must" : {
  155. "knn": {
  156. "field": "image-vector",
  157. "query_vector": [-5, 9, -12],
  158. "k": 3
  159. }
  160. },
  161. "filter" : {
  162. "term" : { "file-type" : "png" }
  163. }
  164. }
  165. }
  166. }
  167. ----
  168. //TEST[continued]
  169. [[knn-query-in-hybrid-search]]
  170. ==== Hybrid search with knn query
  171. Knn query can be used as a part of hybrid search, where knn query is combined
  172. with other lexical queries. For example, the query below finds documents with
  173. `title` matching `mountain lake`, and combines them with the top 10 documents
  174. that have the closest image vectors to the `query_vector`. The combined documents
  175. are then scored and the top 3 top scored documents are returned.
  176. +
  177. [source,console]
  178. ----
  179. POST my-image-index/_search
  180. {
  181. "size" : 3,
  182. "query": {
  183. "bool": {
  184. "should": [
  185. {
  186. "match": {
  187. "title": {
  188. "query": "mountain lake",
  189. "boost": 1
  190. }
  191. }
  192. },
  193. {
  194. "knn": {
  195. "field": "image-vector",
  196. "query_vector": [-5, 9, -12],
  197. "k": 10,
  198. "boost": 2
  199. }
  200. }
  201. ]
  202. }
  203. }
  204. }
  205. ----
  206. //TEST[continued]
  207. [[knn-query-with-nested-query]]
  208. ==== Knn query inside a nested query
  209. `knn` query can be used inside a nested query. The behaviour here is similar
  210. to <<nested-knn-search, top level nested kNN search>>:
  211. * kNN search over nested dense_vectors diversifies the top results over
  212. the top-level document
  213. * `filter` over the top-level document metadata is supported and acts as a
  214. post-filter
  215. * `filter` over `nested` field metadata is not supported
  216. A sample query can look like below:
  217. [source,js]
  218. ----
  219. {
  220. "query" : {
  221. "nested" : {
  222. "path" : "paragraph",
  223. "query" : {
  224. "knn": {
  225. "query_vector": [
  226. 0.45,
  227. 45
  228. ],
  229. "field": "paragraph.vector",
  230. "num_candidates": 2
  231. }
  232. }
  233. }
  234. }
  235. }
  236. ----
  237. // NOTCONSOLE
  238. [[knn-query-aggregations]]
  239. ==== Knn query with aggregations
  240. `knn` query calculates aggregations on top `k` documents from each shard.
  241. Thus, the final results from aggregations contain
  242. `k * number_of_shards` documents. This is different from
  243. the <<knn-search,top level knn section>> where aggregations are
  244. calculated on the global top `k` nearest documents.