이 페이지에서는 ANN 거리 함수를 사용하여 근사 최근접 이웃 (ANN)을 찾고 벡터 임베딩을 쿼리하는 방법을 설명합니다.
데이터 세트가 작으면 K-최근접 이웃(KNN)을 사용하여 정확한 K-최근접 벡터를 찾을 수 있습니다. 하지만 데이터 세트가 증가하면 KNN 검색의 지연 시간과 비용도 증가합니다. ANN을 사용하면 지연 시간과 비용을 크게 줄이면서 근사 K-최근접 이웃을 찾을 수 있습니다.
ANN 검색에서는 근사 거리를 계산하고 데이터 세트의 모든 벡터를 확인하지 않을 수 있으므로 k-반환 벡터가 실제 Top-K-최근접 이웃이 아닙니다. Top-K-최근접 이웃에 없는 일부 벡터가 반환되는 경우가 있습니다. 이를 리콜 손실이라고 부릅니다.
허용되는 리콜 손실 양은 사용 사례에 따라 다릅니다. 하지만 대부분의 사례에서 약간의 리콜 감소가 데이터베이스 성능 향상으로 이어진다면 합리적인 것으로 간주됩니다.
Spanner에서 지원되는 근사 거리 함수에 대한 자세한 내용은 다음 GoogleSQL 참조 페이지를 참고하세요.
Spanner는 벡터 색인을 사용하여 근사 최근접 이웃 (ANN) 벡터 검색 시간을 단축합니다. 벡터 색인을 사용하여 벡터 임베딩을 쿼리할 수 있습니다. 벡터 임베딩을 쿼리하려면 먼저 벡터 색인을 만들어야 합니다.
그런 다음 세 가지 근사 거리 함수 중 하나를 사용하여 ANN을 찾을 수 있습니다.
근사 거리 함수를 사용할 때의 제한사항은 다음과 같습니다.
근사 거리 함수는 임베딩 열과 상수 표현식(예: 파라미터 또는 리터럴) 간의 거리를 계산해야 합니다.
근사 거리 함수 출력은 ORDER BY 절에서 유일한 정렬 키로 사용되어야 하며 LIMIT가 ORDER BY 뒤에 지정되어야 합니다.
쿼리는 색인이 생성되지 않은 행을 명시적으로 필터링해야 합니다. 즉, 대부분의 경우 열이 테이블 정의에서 이미 NOT NULL로 표시되어 있지 않는 한 벡터 색인 정의와 일치하는 WHERE <column_name> IS NOT NULL 절이 쿼리에 포함되어야 합니다.
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["이해하기 어려움","hardToUnderstand","thumb-down"],["잘못된 정보 또는 샘플 코드","incorrectInformationOrSampleCode","thumb-down"],["필요한 정보/샘플이 없음","missingTheInformationSamplesINeed","thumb-down"],["번역 문제","translationIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-09-05(UTC)"],[],[],null,["| **PostgreSQL interface note:** The examples in this topic are intended for GoogleSQL-dialect databases. This feature doesn't support PostgreSQL interface.\n\n\u003cbr /\u003e\n\n\n| **Note:** This feature is available with the Spanner Enterprise edition and Enterprise Plus edition. For more information, see the [Spanner editions overview](/spanner/docs/editions-overview).\n\n\u003cbr /\u003e\n\nThis page describes how to find approximate nearest neighbors (ANN) and query\nvector embeddings using the ANN distance functions.\n\nWhen a dataset is small, you can use [K-nearest neighbors (KNN)](/spanner/docs/find-k-nearest-neighbors)\nto find the exact k-nearest vectors. However, as your dataset grows, the latency\nand cost of a KNN search also increase. You can use ANN to find the approximate\nk-nearest neighbors with significantly reduced latency and cost.\n\nIn an ANN search, the k-returned vectors aren't the true top k-nearest\nneighbors because the ANN search calculates approximate distances and might not\nlook at all the vectors in the dataset. Occasionally, a few vectors that aren't\namong the top k-nearest neighbors are returned. This is known as *recall loss*.\nHow much recall loss is acceptable to you depends on the use case, but in most\ncases, losing a bit of recall in return for improved database performance is an\nacceptable tradeoff.\n\nFor more details about the approximate distance functions supported in\nSpanner, see the following GoogleSQL reference pages:\n\n- [`APPROX_COSINE_DISTANCE`](/spanner/docs/reference/standard-sql/mathematical_functions#approx_cosine_distance)\n- [`APPROX_EUCLIDEAN_DISTANCE`](/spanner/docs/reference/standard-sql/mathematical_functions#approx_euclidean_distance)\n- [`APPROX_DOT_PRODUCT`](/spanner/docs/reference/standard-sql/mathematical_functions#approx_dot_product)\n\nQuery vector embeddings\n\nSpanner accelerates approximate nearest neighbor (ANN) vector\nsearches by using a [vector index](/spanner/docs/vector-indexes). You can use a\nvector index to query vector embeddings. To query vector embeddings, you must\nfirst [create a vector index](/spanner/docs/vector-indexes#create-vector-index).\nYou can then use any one of the three approximate distance functions to find the\nANN.\n\nRestrictions when using the approximate distance functions include the\nfollowing:\n\n- The approximate distance function must calculate the distance between an embedding column and a constant expression (for example, a parameter or a literal).\n- The approximate distance function output must be used in a `ORDER BY` clause as the sole sort key, and a `LIMIT` must be specified after the `ORDER BY`.\n- The query must explicitly filter out rows that aren't indexed. In most cases, this means that the query must include a `WHERE \u003ccolumn_name\u003e IS NOT NULL` clause that matches the vector index definition, unless the column is already marked as `NOT NULL` in the table definition.\n\nFor a detailed list of limitations, see the\n[approximate distance function reference page](/spanner/docs/reference/standard-sql/mathematical_functions).\n\n**Examples**\n\nConsider a `Documents` table that has a `DocEmbedding` column of precomputed\ntext embeddings from the `DocContents` bytes column, and a\n`NullableDocEmbedding` column populated from other sources that might be null. \n\n CREATE TABLE Documents (\n UserId INT64 NOT NULL,\n DocId INT64 NOT NULL,\n Author STRING(1024),\n DocContents BYTES(MAX),\n DocEmbedding ARRAY\u003cFLOAT32\u003e NOT NULL,\n NullableDocEmbedding ARRAY\u003cFLOAT32\u003e,\n WordCount INT64\n ) PRIMARY KEY (UserId, DocId);\n\nTo search for the nearest 100 vectors to `[1.0, 2.0, 3.0]`: \n\n SELECT DocId\n FROM Documents\n WHERE WordCount \u003e 1000\n ORDER BY APPROX_EUCLIDEAN_DISTANCE(\n ARRAY\u003cFLOAT32\u003e[1.0, 2.0, 3.0], DocEmbedding,\n options =\u003e JSON '{\"num_leaves_to_search\": 10}')\n LIMIT 100\n\nIf the embedding column is nullable: \n\n SELECT DocId\n FROM Documents\n WHERE NullableDocEmbedding IS NOT NULL AND WordCount \u003e 1000\n ORDER BY APPROX_EUCLIDEAN_DISTANCE(\n ARRAY\u003cFLOAT32\u003e[1.0, 2.0, 3.0], NullableDocEmbedding,\n options =\u003e JSON '{\"num_leaves_to_search\": 10}')\n LIMIT 100\n\nWhat's next\n\n- Learn more about Spanner [vector indexes](/spanner/docs/vector-indexes).\n\n- Learn more about the [GoogleSQL `APPROXIMATE_COSINE_DISTANCE()`, `APPROXIMATE_EUCLIDEAN_DISTANCE()`, `APPROXIMATE_DOT_PRODUCT()`](/spanner/docs/reference/standard-sql/mathematical_functions) functions.\n\n- Learn more about the [GoogleSQL `VECTOR INDEX` statements](/spanner/docs/reference/standard-sql/data-definition-language#vector_index_statements).\n\n- Learn more about [vector index best practices](/spanner/docs/vector-index-best-practices).\n\n- Try the [Getting started with Spanner Vector Search](https://codelabs.developers.google.com/codelabs/spanner-getting-started-vector-search)\n for a step-by-step example of using ANN."]]