探索Couchbase中的向量搜索:强大而灵活的NoSQL解决方案

37 阅读3分钟

引言

Couchbase是一个屡获殊荣的分布式NoSQL云数据库,因其卓越的灵活性、性能、可扩展性和经济价值而广受欢迎。它在支持云端、移动、AI和边缘计算应用方面表现出色。值得一提的是,Couchbase正拥抱人工智能技术,通过为开发者提供代码辅助和应用程序向量搜索来增强其功能。在本文中,我们将详细探讨如何在Couchbase中使用向量搜索功能。

主要内容

向量搜索简介

向量搜索是Couchbase全文搜索服务(Search Service)的一部分,提供了基于向量的搜索能力,可以与其他索引字段结合使用,进行更全面的文档检索。这使得数据查询变得更加灵活和高效。

安装与设置

要使用Couchbase的VectorStore,首先需要安装langchain-couchbase合作包。运行以下命令可以完成安装:

pip install -qU langchain-couchbase

接下来,您需要在Couchbase网站上创建一个新的连接,并确保保存数据库的用户名和密码。以下Python代码示例展示了如何安全地输入这些凭据:

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: ")

初始化

在实例化对象之前,首先我们需要创建一个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))

创建向量存储

通过以下步骤创建一个向量存储对象:

from langchain_couchbase.vectorstores import CouchbaseVectorStore
from langchain_openai import OpenAIEmbeddings

embeddings = OpenAIEmbeddings(model="text-embedding-3-large")

vector_store = CouchbaseVectorStore(
    cluster=cluster,
    bucket_name="langchain_bucket",
    scope_name="_default",
    collection_name="default",
    embedding=embeddings,
    index_name="langchain-test-index",
)

代码示例

from uuid import uuid4
from langchain_core.documents import Document

# 创建文档示例
documents = [
    Document(page_content="I had chocolate chip pancakes for breakfast.", metadata={"source": "tweet"}),
    Document(page_content="The weather today is cloudy.", metadata={"source": "news"}),
]

# 生成唯一ID并添加文档到向量存储
uuids = [str(uuid4()) for _ in range(len(documents))]
vector_store.add_documents(documents=documents, ids=uuids)

# 执行相似性搜索
results = vector_store.similarity_search("What did I have for breakfast?", k=1)
for res in results:
    print(f"* {res.page_content} [{res.metadata}]")

常见问题和解决方案

问题1:未创建搜索索引前是否可以创建CouchbaseVectorStore对象?

是的,您需要先创建搜索索引,然后才能创建CouchbaseVectorStore对象。

问题2:搜索结果中没有看到我指定的字段?

确保您要访问的字段已包含在搜索索引中。可通过在"Advanced Mode"中启用动态字段存储来解决此问题。

总结和进一步学习资源

Couchbase的向量搜索为数据检索带来了强大的灵活性,特别是在结合AI技术时,能大大提升应用程序的智能性和响应能力。通过上面的步骤,您可以快速上手Couchbase的向量搜索功能,并将其集成到您的项目中。

参考资料

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---