문서 메뉴
문서 홈
/
MongoDB 아틀라스
/

벡터 임베딩을 만드는 방법

이 페이지의 내용

  • 임베딩 생성 방법 선택
  • 데이터에서 임베딩 생성 및 저장
  • 전제 조건
  • 절차
  • 쿼리에 대한 임베딩 만들기
  • 절차

벡터 임베딩 은 데이터를 다차원 공간의 점으로 표현합니다. 이러한 임베딩은 데이터에서 의미 있는 관계를 캡처하고 시맨틱 검색 및 조회와 같은 작업을 가능하게 합니다. 벡터 임베딩을 다른 데이터와 함께 Atlas에 저장하고 Atlas Vector Search를 사용하여 벡터화된 데이터를 쿼리할 수 있습니다.

임베딩에 대한 벡터 검색을 수행하려면 다음을 수행합니다.

  1. 벡터 임베딩을 생성하는 방법을 선택합니다.

  2. 데이터에서 벡터 임베딩을 생성하고 Atlas에 저장합니다.

  3. 검색 쿼리를 나타내는 벡터 임베딩을 만들고 쿼리를 실행합니다.

Atlas Vector Search는 쿼리를 나타내는 임베딩과 거리가 가장 가까운 벡터 임베딩을 가진 문서를 반환합니다. 이는 의미가 비슷하다는 것을 나타냅니다.

벡터 임베딩을 만들려면 임베딩 모델 을 사용해야 합니다. 임베딩 모델에 연결하고 Atlas Vector Search에 대한 임베딩을 생성하려면 다음 방법 중 하나를 사용합니다.

메서드
설명
자습서
오픈 소스 모델 로드
API 키 또는 임베딩 서비스 크레딧이 없는 경우 애플리케이션에서 로컬로 로드하여 오픈 소스 임베딩 모델을 사용하세요.
Create and Store Embeddings
임베딩 서비스 호출
대부분의 AI 제공자는 벡터 임베딩을 생성하는 데 사용할 수 있는 독점 임베딩 모델에 대한 API를 제공합니다.
통합 사용

Atlas Vector Search를 LangChainLlamaIndex 와 같은 오픈 소스 프레임워크 , Amazon 침대록과 같은 서비스 등과 통합할 수 있습니다.

이러한 통합에는 오픈 소스 및 독점 임베딩 모델에 빠르게 연결하고 Atlas Vector Search를 위한 벡터 임베딩을 생성하는 데 도움이 되는 내장 라이브러리와 도구가 포함되어 있습니다.

다음 절차는 오픈 소스 또는 독점 임베딩 모델을 사용하여 벡터 임베딩을 생성하고 Atlas에 저장하는 방법을 보여줍니다.


언어 선택 드롭다운 메뉴를 사용하여 이 페이지에 있는 예제의 언어를 설정합니다.


이러한 예제를 실행하려면 다음이 필요합니다.

사용자 지정 데이터에서 벡터 임베딩을 생성하고 Atlas의 컬렉션에 저장하려면 다음 단계를 완료하세요. 다음 코드를 수정하여 모든 유형의 자체 데이터에서 임베딩을 생성할 수도 있습니다.

참고

기존 컬렉션에 대한 임베딩을 생성하려면 임베딩이 포함된 새 필드를 추가하고 컬렉션의 각 문서를 업데이트 해야 합니다.

1

터미널 창에서 다음 명령을 실행하여 my-embeddings-project 라는 새 디렉토리를 만들고 프로젝트를 초기화합니다.

mkdir my-embeddings-project
cd my-embeddings-project
npm init -y
2

ES 모듈 을 사용하도록 프로젝트 "type": "module" package.json 구성 파일에 를 추가한 다음 저장합니다.

{
"type": "module",
// other fields...
}
3

터미널 창에서 다음 명령을 실행합니다.

