Skip to main content
Open In ColabOpen on GitHub

SingleStoreVectorStore

SingleStore is a robust, high-performance distributed SQL database solution designed to excel in both cloud and on-premises environments. Boasting a versatile feature set, it offers seamless deployment options while delivering unparalleled performance.

SingleStore 的一个突出特点是其对向量存储和操作的高级支持,使其成为需要复杂人工智能功能(如文本相似性匹配)的应用的理想选择。通过内置的向量函数,例如 点积欧几里得距离,SingleStore 使开发者能够高效地实现复杂的算法。

对于希望在SingleStore中利用向量数据的开发者,一份全面的教程可供使用,指导他们了解处理向量数据的复杂性。该教程深入探讨了SingleStoreDB中的向量存储,展示了其基于向量相似性进行搜索的能力。借助向量索引,查询可以以极快的速度执行,从而实现快速检索相关数据。

此外,SingleStore 的向量存储与基于 Lucene 的全文索引无缝集成,支持强大的文本相似性搜索。用户可以根据文档元数据对象的选定字段过滤搜索结果,从而提高查询精度。

SingleStore的独特之处在于它能够以多种方式结合向量搜索和全文搜索,提供灵活性和多功能性。无论是通过文本或向量相似性进行预筛选并选择最相关数据,还是采用加权求和的方法计算最终的相似度分数,开发者都有多种选择可用。

本质上,SingleStore 提供了一个全面的解决方案来管理和查询向量数据,为人工智能驱动的应用程序提供了无与伦比的性能和灵活性。

JS 支持
SingleStoreVectorStorelangchain_singlestore
笔记

对于 langchain-community 版本 SingleStoreDB(已弃用),请参阅 v0.2 文档

设置

要访问 SingleStore 向量存储,您需要安装 langchain-singlestore 集成包。 %pip install -qU "langchain-singlestore"

初始化

要初始化 SingleStoreVectorStore,你需要一个 Embeddings 对象以及连接 SingleStore 数据库的参数。

必需参数:

  • 嵌入 (Embeddings): 一种文本嵌入模型。

可选参数:

  • distance_strategy (DistanceStrategy): 计算向量距离的策略。默认为 DOT_PRODUCT。选项:

    • DOT_PRODUCT: 计算两个向量的标量积。
    • EUCLIDEAN_DISTANCE: 计算两个向量之间的欧几里得距离。
  • 表名 (str): 表的名称。默认为 embeddings

  • content_field (str): 用于存储内容的字段。默认值为 content

  • metadata_field (str): 用于存储元数据的字段。默认值为 metadata

  • 向量字段 (str): 用于存储向量的字段。默认为 vector

  • id字段 (str): 用于存储ID的字段。默认值为 id

  • use_vector_index (bool): 启用向量索引(需要 SingleStore 8.5+)。默认值为 False

  • vector_index_name (str): 向量索引的名称。如果 use_vector_indexFalse,则忽略。

  • vector_index_options (dict): 向量索引的选项。如果 use_vector_indexFalse,则忽略。

  • 向量大小 (int): 向量的大小。如果 use_vector_indexTrue,则为必填项。

  • use_full_text_search (bool): 启用内容的全文索引。默认为 False

连接池参数:

  • pool_sizeint):池中活动连接的数量。默认值为 5
  • max_overflowint):超出 pool_size 的最大连接数。默认值为 10
  • 超时 (float):连接超时时间(秒)。默认值为 30

数据库连接参数:

  • 主机 (str): 数据库的主机名、IP 地址或 URL。
  • 用户 (str): 数据库用户名。
  • 密码 (str): 数据库密码。
  • 端口 (int): 数据库端口。默认为 3306
  • 数据库 (str): 数据库名称。

其他选项:

  • pure_python (bool):启用纯 Python 模式。
  • local_infile (bool):允许本地文件上传。
  • charset (str): 字符串值的字符集。
  • ssl_keyssl_certssl_castr):SSL 文件的路径。
  • ssl_disabled (bool):禁用 SSL。
  • ssl_verify_cert (bool): 验证服务器的证书。
  • ssl_verify_identity (bool):验证服务器身份。
  • autocommit (bool):启用自动提交。
  • results_typestr):查询结果的结构(例如:tuplesdicts)。
import os

from langchain_singlestore.vectorstores import SingleStoreVectorStore

os.environ["SINGLESTOREDB_URL"] = "root:pass@localhost:3306/db"

vector_store = SingleStoreVectorStore(embeddings=embeddings)

