如何创建向量嵌入
向量嵌入将数据表示为多维空间中的点。这些嵌入捕获数据中有意义的关系,并支持语义搜索和检索等任务。您可以将矢量嵌入与其他数据一起存储在 Atlas 中,并使用 Atlas Vector Search 查询矢量化数据。
要对嵌入执行向量搜索,请执行以下操作:
选择一种创建向量嵌入的方法。
从您的数据创建向量嵌入并将其存储在 Atlas 中。
创建表示搜索查询的向量嵌入并运行查询。
Atlas Vector Search 返回向量嵌入与表示查询的嵌入距离最近的文档。这表明它们的含义相似。
选择创建嵌入的方法
要创建向量嵌入,您必须使用嵌入模型。要连接到嵌入模型并为 Atlas Vector Search 创建嵌入,请使用以下方法之一:
方法 | 说明 | 教程 |
---|---|---|
加载开源模型 | 如果您没有用于嵌入服务的 API密钥或信用额度,请通过从应用程序在本地加载开源嵌入模型来使用。 | |
调用嵌入服务 | 大多数 AI 提供商都为其专有的嵌入模型提供API ,可用于创建向量嵌入。 | |
使用集成 | 您可以将 Atlas Vector Search 与LangChain和LlamaIndex等开源框架以及Amazon Bedrock等服务集成。 这些集成包括内置库和工具,可帮助您快速连接到开源和专有的嵌入模型,并为 Atlas Vector Search 生成矢量嵌入。 |
从数据创建和存储嵌入
以下过程展示了如何使用开源或专有的嵌入模型创建向量嵌入并将其存储在 Atlas 中。
➤ 使用 Select your language(选择您的语言)下拉菜单设置此页面上示例的语言。
先决条件
要运行这些示例,您必须具备以下条件:
运行 MongoDB 6版本的 Atlas 集群。 0 。 11 、 7 。 0 。 2或更高版本。确保您的IP 地址包含在 Atlas 项目的访问列表中。
用于运行 Node.js 项目的终端和代码编辑器。
npm 和 Node.js 已安装。
运行 MongoDB 6版本的 Atlas 集群。 0 。 11 、 7 。 0 。 2或更高版本。确保您的IP 地址包含在 Atlas 项目的访问列表中。
运行交互式 Python 笔记本(例如 Colab)的环境。
步骤
完成以下步骤,从自定义数据创建向量嵌入并将其存储在 Atlas 的集合中。您还可以修改以下代码,从自己的任何类型的数据生成嵌入。
注意
如果要为现有集合创建嵌入,则必须添加包含嵌入的新字段并更新集合中的每个文档。
更新package.json
文件。
配置项目以使用 ES 模块 "type": "module"
package.json
将 添加到 文件,然后保存。
{ "type": "module", // other fields... }
创建向量嵌入并将其存储在 Atlas 中。
创建一个名为
create-embeddings.js
的文件并粘贴以下代码。此代码执行以下操作:创建并导出名为
getEmbedding
的异步函数,为给定输入生成嵌入。此函数还指定:feature-extraction
Huging Face 的 transformers.js 中的 任务 库。要了解更多信息,请参阅 任务。nomic-embed-text-v1 嵌入模型。
从样本文本数据生成嵌入,并使用 MongoDB Node.js 驱动程序将其摄取到 Atlas 中的
sample_db.embeddings
集合中。
create-embeddings.jsimport { 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); 将
<connectionString>
替换为 Atlas 集群的SRV连接字符串。注意
连接字符串应使用以下格式:
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net 保存文件,然后运行以下命令:
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 用户界面中查看向量嵌入。
更新package.json
文件。
配置项目以使用 ES 模块 "type": "module"
package.json
将 添加到 文件,然后保存。
{ "type": "module", // other fields... }
创建向量嵌入并将其存储在 Atlas 中。
创建一个名为
create-embeddings.js
的文件并粘贴以下代码。此代码执行以下操作:创建并导出名为
getEmbedding
的异步函数,该函数使用 OpenAI 的text-embedding-3-small
模型为给定输入生成嵌入。从样本文本数据生成嵌入,并使用 MongoDB Node.js 驱动程序将其摄取到 Atlas 中的
sample_db.embeddings
集合中。
create-embeddings.jsimport { 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); 替换以下占位符值:
<apiKey>
与您的 OpenAI API密钥。<connectionString>
替换为 Atlas 集群的SRV连接字符串。
注意
连接字符串应使用以下格式:
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net 保存文件,然后运行以下命令:
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 用户界面中查看向量嵌入。
创建一个函数以生成向量嵌入。
在笔记本中粘贴并运行以下代码,以创建一个函数,该函数使用 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, ... ]
创建嵌入并将其存储在 Atlas 中。
在笔记本中粘贴并运行以下代码,以连接到 Atlas 集群,从自定义数据生成嵌入,并使用 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
collection,在 Atlas 用户界面中查看向量嵌入。
创建一个函数以生成向量嵌入。
在笔记本中粘贴并运行以下代码,以创建一个函数,该函数使用 OpenAI 的专有嵌入模型生成向量嵌入 。将<api-key>
替换为您的 OpenAI API 密钥。此代码执行以下操作:
指定
text-embedding-3-small
嵌入模型。创建一个名为
get_embedding
的函数,该函数调用模型的API来为给定的文本输入生成嵌入。为字符串
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, ... ]
创建嵌入并将其存储在 Atlas 中。
在笔记本中粘贴并运行以下代码,以连接到 Atlas 集群,从自定义数据生成嵌入,并使用 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
collection,在 Atlas 用户界面中查看向量嵌入。
为查询创建嵌入
以下过程展示了如何使用开源或专有的嵌入模型为 Atlas Vector Search 查询创建嵌入。
步骤
从样本数据创建嵌入后,请完成以下步骤,对数据和嵌入创建 Atlas Vector Search 索引,以进行向量搜索查询。
创建 Atlas Vector Search 索引。
要对数据启用向量搜索查询,必须在集合上创建 Atlas Vector Search 索引。
完成以下步骤,在sample_db.embeddings
集合上创建索引,将embedding
字段指定为向量类型,将768
向量维度指定为 euclidean
,并将相似性度量指定为 。
创建一个名为
create-index.js
的文件并粘贴以下代码。create-index.jsimport { 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); 将
<connectionString>
替换为 Atlas 集群的SRV连接字符串。保存文件,然后运行以下命令:
node create-index.js
要了解更多信息,请参阅创建 Atlas Vector Search 索引。
为向量搜索查询创建嵌入并运行查询。
创建一个名为
vector-query.js
的文件并粘贴以下代码。要运行向量搜索查询,请生成要传递到聚合管道的查询向量。
例如,以下代码执行以下操作:
通过调用您在上一示例中定义的嵌入函数,为字符串
ocean tragedy
创建嵌入。将嵌入传递到聚合管道中的
queryVector
字段。运行向量搜索查询。它按相关性顺序返回语义相似的文档及其向量搜索分数。
vector-query.jsimport { 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); 将
<connectionString>
替换为 Atlas 集群的SRV连接字符串。保存文件,然后运行以下命令:
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}'
创建 Atlas Vector Search 索引。
要对数据启用向量搜索查询,必须在集合上创建 Atlas Vector Search 索引。
完成以下步骤,在sample_db.embeddings
集合上创建索引,将embedding
字段指定为向量类型,将1536
向量维度指定为 euclidean
,并将相似性度量指定为 。
创建一个名为
create-index.js
的文件并粘贴以下代码。create-index.jsimport { 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); 将
<connectionString>
替换为 Atlas 集群的SRV连接字符串。保存文件,然后运行以下命令:
node create-index.js
要了解更多信息,请参阅创建 Atlas Vector Search 索引。
为向量搜索查询创建嵌入并运行查询。
创建一个名为
vector-query.js
的文件并粘贴以下代码。要运行向量搜索查询,请生成要传递到聚合管道的查询向量。
例如,以下代码执行以下操作:
通过调用您在上一示例中定义的嵌入函数,为字符串
ocean tragedy
创建嵌入。将嵌入传递到聚合管道中的
queryVector
字段。运行向量搜索查询。它按相关性顺序返回语义相似的文档及其向量搜索分数。
vector-query.jsimport { 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); 将
<connectionString>
替换为 Atlas 集群的SRV连接字符串。保存文件,然后运行以下命令:
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}'
创建 Atlas Vector Search 索引。
要对数据启用向量搜索查询,必须在集合上创建 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 索引。
为向量搜索查询创建嵌入并运行查询。
要运行向量搜索查询,请生成要传递到聚合管道的查询向量。
例如,以下代码执行以下操作:
通过调用您在上一示例中定义的嵌入函数,为字符串
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}
创建 Atlas Vector Search 索引。
要对数据启用向量搜索查询,必须在集合上创建 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 索引。
为向量搜索查询创建嵌入并运行查询。
要运行向量搜索查询,请生成要传递到聚合管道的查询向量。
例如,以下代码执行以下操作:
通过调用您在上一示例中定义的嵌入函数,为字符串
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 参考文档。
要了解有关运行向量搜索查询的更多信息,请参阅运行向量搜索查询。