引言
在当今的数据驱动世界中,NoSQL数据库如Couchbase已经成为许多应用程序的基石。Couchbase不仅提供了高性能和可扩展性,还集成了AI支持的功能,如向量搜索,使开发者能够更有效地利用数据。本教程将带你探索如何在Couchbase中使用向量搜索,从而增强你的应用程序能力。
主要内容
1. 设置环境
在开始使用Couchbase向量搜索之前,你需要安装langchain-couchbase合作包:
pip install -qU langchain-couchbase
2. 凭证管理
访问Couchbase集群需要先创建连接,并保存数据库的用户名和密码:
import getpass
COUCHBASE_CONNECTION_STRING = getpass.getpass("Enter the connection string for the Couchbase cluster: ")
DB_USERNAME = getpass.getpass("Enter the username for the Couchbase cluster: ")
DB_PASSWORD = getpass.getpass("Enter the password for the Couchbase cluster: ")
3. 初始化
在实例化之前,我们需要建立与Couchbase集群的连接:
from datetime import timedelta
from couchbase.auth import PasswordAuthenticator
from couchbase.cluster import Cluster
from couchbase.options import ClusterOptions
auth = PasswordAuthenticator(DB_USERNAME, DB_PASSWORD)
options = ClusterOptions(auth)
cluster = Cluster(COUCHBASE_CONNECTION_STRING, options)
# 等待集群准备就绪
cluster.wait_until_ready(timedelta(seconds=5))
4. 向量存储管理
创建向量存储对象
接下来,我们需要创建一个向量存储对象,并指定所需的搜索索引名称:
from langchain_couchbase.vectorstores import CouchbaseVectorStore
vector_store = CouchbaseVectorStore(
cluster=cluster,
bucket_name="langchain_bucket",
scope_name="_default",
collection_name="default",
embedding=None, # 替换为实际的嵌入
index_name="langchain-test-index",
)
添加和删除文档
我们可以通过add_documents方法添加文档,以及通过delete方法删除文档。
from uuid import uuid4
from langchain_core.documents import Document
documents = [
Document(page_content="Example content.", metadata={"source": "tweet"}),
# 其他文档
]
uuids = [str(uuid4()) for _ in range(len(documents))]
vector_store.add_documents(documents=documents, ids=uuids)
vector_store.delete(ids=[uuids[-1]])
查询向量存储
进行相似性搜索以查找相关文档:
results = vector_store.similarity_search("Search query", k=2)
for res in results:
print(f"* {res.page_content} [{res.metadata}]")
常见问题和解决方案
问题1: 我没有看到我在搜索结果中指定的所有字段。
解决方案: 请确保这些字段已在搜索索引中进行索引和存储。
问题2: 我无法看到搜索结果中的元数据对象。
解决方案: 请确保在搜索索引中正确映射和存储了metadata字段。
总结和进一步学习资源
通过本教程,你应该了解如何利用Couchbase中的向量搜索功能来增强应用程序功能。若要进一步探索,请参考以下资源:
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---