npm install mongodb @xenova/transformers
4
  1. create-embeddings.js 이라는 파일을 만들고 다음 코드를 붙여넣습니다. 이 코드는 다음을 수행합니다.

    • 지정된 입력에 대한 임베딩을 생성하기 위해 getEmbedding 이라는 이름의 비동기 함수를 생성하고 내보냅니다. 이 함수는 또한 다음을 지정합니다.

    • 샘플 텍스트 데이터에서 임베딩을 생성하고 MongoDB Node.js 드라이버를 사용하여 Atlas의 sample_db.embeddings 컬렉션에 수집합니다.

    create-embeddings.js
    import { MongoClient } from 'mongodb';
    import { pipeline } from '@xenova/transformers';
    // Function to generate embeddings for a given data source
    export async function getEmbedding(data) {
    const embedder = await pipeline(
    'feature-extraction',
    'Xenova/nomic-embed-text-v1');
    const response = await embedder(data, { pooling: 'mean', normalize: true });
    return Array.from(response.data);
    }
    // Data to embed
    const data = [
    "Titanic: The story of the 1912 sinking of the largest luxury liner ever built",
    "The Lion King: Lion cub and future king Simba searches for his identity",
    "Avatar: A marine is dispatched to the moon Pandora on a unique mission"
    ]
    async function run() {
    // Connect to your Atlas cluster
    const uri = "<connectionString>";
    const client = new MongoClient(uri);
    try {
    await client.connect();
    const db = client.db("sample_db");
    const collection = db.collection("embeddings");
    // Ingest data and embeddings into Atlas
    await Promise.all(data.map(async text => {
    const embedding = await getEmbedding(text);
    // Check if the document already exists before inserting
    const existingDoc = await collection.findOne({ text: text });
    if (!existingDoc) {
    await collection.insertOne({
    text: text,
    embedding: embedding
    });
    console.log(embedding);
    }
    }));
    } catch (err) {
    console.log(err.stack);
    }
    finally {
    await client.close();
    }
    }
    run().catch(console.dir);
  2. <connectionString> 을(를) Atlas cluster의 SRV 연결 문자열로 바꿉니다.

    참고

    연결 문자열은 다음 형식을 사용해야 합니다.

    mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net
  3. 파일을 저장한 후 다음 명령을 실행합니다.

    node create-embeddings.js
    [ -0.04323853924870491, -0.008460805751383305, 0.012494648806750774, -0.013014335185289383, ... ]
    [ -0.017400473356246948, 0.04922063276171684, -0.002836339408531785, -0.030395228415727615, ... ]
    [ -0.016950927674770355, 0.013881809078156948, -0.022074559703469276, -0.02838018536567688, ... ]

    참고

    출력의 차원 수는 가독성을 위해 잘렸습니다.

    클러스터의 sample_db.embeddings 컬렉션으로 이동 하여 Atlas UI에서 벡터 임베딩을 볼 수도 있습니다.

1

터미널 창에서 다음 명령을 실행하여 my-embeddings-project (이)라는 새 디렉토리를 만들고 프로젝트를 초기화합니다.

mkdir my-embeddings-project
cd my-embeddings-project
npm init -y
2

ES 모듈 을 사용하도록 프로젝트 "type": "module" package.json 구성 파일에 를 추가한 다음 저장합니다.

{
"type": "module",
// other fields...
}
3

터미널 창에서 다음 명령을 실행합니다.

