vector-functions.asciidoc 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. [role="xpack"]
  2. [[vector-functions]]
  3. ===== Functions for vector fields
  4. NOTE: During vector functions' calculation, all matched documents are
  5. linearly scanned. Thus, expect the query time grow linearly
  6. with the number of matched documents. For this reason, we recommend
  7. to limit the number of matched documents with a `query` parameter.
  8. This is the list of available vector functions and vector access methods:
  9. 1. `cosineSimilarity` – calculates cosine similarity
  10. 2. `dotProduct` – calculates dot product
  11. 3. `l1norm` – calculates L^1^ distance
  12. 4. `l2norm` - calculates L^2^ distance
  13. 5. `doc[<field>].vectorValue` – returns a vector's value as an array of floats
  14. 6. `doc[<field>].magnitude` – returns a vector's magnitude
  15. Let's create an index with a `dense_vector` mapping and index a couple
  16. of documents into it.
  17. [source,console]
  18. --------------------------------------------------
  19. PUT my-index-000001
  20. {
  21. "mappings": {
  22. "properties": {
  23. "my_dense_vector": {
  24. "type": "dense_vector",
  25. "dims": 3
  26. },
  27. "status" : {
  28. "type" : "keyword"
  29. }
  30. }
  31. }
  32. }
  33. PUT my-index-000001/_doc/1
  34. {
  35. "my_dense_vector": [0.5, 10, 6],
  36. "status" : "published"
  37. }
  38. PUT my-index-000001/_doc/2
  39. {
  40. "my_dense_vector": [-0.5, 10, 10],
  41. "status" : "published"
  42. }
  43. POST my-index-000001/_refresh
  44. --------------------------------------------------
  45. // TESTSETUP
  46. The `cosineSimilarity` function calculates the measure of
  47. cosine similarity between a given query vector and document vectors.
  48. [source,console]
  49. --------------------------------------------------
  50. GET my-index-000001/_search
  51. {
  52. "query": {
  53. "script_score": {
  54. "query" : {
  55. "bool" : {
  56. "filter" : {
  57. "term" : {
  58. "status" : "published" <1>
  59. }
  60. }
  61. }
  62. },
  63. "script": {
  64. "source": "cosineSimilarity(params.query_vector, 'my_dense_vector') + 1.0", <2>
  65. "params": {
  66. "query_vector": [4, 3.4, -0.2] <3>
  67. }
  68. }
  69. }
  70. }
  71. }
  72. --------------------------------------------------
  73. <1> To restrict the number of documents on which script score calculation is applied, provide a filter.
  74. <2> The script adds 1.0 to the cosine similarity to prevent the score from being negative.
  75. <3> To take advantage of the script optimizations, provide a query vector as a script parameter.
  76. NOTE: If a document's dense vector field has a number of dimensions
  77. different from the query's vector, an error will be thrown.
  78. The `dotProduct` function calculates the measure of
  79. dot product between a given query vector and document vectors.
  80. [source,console]
  81. --------------------------------------------------
  82. GET my-index-000001/_search
  83. {
  84. "query": {
  85. "script_score": {
  86. "query" : {
  87. "bool" : {
  88. "filter" : {
  89. "term" : {
  90. "status" : "published"
  91. }
  92. }
  93. }
  94. },
  95. "script": {
  96. "source": """
  97. double value = dotProduct(params.query_vector, 'my_dense_vector');
  98. return sigmoid(1, Math.E, -value); <1>
  99. """,
  100. "params": {
  101. "query_vector": [4, 3.4, -0.2]
  102. }
  103. }
  104. }
  105. }
  106. }
  107. --------------------------------------------------
  108. <1> Using the standard sigmoid function prevents scores from being negative.
  109. The `l1norm` function calculates L^1^ distance
  110. (Manhattan distance) between a given query vector and
  111. document vectors.
  112. [source,console]
  113. --------------------------------------------------
  114. GET my-index-000001/_search
  115. {
  116. "query": {
  117. "script_score": {
  118. "query" : {
  119. "bool" : {
  120. "filter" : {
  121. "term" : {
  122. "status" : "published"
  123. }
  124. }
  125. }
  126. },
  127. "script": {
  128. "source": "1 / (1 + l1norm(params.queryVector, 'my_dense_vector'))", <1>
  129. "params": {
  130. "queryVector": [4, 3.4, -0.2]
  131. }
  132. }
  133. }
  134. }
  135. }
  136. --------------------------------------------------
  137. <1> Unlike `cosineSimilarity` that represent similarity, `l1norm` and
  138. `l2norm` shown below represent distances or differences. This means, that
  139. the more similar the vectors are, the lower the scores will be that are
  140. produced by the `l1norm` and `l2norm` functions.
  141. Thus, as we need more similar vectors to score higher,
  142. we reversed the output from `l1norm` and `l2norm`. Also, to avoid
  143. division by 0 when a document vector matches the query exactly,
  144. we added `1` in the denominator.
  145. The `l2norm` function calculates L^2^ distance
  146. (Euclidean distance) between a given query vector and
  147. document vectors.
  148. [source,console]
  149. --------------------------------------------------
  150. GET my-index-000001/_search
  151. {
  152. "query": {
  153. "script_score": {
  154. "query" : {
  155. "bool" : {
  156. "filter" : {
  157. "term" : {
  158. "status" : "published"
  159. }
  160. }
  161. }
  162. },
  163. "script": {
  164. "source": "1 / (1 + l2norm(params.queryVector, 'my_dense_vector'))",
  165. "params": {
  166. "queryVector": [4, 3.4, -0.2]
  167. }
  168. }
  169. }
  170. }
  171. }
  172. --------------------------------------------------
  173. NOTE: If a document doesn't have a value for a vector field on which
  174. a vector function is executed, an error will be thrown.
  175. You can check if a document has a value for the field `my_vector` by
  176. `doc['my_vector'].size() == 0`. Your overall script can look like this:
  177. [source,js]
  178. --------------------------------------------------
  179. "source": "doc['my_vector'].size() == 0 ? 0 : cosineSimilarity(params.queryVector, 'my_vector')"
  180. --------------------------------------------------
  181. // NOTCONSOLE
  182. The recommended way to access dense vectors is through `cosineSimilarity`,
  183. `dotProduct`, `l1norm` or `l2norm` functions. But for custom use cases,
  184. you can access dense vectors's values directly through the following functions:
  185. - `doc[<field>].vectorValue` – returns a vector's value as an array of floats
  186. - `doc[<field>].magnitude` – returns a vector's magnitude as a float
  187. (for vectors created prior to version 7.5 the magnitude is not stored.
  188. So this function calculates it anew every time it is called).
  189. For example, the script below implements a cosine similarity using these
  190. two functions:
  191. [source,console]
  192. --------------------------------------------------
  193. GET my-index-000001/_search
  194. {
  195. "query": {
  196. "script_score": {
  197. "query" : {
  198. "bool" : {
  199. "filter" : {
  200. "term" : {
  201. "status" : "published"
  202. }
  203. }
  204. }
  205. },
  206. "script": {
  207. "source": """
  208. float[] v = doc['my_dense_vector'].vectorValue;
  209. float vm = doc['my_dense_vector'].magnitude;
  210. float dotProduct = 0;
  211. for (int i = 0; i < v.length; i++) {
  212. dotProduct += v[i] * params.queryVector[i];
  213. }
  214. return dotProduct / (vm * (float) params.queryVectorMag);
  215. """,
  216. "params": {
  217. "queryVector": [4, 3.4, -0.2],
  218. "queryVectorMag": 5.25357
  219. }
  220. }
  221. }
  222. }
  223. }
  224. --------------------------------------------------