管理向量存储

SingleStoreVectorStore 假设文档的 ID 是一个整数。以下是管理向量存储器的一些示例。

将项目添加到向量存储

你可以按照以下方式将文档添加到向量存储中:

%pip install -qU langchain-core
from langchain_core.documents import Document

docs = [
Document(
page_content="""In the parched desert, a sudden rainstorm brought relief,
as the droplets danced upon the thirsty earth, rejuvenating the landscape
with the sweet scent of petrichor.""",
metadata={"category": "rain"},
),
Document(
page_content="""Amidst the bustling cityscape, the rain fell relentlessly,
creating a symphony of pitter-patter on the pavement, while umbrellas
bloomed like colorful flowers in a sea of gray.""",
metadata={"category": "rain"},
),
Document(
page_content="""High in the mountains, the rain transformed into a delicate
mist, enveloping the peaks in a mystical veil, where each droplet seemed to
whisper secrets to the ancient rocks below.""",
metadata={"category": "rain"},
),
Document(
page_content="""Blanketing the countryside in a soft, pristine layer, the
snowfall painted a serene tableau, muffling the world in a tranquil hush
as delicate flakes settled upon the branches of trees like nature's own
lacework.""",
metadata={"category": "snow"},
),
Document(
page_content="""In the urban landscape, snow descended, transforming
bustling streets into a winter wonderland, where the laughter of
children echoed amidst the flurry of snowballs and the twinkle of
holiday lights.""",
metadata={"category": "snow"},
),
Document(
page_content="""Atop the rugged peaks, snow fell with an unyielding
intensity, sculpting the landscape into a pristine alpine paradise,
where the frozen crystals shimmered under the moonlight, casting a
spell of enchantment over the wilderness below.""",
metadata={"category": "snow"},
),
]


vector_store.add_documents(docs)
API 参考:文档

更新向量存储中的项目

要更新向量存储中的现有文档,请使用以下代码:

updated_document = Document(
page_content="qux", metadata={"source": "https://another-example.com"}
)

vector_store.update_documents(document_id="1", document=updated_document)

从向量存储中删除项目

要从向量存储中删除文档,请使用以下代码:

vector_store.delete(ids=["3"])

查询向量存储

一旦您的向量存储已创建并添加了相关文档,您很可能希望在链或代理运行期间对其进行查询。

直接查询

执行简单的相似度搜索可以按以下方式完成:

results = vector_store.similarity_search(query="trees in the snow", k=1)
for doc in results:
print(f"* {doc.page_content} [{doc.metadata}]")

如果您想执行相似度搜索并获取相应的分数,可以运行:

  • TODO:编辑并运行代码单元格以生成输出
results = vector_store.similarity_search_with_score(query="trees in the snow", k=1)
for doc, score in results:
print(f"* [SIM={score:3f}] {doc.page_content} [{doc.metadata}]")

元数据过滤

SingleStoreDB通过允许用户根据元数据字段进行预筛选来提升搜索功能,从而增强和优化搜索结果。这一功能使开发者和数据分析师能够对查询进行微调,确保搜索结果完全符合他们的需求。通过使用特定的元数据属性筛选搜索结果,用户可以缩小查询范围,仅关注相关数据子集。

query = "trees branches"
docs = vector_store.similarity_search(
query, filter={"category": "snow"}
) # Find documents that correspond to the query and has category "snow"
print(docs[0].page_content)

向量索引

通过利用ANN向量索引,在使用版本8.5或更高版本的SingleStore DB时,可以提高搜索效率。在创建向量存储对象时设置use_vector_index=True即可启用此功能。此外,如果您的向量维度与默认的OpenAI嵌入大小1536不同,请相应地指定vector_size参数。

搜索策略

SingleStoreDB 提供了多种搜索策略,每种策略都经过精心设计,以满足特定的使用场景和用户偏好。默认的 VECTOR_ONLY 策略利用向量操作(如 dot_producteuclidean_distance)直接计算向量之间的相似度得分,而 TEXT_ONLY 则采用基于 Lucene 的全文搜索,特别适用于文本密集型应用。对于寻求平衡方法的用户,FILTER_BY_TEXT 首先根据文本相似性进行结果筛选,然后再进行向量比较;而 FILTER_BY_VECTOR 则优先考虑向量相似性,在评估文本相似性之前过滤结果,以获得最佳匹配。值得注意的是,FILTER_BY_TEXTFILTER_BY_VECTOR 都需要全文索引才能运行。此外,WEIGHTED_SUM 是一种复杂的策略,通过权衡向量和文本相似性来计算最终的相似度得分,但仅使用点积距离计算,并且也需要全文索引。这些灵活的策略使用户能够根据自身需求优化搜索,从而实现高效且精确的数据检索与分析。此外,SingleStoreDB 的混合方法(如 FILTER_BY_TEXTFILTER_BY_VECTORWEIGHTED_SUM 策略)巧妙地结合了向量和文本搜索,以最大化效率和准确性,确保用户能够充分利用平台的功能,应对各种应用场景。