npm install mongodb openai
4
  1. create-embeddings.js 이라는 파일을 만들고 다음 코드를 붙여넣습니다. 이 코드는 다음을 수행합니다.

    • OpenAI의 text-embedding-3-small 모델을 사용하여 지정된 입력에 대한 임베딩을 생성하는 getEmbedding 라는 비동기 함수를 생성하고 내보냅니다.

    • 샘플 텍스트 데이터에서 임베딩을 생성하고 MongoDB Node.js 드라이버를 사용하여 Atlas의 sample_db.embeddings 컬렉션에 수집합니다.

    create-embeddings.js
    import { MongoClient } from 'mongodb';
    import OpenAI from 'openai';
    // Setup OpenAI configuration
    const openai = new OpenAI({
    apiKey: "<apiKey>",
    });
    // Function to get the embeddings using the OpenAI API
    export async function getEmbedding(text) {
    const response = await openai.embeddings.create({
    model: "text-embedding-3-small",
    input: text,
    encoding_format: "float",
    });
    return response.data[0].embedding;
    }
    // Data to embed
    const data = [
    "Titanic: The story of the 1912 sinking of the largest luxury liner ever built",
    "The Lion King: Lion cub and future king Simba searches for his identity",
    "Avatar: A marine is dispatched to the moon Pandora on a unique mission"
    ]
    async function run() {
    // Connect to your Atlas cluster
    const uri = "<connectionString>";
    const client = new MongoClient(uri);
    try {
    await client.connect();
    const db = client.db("sample_db");
    const collection = db.collection("embeddings");
    // Ingest data and embeddings into Atlas
    await Promise.all(data.map(async text => {
    // Check if the document already exists
    const embedding = await getEmbedding(text);
    const existingDoc = await collection.findOne({ text: text });
    if (!existingDoc) {
    await collection.insertOne({
    text: text,
    embedding: embedding
    });
    console.log(embedding);
    }
    }));
    } catch (err) {
    console.log(err.stack);
    }
    finally {
    await client.close();
    }
    }
    run().catch(console.dir);
  2. 다음 자리 표시자 값을 바꿉니다.

    참고

    연결 문자열은 다음 형식을 사용해야 합니다.

    mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net
  3. 파일을 저장한 후 다음 명령을 실행합니다.

    node create-embeddings.js
    [ 0.031927742, -0.014192767, -0.021851597, 0.045498233, -0.0077904654, ... ]
    [ -0.01664538, 0.013198251, 0.048684783, 0.014485021, -0.018121032, ... ]
    [ 0.030449908, 0.046782598, 0.02126599, 0.025799986, -0.015830345, ... ]

    참고

    출력의 차원 수는 가독성을 위해 잘렸습니다.

    클러스터의 sample_db.embeddings 컬렉션으로 이동 하여 Atlas UI에서 벡터 임베딩을 볼 수도 있습니다.

1

확장자가 .ipynb 인 파일을 저장하여 대화형 Python 노트북을 만든 후 노트북에서 다음 명령을 실행하여 종속성을 설치합니다.

pip install --quiet nomic sentence-transformers pymongo
2

노트북에 다음 코드를 붙여넣고 실행하여 Nomic AI 의 오픈 소스 임베딩 모델을 사용하여 벡터 임베딩을 생성하는 함수를 만듭니다. . 이 코드는 다음을 수행합니다.

  • nomic-embed-text-v1 를 로드합니다. 임베딩 모델.

  • 모델을 사용하여 지정된 텍스트 입력에 대한 임베딩을 생성하는 get_embedding 라는 함수를 만듭니다.

  • 문자열 foo 에 대한 단일 임베딩을 생성합니다.

from nomic import embed
from sentence_transformers import SentenceTransformer
# Load the embedding model (https://huggingface.co/nomic-ai/nomic-embed-text-v1")
model = SentenceTransformer("nomic-ai/nomic-embed-text-v1", trust_remote_code=True)
# Define a function to generate embeddings
def get_embedding(data):
"""Generates vector embeddings for the given data."""
embedding = model.encode(data)
return embedding.tolist()
# Generate an embedding
get_embedding("foo")
[-0.029808253049850464, 0.03841473162174225, -0.02561120130121708, -0.06707508116960526, 0.03867151960730553, ... ]
3

노트북에 다음 코드를 붙여넣고 실행하여 Atlas cluster에 연결하고, 사용자 지정 데이터에서 임베딩을 생성한 다음, MongoDB PyMongo 드라이버 를 사용하여 sample_db.embeddings 컬렉션에 수집합니다. <connection-string> 를 Atlas 클러스터의 SRV 연결 문자열로 바꿉니다.

참고

연결 문자열은 다음 형식을 사용해야 합니다.

mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net
import pymongo
# Connect to your Atlas cluster
mongo_client = pymongo.MongoClient("<connection-string>")
db = mongo_client["sample_db"]
collection = db["embeddings"]
# Sample data
data = [
"Titanic: The story of the 1912 sinking of the largest luxury liner ever built",
"The Lion King: Lion cub and future king Simba searches for his identity",
"Avatar: A marine is dispatched to the moon Pandora on a unique mission"
]
# Ingest data into Atlas
for text in data:
embedding = get_embedding(text)
collection.insert_one({ "text": text, "embedding": embedding })

