SingleStoreVectorStore
SingleStore 是一种强大的高性能分布式 SQL 数据库解决方案,旨在在云中和本地环境中表现出色。它拥有多功能功能集,提供无缝部署选项,同时提供无与伦比的性能。
SingleStore 的一个突出特点是它对向量存储和作的高级支持,使其成为需要复杂 AI 功能(如文本相似性匹配)的应用程序的理想选择。借助 dot_product 和 euclidean_distance 等内置向量函数,SingleStore 使开发人员能够高效地实施复杂的算法。
对于热衷于在 SingleStore 中利用矢量数据的开发人员,提供了一个全面的教程,指导他们了解使用矢量数据的复杂性。本教程深入探讨了 SingleStoreDB 中的 Vector Store,展示了它根据 vector 相似性促进搜索的能力。利用矢量索引,可以以极快的速度执行查询,从而快速检索相关数据。
此外,SingleStore 的 Vector Store 与基于 Lucene 的全文索引无缝集成,实现了强大的文本相似性搜索。用户可以根据文档元数据对象的选定字段筛选搜索结果,从而提高查询精度。
SingleStore 的与众不同之处在于它能够以各种方式组合矢量和全文搜索,从而提供灵活性和多功能性。无论是按文本或向量相似度进行预筛选并选择最相关的数据,还是采用加权和方法来计算最终相似度分数,开发人员都有多种选择。
从本质上讲,SingleStore 为管理和查询矢量数据提供了全面的解决方案,为 AI 驱动的应用程序提供了无与伦比的性能和灵活性。
| 类 | 包 | JS 支持 |
|---|---|---|
| SingleStoreVectorStore | langchain_singlestore | ✅ |
对于 langchain-community 版本SingleStoreDB(已弃用),请参阅
v0.2 文档。
设置
要访问 SingleStore 向量存储,您需要安装langchain-singlestore集成包。
%pip install -qU “langchain-singlestore”
初始化
初始化SingleStoreVectorStore,您需要一个Embeddingsobject 和 connection 参数。
必需参数:
- 嵌入 (
Embeddings):文本嵌入模型。
可选参数:
-
distance_strategy (
DistanceStrategy):计算矢量距离的策略。默认为DOT_PRODUCT.选项:DOT_PRODUCT:计算两个向量的标量积。EUCLIDEAN_DISTANCE:计算两个向量之间的欧氏距离。
-
table_name (
str):表的名称。默认为embeddings. -
content_field (
str):用于存储内容的字段。默认为content. -
metadata_field (
str):用于存储元数据的字段。默认为metadata. -
vector_field (
str):用于存储向量的字段。默认为vector. -
id_field (
str):用于存储 ID 的字段。默认为id. -
use_vector_index (
bool):启用矢量索引(需要 SingleStore 8.5+)。默认为False. -
vector_index_name (
str):向量索引的名称。如果 Ignoreduse_vector_index是False. -
vector_index_options (
dict):向量索引的选项。如果 Ignoreduse_vector_index是False. -
vector_size (
int):向量的大小。如果 requireuse_vector_index是True. -
use_full_text_search (
bool):启用对内容的全文索引。默认为False.
连接池参数:
- pool_size (
int):池中的活动连接数。默认为5. - max_overflow (
int):超出的最大连接数pool_size.默认为10. - 超时 (
float):连接超时(以秒为单位)。默认为30.
数据库连接参数:
- 主机 (
str):数据库的主机名、IP 或 URL。 - 用户 (
str):数据库用户名。 - 密码 (
str):数据库密码。 - 港口 (
int):数据库端口。默认为3306. - 数据库 (
str):数据库名称。
其他选项:
- pure_python (
bool):启用纯 Python 模式。 - local_infile (
bool):允许本地文件上传。 - 字符集 (
str):字符串值的字符集。 - ssl_key、ssl_cert ssl_ca (
str):SSL 文件的路径。 - ssl_disabled (
bool):禁用 SSL。 - ssl_verify_cert (
bool):验证服务器的证书。 - ssl_verify_identity (
bool):验证服务器的身份。 - 自动提交 (
bool):启用自动提交。 - results_type (
str):查询结果的结构(例如tuples,dicts).
import os
from langchain_singlestore.vectorstores import SingleStoreVectorStore
os.environ["SINGLESTOREDB_URL"] = "root:pass@localhost:3306/db"
vector_store = SingleStoreVectorStore(embeddings=embeddings)
管理矢量存储
这SingleStoreVectorStore假设 Document 的 ID 是一个整数。以下是如何管理 vector store 的示例。
将项目添加到向量存储
您可以按如下方式将文档添加到矢量存储中:
%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)
更新 vector store 中的项
要更新 vector store 中的现有文档,请使用以下代码:
updated_document = Document(
page_content="qux", metadata={"source": "https://another-example.com"}
)
vector_store.update_documents(document_id="1", document=updated_document)
从 vector store 中删除项目
要从矢量存储中删除文档,请使用以下代码:
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 向量索引,使用 SingleStore DB 版本 8.5 或更高版本提高搜索效率。通过设置use_vector_index=True在 Vector Store 对象创建期间,您可以激活此功能。此外,如果您的向量的维数与默认的 OpenAI 嵌入大小 1536 不同,请确保指定vector_size参数。
搜索策略
SingleStoreDB 提供了多种搜索策略,每种策略都经过精心设计,以满足特定的使用案例和用户偏好。默认的VECTOR_ONLY策略利用向量运算,例如dot_product或euclidean_distance直接计算向量之间的相似性分数,而TEXT_ONLY使用基于 Lucene 的全文搜索,特别有利于以文本为中心的应用程序。对于寻求平衡方法的用户,FILTER_BY_TEXT首先根据文本相似性优化结果,然后再进行向量比较,而FILTER_BY_VECTOR确定向量相似度的优先级,在评估文本相似度以获得最佳匹配之前筛选结果。值得注意的是,两者FILTER_BY_TEXT和FILTER_BY_VECTOR需要 operation.此外WEIGHTED_SUM作为一种复杂的策略出现,通过权衡向量和文本相似性来计算最终的相似度分数,尽管完全使用dot_product距离计算并且还需要全文索引。这些多功能策略使用户能够根据其独特需求微调搜索,从而促进高效、精确的数据检索和分析。此外,SingleStoreDB 的混合方法,例如FILTER_BY_TEXT,FILTER_BY_VECTOR和WEIGHTED_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 转换为检索器,以便在您的链中更轻松地使用。
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)
用于检索增强生成
有关如何使用此向量存储进行检索增强生成 (RAG) 的指南,请参阅以下部分:
API 参考
有关所有 SingleStore Document Loader 功能和配置的详细文档,请访问 github 页面:https://github.com/singlestore-labs/langchain-singlestore/