from langchain_singlestore.vectorstores import DistanceStrategy

docsearch = SingleStoreVectorStore.from_documents(
docs,
embeddings,
distance_strategy=DistanceStrategy.DOT_PRODUCT, # Use dot product for similarity search
use_vector_index=True, # Use vector index for faster search
use_full_text_search=True, # Use full text index
)

vectorResults = docsearch.similarity_search(
"rainstorm in parched desert, rain",
k=1,
search_strategy=SingleStoreVectorStore.SearchStrategy.VECTOR_ONLY,
filter={"category": "rain"},
)
print(vectorResults[0].page_content)

textResults = docsearch.similarity_search(
"rainstorm in parched desert, rain",
k=1,
search_strategy=SingleStoreVectorStore.SearchStrategy.TEXT_ONLY,
)
print(textResults[0].page_content)

filteredByTextResults = docsearch.similarity_search(
"rainstorm in parched desert, rain",
k=1,
search_strategy=SingleStoreVectorStore.SearchStrategy.FILTER_BY_TEXT,
filter_threshold=0.1,
)
print(filteredByTextResults[0].page_content)

filteredByVectorResults = docsearch.similarity_search(
"rainstorm in parched desert, rain",
k=1,
search_strategy=SingleStoreVectorStore.SearchStrategy.FILTER_BY_VECTOR,
filter_threshold=0.1,
)
print(filteredByVectorResults[0].page_content)

weightedSumResults = docsearch.similarity_search(
"rainstorm in parched desert, rain",
k=1,
search_strategy=SingleStoreVectorStore.SearchStrategy.WEIGHTED_SUM,
text_weight=0.2,
vector_weight=0.8,
)
print(weightedSumResults[0].page_content)

通过转换为检索器进行查询

您还可以将向量存储转换为检索器,以便在链中更轻松地使用。

retriever = vector_store.as_retriever(search_kwargs={"k": 1})
retriever.invoke("trees in the snow")

多模态示例:利用CLIP和OpenClip嵌入

在多模态数据分析领域,整合图像和文本等不同类型信息的重要性日益凸显。一个强大的工具是CLIP,这是一种先进的模型,能够将图像和文本嵌入到共享的语义空间中。通过这种方式,CLIP可以通过相似性搜索实现跨模态的相关内容检索。

例如,让我们考虑一个应用场景,我们旨在有效地分析多模态数据。在这个例子中,我们利用了 OpenClip 多模态嵌入 的能力,它利用了 CLIP 的框架。通过 OpenClip,我们可以无缝地将文本描述与相应的图像嵌入在一起,从而实现全面的分析和检索任务。无论是根据文本查询识别视觉上相似的图像,还是找到与特定视觉内容相关的相关文本段落,OpenClip 都能帮助用户以极高的效率和准确性探索和提取多模态数据中的洞察。

%pip install -U langchain openai lanchain-singlestore langchain-experimental
import os

from langchain_experimental.open_clip import OpenCLIPEmbeddings
from langchain_singlestore.vectorstores import SingleStoreVectorStore

os.environ["SINGLESTOREDB_URL"] = "root:pass@localhost:3306/db"

TEST_IMAGES_DIR = "../../modules/images"

docsearch = SingleStoreVectorStore(OpenCLIPEmbeddings())

image_uris = sorted(
[
os.path.join(TEST_IMAGES_DIR, image_name)
for image_name in os.listdir(TEST_IMAGES_DIR)
if image_name.endswith(".jpg")
]
)

# Add images
docsearch.add_images(uris=image_uris)
API 参考:OpenCLIPEmbeddings

检索增强生成的用法

有关如何使用此向量存储进行检索增强生成 (RAG) 的指南,请参阅以下部分:

API 参考

有关所有 SingleStore 文档加载器功能和配置的详细文档,请前往 GitHub 页面:https://github.com/singlestore-labs/langchain-singlestore/