샘플 코드를 실행한sample_db.embeddings cluster의 collection으로 이동 하여 Atlas UI에서 벡터 임베딩을 볼 수 있습니다.

1

확장자가 .ipynb 인 파일을 저장하여 대화형 Python 노트북을 만든 후 노트북에서 다음 명령을 실행하여 종속성을 설치합니다.

pip install --quiet openai pymongo
2

노트북에 다음 코드를 붙여넣고 실행하여 OpenAI <api-key> 의 독점 임베딩 모델을 사용하여 벡터 임베딩을 생성하는 함수를 만듭니다. . 를 OpenAI API 키로 바꿉니다. 이 코드는 다음을 수행합니다.

  • text-embedding-3-small 임베딩 모델을 지정합니다.

  • 모델의 API 를 호출하여 지정된 텍스트 입력에 대한 임베딩을 생성하는 get_embedding 함수를 만듭니다.

  • 문자열 foo 에 대한 단일 임베딩을 생성합니다.

import os
from openai import OpenAI
# Specify your OpenAI API key and embedding model
os.environ["OPENAI_API_KEY"] = "<api-key>"
model = "text-embedding-3-small"
openai_client = OpenAI()
# Define a function to generate embeddings
def get_embedding(text):
"""Generates vector embeddings for the given text."""
embedding = openai_client.embeddings.create(input = [text], model=model).data[0].embedding
return embedding
# Generate an embedding
get_embedding("foo")
[-0.005843308754265308, -0.013111298903822899, -0.014585349708795547, 0.03580040484666824, 0.02671629749238491, ... ]

다음도 참조하세요.

API 세부 정보 및 사용 가능한 모델 목록은 OpenAI 문서를 참조하세요.

3

노트북에 다음 코드를 붙여넣고 실행하여 Atlas cluster에 연결하고, 사용자 지정 데이터에서 임베딩을 생성한 다음, MongoDB PyMongo 드라이버 를 사용하여 sample_db.embeddings 컬렉션에 수집합니다. <connection-string> 를 Atlas 클러스터의 SRV 연결 문자열로 바꿉니다.

참고

연결 문자열은 다음 형식을 사용해야 합니다.

mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net
import pymongo
# Connect to your Atlas cluster
mongo_client = pymongo.MongoClient("<connection-string>")
db = mongo_client["sample_db"]
collection = db["embeddings"]
# Sample data
data = [
"Titanic: The story of the 1912 sinking of the largest luxury liner ever built",
"The Lion King: Lion cub and future king Simba searches for his identity",
"Avatar: A marine is dispatched to the moon Pandora on a unique mission"
]
# Ingest data into Atlas
for text in data:
embedding = get_embedding(text)
collection.insert_one({ "text": text, "embedding": embedding })

샘플 코드를 실행한sample_db.embeddings cluster의 collection으로 이동 하여 Atlas UI에서 벡터 임베딩을 볼 수 있습니다.

다음 절차는 오픈 소스 또는 독점 임베딩 모델을 사용하여 Atlas Vector Search 쿼리에 대한 임베딩을 생성하는 방법을 보여줍니다.

샘플 데이터 에서 임베딩을 생성 한 후 다음 단계를 완료하여 데이터에 대한 Atlas Vector Search 인덱스와 벡터 검색 쿼리에 대한 임베딩을 생성합니다.

1

데이터에 대한 벡터 검색 쿼리를 활성화하려면 컬렉션에 Atlas Vector Search 인덱스를 생성해야 합니다.

