コンテンツにスキップ

このドキュメントでは、PlaidCloud Lakehouseのcosine_distance関数の概要と、この関数を使用してドキュメントの類似度を測定する方法を説明します。

PlaidCloud Lakehouseのcosine_distance関数は、2つのベクトル間のコサイン距離を計算する組み込み関数です。ドキュメントの類似度やレコメンデーションシステムなどの自然言語処理タスクでよく使用されます。

コサイン距離は、2つのベクトルがなす角のコサインに基づく類似度の尺度です。この関数は2つの入力ベクトルを受け取り、0から1の間の値を返します。0は同一のベクトルを、1は直交する(まったく似ていない)ベクトルを表します。

func.cosine_distance(<vector1>, <vector2>)

テーブルの作成とサンプルデータの挿入

サンプルのテキストドキュメントとそれに対応する埋め込みを格納するテーブルを作成します。

CREATE TABLE articles (
id INT,
title VARCHAR,
content VARCHAR,
embedding ARRAY(FLOAT32)
);

次に、サンプルドキュメントをテーブルに挿入します。

INSERT INTO articles (id, title, content, embedding)
VALUES
(1, 'Python for Data Science', 'Python is a versatile programming language widely used in data science...', ai_embedding_vector('Python is a versatile programming language widely used in data science...')),
(2, 'Introduction to R', 'R is a popular programming language for statistical computing and graphics...', ai_embedding_vector('R is a popular programming language for statistical computing and graphics...')),
(3, 'Getting Started with SQL', 'Structured Query Language (SQL) is a domain-specific language used for managing relational databases...', ai_embedding_vector('Structured Query Language (SQL) is a domain-specific language used for managing relational databases...'));

類似ドキュメントの検索

次に、cosine_distance関数を使用して、指定したクエリに最も近いドキュメントを検索します。

SELECT
id,
title,
content,
cosine_distance(embedding, ai_embedding_vector('How to use Python in data analysis?')) AS similarity
FROM
articles
ORDER BY
similarity ASC
LIMIT 3;

結果:

┌──────┬──────────────────────────┬─────────────────────────────────────────────────────────────────────────────────────────────────────────┬────────────┐
│ id │ title │ content │ similarity │
├──────┼──────────────────────────┼─────────────────────────────────────────────────────────────────────────────────────────────────────────┼────────────┤
│ 1 │ Python for Data Science │ Python is a versatile programming language widely used in data science... │ 0.1142081 │
│ 2 │ Introduction to R │ R is a popular programming language for statistical computing and graphics... │ 0.18741018 │
│ 3 │ Getting Started with SQL │ Structured Query Language (SQL) is a domain-specific language used for managing relational databases... │ 0.25137568 │
└──────┴──────────────────────────┴─────────────────────────────────────────────────────────────────────────────────────────────────────────┴────────────┘