다음 단계를 완료하여 sample_db.embeddings 컬렉션에 embedding 필드를 벡터 유형으로, 768 벡터 차원, 유사성 측정값을 euclidean 로 지정하는 인덱스를 만듭니다.

  1. create-index.js 이라는 파일을 만들고 다음 코드를 붙여넣습니다.

    create-index.js
    import { MongoClient } from 'mongodb';
    // connect to your Atlas deployment
    const uri = "<connectionString>";
    const client = new MongoClient(uri);
    async function run() {
    try {
    const database = client.db("sample_db");
    const collection = database.collection("embeddings");
    // define your Atlas Vector Search index
    const index = {
    name: "vector_index",
    type: "vectorSearch",
    definition: {
    "fields": [
    {
    "type": "vector",
    "numDimensions": 768,
    "path": "embedding",
    "similarity": "euclidean"
    }
    ]
    }
    }
    // run the helper method
    const result = await collection.createSearchIndex(index);
    console.log(result);
    } finally {
    await client.close();
    }
    }
    run().catch(console.dir);
  2. <connectionString> 을(를) Atlas cluster의 SRV 연결 문자열로 바꿉니다.

  3. 파일을 저장한 후 다음 명령을 실행합니다.

    node create-index.js

자세히 알아보려면 Atlas Vector Search 인덱스 만들기를 참조하세요.

2
  1. vector-query.js 이라는 파일을 만들고 다음 코드를 붙여넣습니다.

    벡터 검색 쿼리를 실행하려면 쿼리 벡터 를 생성하여 집계 파이프라인에 전달할 수 있습니다.

    예를 들어 다음 코드는 다음을 수행합니다.

    • 이전 예제에서 정의한 임베딩 함수를 호출하여 문자열 ocean tragedy 에 대한 임베딩을 생성합니다.

    • 임베딩을 집계 파이프라인의 queryVector 필드에 전달합니다.

    • 벡터 검색 쿼리를 실행합니다. 의미적으로 유사한 문서를 관련성과 벡터 검색 점수 순으로 반환합니다.

    vector-query.js
    import { MongoClient } from 'mongodb';
    import { getEmbedding } from './create-embeddings.js';
    // MongoDB connection URI and options
    const uri = "<connectionString>";
    const client = new MongoClient(uri);
    async function run() {
    try {
    // Connect to the MongoDB client
    await client.connect();
    // Specify the database and collection
    const database = client.db("sample_db");
    const collection = database.collection("embeddings");
    // Generate embedding for the search query
    const queryEmbedding = await getEmbedding("ocean tragedy");
    // Define the sample vector search pipeline
    const pipeline = [
    {
    $vectorSearch: {
    index: "vector_index",
    queryVector: queryEmbedding,
    path: "embedding",
    exact: true,
    limit: 5
    }
    },
    {
    $project: {
    _id: 0,
    text: 1,
    score: {
    $meta: "vectorSearchScore"
    }
    }
    }
    ];
    // run pipeline
    const result = collection.aggregate(pipeline);
    // print results
    for await (const doc of result) {
    console.dir(JSON.stringify(doc));
    }
    } finally {
    await client.close();
    }
    }
    run().catch(console.dir);
  2. <connectionString> 을(를) Atlas cluster의 SRV 연결 문자열로 바꿉니다.

  3. 파일을 저장한 후 다음 명령을 실행합니다.

    node vector-query.js
    '{"text":"Titanic: The story of the 1912 sinking of the largest luxury liner ever built","score":0.5103757977485657}'
    '{"text":"Avatar: A marine is dispatched to the moon Pandora on a unique mission","score":0.4616812467575073}'
    '{"text":"The Lion King: Lion cub and future king Simba searches for his identity","score":0.4115804433822632}'
1

데이터에 대한 벡터 검색 쿼리를 활성화하려면 컬렉션에 Atlas Vector Search 인덱스를 생성해야 합니다.

다음 단계를 완료하여 sample_db.embeddings 컬렉션에 embedding 필드를 벡터 유형으로, 1536 벡터 차원, 유사성 측정값을 euclidean 로 지정하는 인덱스를 만듭니다.

  1. create-index.js 이라는 파일을 만들고 다음 코드를 붙여넣습니다.

    create-index.js
    import { MongoClient } from 'mongodb';
    // connect to your Atlas deployment
    const uri = "<connectionString>";
    const client = new MongoClient(uri);
    async function run() {
    try {
    const database = client.db("sample_db");
    const collection = database.collection("embeddings");
    // define your Atlas Vector Search index
    const index = {
    name: "vector_index",
    type: "vectorSearch",
    definition: {
    "fields": [
    {
    "type": "vector",
    "numDimensions": 1536,
    "path": "embedding",
    "similarity": "euclidean"
    }
    ]
    }
    }
    // run the helper method
    const result = await collection.createSearchIndex(index);
    console.log(result);
    } finally {
    await client.close();
    }
    }
    run().catch(console.dir);
  2. <connectionString> 을(를) Atlas cluster의 SRV 연결 문자열로 바꿉니다.

  3. 파일을 저장한 후 다음 명령을 실행합니다.

    node create-index.js

자세히 알아보려면 Atlas Vector Search 인덱스 만들기를 참조하세요.

2
  1. vector-query.js 이라는 파일을 만들고 다음 코드를 붙여넣습니다.

    벡터 검색 쿼리를 실행하려면 쿼리 벡터 를 생성하여 집계 파이프라인에 전달할 수 있습니다.

    예를 들어 다음 코드는 다음을 수행합니다.

    • 이전 예제에서 정의한 임베딩 함수를 호출하여 문자열 ocean tragedy 에 대한 임베딩을 생성합니다.

    • 임베딩을 집계 파이프라인의 queryVector 필드에 전달합니다.

    • 벡터 검색 쿼리를 실행합니다. 의미적으로 유사한 문서를 관련성과 벡터 검색 점수 순으로 반환합니다.

    vector-query.js
    import { MongoClient } from 'mongodb';
    import { getEmbedding } from './create-embeddings.js';
    // MongoDB connection URI and options
    const uri = "<connectionString>";
    const client = new MongoClient(uri);
    async function run() {
    try {
    // Connect to the MongoDB client
    await client.connect();
    // Specify the database and collection
    const database = client.db("sample_db");
    const collection = database.collection("embeddings");
    // Generate embedding for the search query
    const queryEmbedding = await getEmbedding("ocean tragedy");
    // Define the sample vector search pipeline
    const pipeline = [
    {
    $vectorSearch: {
    index: "vector_index",
    queryVector: queryEmbedding,
    path: "embedding",
    exact: true,
    limit: 5
    }
    },
    {
    $project: {
    _id: 0,
    text: 1,
    score: {
    $meta: "vectorSearchScore"
    }
    }
    }
    ];
    // run pipeline
    const result = collection.aggregate(pipeline);
    // print results
    for await (const doc of result) {
    console.dir(JSON.stringify(doc));
    }
    } finally {
    await client.close();
    }
    }
    run().catch(console.dir);
  2. <connectionString> 을(를) Atlas cluster의 SRV 연결 문자열로 바꿉니다.

  3. 파일을 저장한 후 다음 명령을 실행합니다.

    node vector-query.js
    '{"text":"Titanic: The story of the 1912 sinking of the largest luxury liner ever built","score":0.4551968574523926}'
    '{"text":"Avatar: A marine is dispatched to the moon Pandora on a unique mission","score":0.4050074517726898}'
    '{"text":"The Lion King: Lion cub and future king Simba searches for his identity","score":0.3594386577606201}'
1

데이터에 대한 벡터 검색 쿼리를 활성화하려면 컬렉션에 Atlas Vector Search 인덱스를 생성해야 합니다.

다음 코드를 실행하여 sample_db.embeddings 컬렉션에 embedding 필드를 벡터 유형으로, 768 벡터 차원, 유사성 측정값을 euclidean 로 지정하는 인덱스를 만듭니다.

from pymongo.operations import SearchIndexModel
# Create your index model, then create the search index
search_index_model = SearchIndexModel(
definition = {
"fields": [
{
"type": "vector",
"path": "embedding",
"numDimensions": 768,
"similarity": "euclidean"
}
]
},
name="vector_index",
type="vectorSearch",
)
collection.create_search_index(model=search_index_model)

자세히 알아보려면 Atlas Vector Search 인덱스 만들기를 참조하세요.

2

벡터 검색 쿼리를 실행하려면 쿼리 벡터 를 생성하여 집계 파이프라인에 전달할 수 있습니다.

예를 들어 다음 코드는 다음을 수행합니다.

  • 이전 예제에서 정의한 임베딩 함수를 호출하여 문자열 ocean tragedy 에 대한 임베딩을 생성합니다.

  • 임베딩을 집계 파이프라인의 queryVector 필드에 전달합니다.

  • 벡터 검색 쿼리를 실행합니다. 의미적으로 유사한 문서를 관련성과 벡터 검색 점수 순으로 반환합니다.

# Generate embedding for the search query
query_embedding = get_embedding("ocean tragedy")
# Sample vector search pipeline
pipeline = [
{
"$vectorSearch": {
"index": "vector_index",
"queryVector": query_embedding,
"path": "embedding",
"exact": true,
"limit": 5
}
},
{
"$project": {
"_id": 0,
"text": 1,
"score": {
"$meta": "vectorSearchScore"
}
}
}
]
# Execute the search
results = collection.aggregate(pipeline)
# Print results
for i in results:
print(i)
{'text': 'Titanic: The story of the 1912 sinking of the largest luxury liner ever built','score': 0.5103757977485657}
{'text': 'Avatar: A marine is dispatched to the moon Pandora on a unique mission','score': 0.4616812467575073}
{'text': 'The Lion King: Lion cub and future king Simba searches for his identity','score': 0.4115804433822632}
1

데이터에 대한 벡터 검색 쿼리를 활성화하려면 컬렉션에 Atlas Vector Search 인덱스를 생성해야 합니다.

다음 코드를 실행하여 sample_db.embeddings 컬렉션에 embedding 필드를 벡터 유형으로, 1536 벡터 차원, 유사성 측정값을 euclidean 로 지정하는 인덱스를 만듭니다.

from pymongo.operations import SearchIndexModel
# Create your index model, then create the search index
search_index_model = SearchIndexModel(
definition = {
"fields": [
{
"type": "vector",
"path": "embedding",
"numDimensions": 1536,
"similarity": "euclidean"
}
]
},
name="vector_index",
type="vectorSearch",
)
collection.create_search_index(model=search_index_model)

자세히 알아보려면 Atlas Vector Search 인덱스 만들기를 참조하세요.

2

벡터 검색 쿼리를 실행하려면 쿼리 벡터 를 생성하여 집계 파이프라인에 전달할 수 있습니다.

예를 들어 다음 코드는 다음을 수행합니다.

  • 이전 예제에서 정의한 임베딩 함수를 호출하여 문자열 ocean tragedy 에 대한 임베딩을 생성합니다.

  • 임베딩을 집계 파이프라인의 queryVector 필드에 전달합니다.

  • 벡터 검색 쿼리를 실행합니다. 의미적으로 유사한 문서를 관련성과 벡터 검색 점수 순으로 반환합니다.

# Generate embedding for the search query
query_embedding = get_embedding("ocean tragedy")
# Sample vector search pipeline
pipeline = [
{
"$vectorSearch": {
"index": "vector_index",
"queryVector": query_embedding,
"path": "embedding",
"exact": true,
"limit": 5
}
},
{
"$project": {
"_id": 0,
"text": 1,
"score": {
"$meta": "vectorSearchScore"
}
}
}
]
# Execute the search
results = collection.aggregate(pipeline)
# Print results
for i in results:
print(i)
{'text': 'Titanic: The story of the 1912 sinking of the largest luxury liner ever built','score': 0.4551968574523926}
{'text': 'Avatar: A marine is dispatched to the moon Pandora on a unique mission','score': 0.4050074517726898}
{'text': 'The Lion King: Lion cub and future king Simba searches for his identity','score': 0.3594386577606201}

API 엔드포인트를 직접 호출하여 임베딩을 생성할 수도 있습니다. 자세한 내용은 OpenAI API 참조를 참조하세요.

벡터 검색 쿼리 실행에 대해 자세히 알아보려면 벡터 검색 쿼리 실행을 참조하세요.

돌아가기

Atlas Vector Search 빠른 시작

다음

색인 생성 및 관리