Skip to main content
Couchbase 是一款屡获殊荣的分布式 NoSQL 云数据库,为您所有的云、移动、AI 和边缘计算应用提供无与伦比的通用性、性能、可扩展性和性价比。Couchbase 积极拥抱 AI,为开发者提供编码辅助,为应用提供向量搜索功能。 Couchbase 为 LangChain 提供两种不同的向量存储实现:
向量存储索引类型最低版本要求最适用场景
CouchbaseQueryVectorStore超大规模向量索引复合向量索引Couchbase Server 8.0+大规模纯向量搜索,或将向量相似度与标量过滤相结合的搜索
CouchbaseSearchVectorStore搜索向量索引Couchbase Server 7.6+将向量相似度与全文搜索(FTS)和地理空间搜索相结合的混合搜索
本教程介绍如何在 Couchbase 中使用向量搜索。您可以使用 Couchbase Capella 或自托管的 Couchbase Server。

设置

要访问 Couchbase 向量存储,首先需要安装 langchain-couchbase 合作伙伴包:
pip install langchain-couchbase langchain-openai langchain-community

凭证

前往 Couchbase 官网 创建新连接,并保存您的数据库用户名和密码。 您还需要 OpenAI API 密钥用于嵌入。从 OpenAI 获取。
import getpass
import os

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: ")
OPENAI_API_KEY = getpass.getpass("Enter your OpenAI API key: ")

os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
Enter the connection string for the Couchbase cluster:  ········
Enter the username for the Couchbase cluster:  ········
Enter the password for the Couchbase cluster:  ········
Enter your OpenAI API key:  ········
如果希望获得模型调用的顶级自动追踪功能,还可以取消注释以下内容,设置您的 LangSmith API 密钥:
os.environ["LANGSMITH_TRACING"] = "true"
# os.environ["LANGSMITH_API_KEY"] = getpass.getpass()

创建 Couchbase 连接对象

我们先创建到 Couchbase 集群的连接,然后将集群对象传递给向量存储。 这里我们使用上面的用户名和密码进行连接。您也可以使用其他任何受支持的方式连接到集群。 有关连接到 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)
options.apply_profile("wan_development")
cluster = Cluster(COUCHBASE_CONNECTION_STRING, options)

# 等待集群就绪
cluster.wait_until_ready(timedelta(seconds=5))
接下来设置 Couchbase 集群中用于向量搜索的 bucket、scope 和 collection 名称。 本示例使用默认的 scope 和 collection。
BUCKET_NAME = "langchain_bucket"
SCOPE_NAME = "_default"
COLLECTION_NAME = "_default"

CouchbaseQueryVectorStore

CouchbaseQueryVectorStore 支持使用查询和索引服务在 Couchbase 中进行向量搜索。它支持两种不同类型的向量索引:
  • 超大规模向量索引 - 针对大型数据集(数十亿文档)的纯向量搜索进行优化。最适合内容发现、推荐系统以及需要在低内存占用下实现高精度的应用场景。超大规模向量索引同时比较向量和标量值。
  • 复合向量索引 - 将全局二级索引(GSI)与向量列相结合。适用于向量相似度与标量过滤相结合的搜索场景,尤其是标量过滤能过滤掉大量数据集的情况。复合向量索引先应用标量过滤,再对过滤结果执行向量搜索。
有关选择合适索引类型的指导,请参阅选择合适的向量索引 要求: Couchbase Server 版本 8.0 及以上。 更多索引信息,请参阅:

初始化

以下代码使用集群信息和距离度量创建向量存储对象。 首先设置嵌入(如尚未设置):
from langchain_openai import OpenAIEmbeddings

embeddings = OpenAIEmbeddings(model="text-embedding-3-large")
然后创建向量存储:
from langchain_couchbase import CouchbaseQueryVectorStore
from langchain_couchbase.vectorstores import DistanceStrategy

vector_store = CouchbaseQueryVectorStore(
    cluster=cluster,
    bucket_name=BUCKET_NAME,
    scope_name=SCOPE_NAME,
    collection_name=COLLECTION_NAME,
    embedding=embeddings,
    distance_metric=DistanceStrategy.DOT,
)

距离策略

CouchbaseQueryVectorStore 通过 DistanceStrategy 枚举支持以下距离策略:
策略描述
DistanceStrategy.DOT点积相似度
DistanceStrategy.COSINE余弦相似度
DistanceStrategy.EUCLIDEAN欧氏距离(等价于 L2)
DistanceStrategy.EUCLIDEAN_SQUARED欧氏距离平方(等价于 L2_SQUARED)

指定文本和嵌入字段

您可以通过 text_keyembedding_key 字段可选地指定文档的文本和嵌入字段。
vector_store_specific = CouchbaseQueryVectorStore(
    cluster=cluster,
    bucket_name=BUCKET_NAME,
    scope_name=SCOPE_NAME,
    collection_name=COLLECTION_NAME,
    embedding=embeddings,
    distance_metric=DistanceStrategy.COSINE,
    text_key="text",
    embedding_key="embedding",
)

管理向量存储

创建向量存储后,可以通过添加和删除不同条目与其进行交互。 向向量存储添加条目 可以使用 add_documents 函数向向量存储添加条目。
from uuid import uuid4

from langchain_core.documents import Document

document_1 = Document(page_content="foo", metadata={"baz": "bar"})
document_2 = Document(page_content="thud", metadata={"bar": "baz"})
document_3 = Document(page_content="i will be deleted :(")

documents = [document_1, document_2, document_3]
ids = ["1", "2", "3"]
vector_store.add_documents(documents=documents, ids=ids)
创建向量索引 重要: 向量索引必须在向向量存储添加文档之后创建。请在添加文档后使用 create_index() 方法,以启用高效的向量搜索。
from langchain_couchbase.vectorstores import IndexType

# 创建超大规模向量索引
vector_store.create_index(
    index_type=IndexType.HYPERSCALE,
    index_description="IVF,SQ8",
)
或创建复合向量索引:
# 创建复合向量索引
vector_store.create_index(
    index_type=IndexType.COMPOSITE,
    index_description="IVF,SQ8",
)
从向量存储删除条目
vector_store.delete(ids=["3"])

查询向量存储

相似度搜索 执行简单相似度搜索的方法如下:
results = vector_store.similarity_search(query="thud", k=1)
for doc in results:
    print(f"* {doc.page_content} [{doc.metadata}]")
* thud [{'bar': 'baz'}]
带过滤器的相似度搜索 可以使用 where_str 参数通过 SQL++ WHERE 子句过滤结果:
results = vector_store.similarity_search(
    query="thud", k=1, where_str="metadata.bar = 'baz'"
)
for doc in results:
    print(f"* {doc.page_content} [{doc.metadata}]")
* thud [{'bar': 'baz'}]
带分数的相似度搜索 可以通过调用 similarity_search_with_score 方法获取结果的距离分数。距离越小,文档越相似。
results = vector_store.similarity_search_with_score(query="qux", k=1)
for doc, score in results:
    print(f"* [DIST={score:3f}] {doc.page_content} [{doc.metadata}]")
* [DIST=-0.500724] foo [{'baz': 'bar'}]

异步操作

CouchbaseQueryVectorStore 支持异步操作:
# 添加文档
await vector_store.aadd_documents(documents=documents, ids=ids)

# 删除文档
await vector_store.adelete(ids=["3"])

# 搜索
results = await vector_store.asimilarity_search(query="thud", k=1)

# 带分数的搜索
results = await vector_store.asimilarity_search_with_score(query="qux", k=1)
for doc, score in results:
    print(f"* [DIST={score:3f}] {doc.page_content} [{doc.metadata}]")
* [DIST=-0.500724] foo [{'baz': 'bar'}]

用作检索器

可以将向量存储转换为检索器:
retriever = vector_store.as_retriever(
    search_kwargs={"k": 1, "fetch_k": 2, "lambda_mult": 0.5},
)
retriever.invoke("thud")
[Document(id='2', metadata={'bar': 'baz'}, page_content='thud')]

从文本创建

可以直接从文本列表创建 CouchbaseQueryVectorStore
texts = ["hello", "world"]

vectorstore = CouchbaseQueryVectorStore.from_texts(
    texts,
    embedding=embeddings,
    cluster=cluster,
    bucket_name=BUCKET_NAME,
    scope_name=SCOPE_NAME,
    collection_name=COLLECTION_NAME,
    distance_metric=DistanceStrategy.COSINE,
)

CouchbaseSearchVectorStore

CouchbaseSearchVectorStore 支持使用搜索向量索引在 Couchbase 中进行向量搜索。搜索向量索引将 Couchbase 搜索索引与向量列相结合,支持将向量搜索与全文搜索(FTS)和地理空间搜索相结合的混合搜索。 要求: Couchbase Server 版本 7.6 及以上。 有关如何创建支持向量字段的搜索索引的详细信息,请参阅以下文档:

本教程的搜索索引字段映射

为了跟随本文档中的示例,您的搜索索引应包含以下字段的映射:
字段类型描述
texttext文档文本内容
embeddingvector向量嵌入字段(维度:text-embedding-3-large 为 3072)
metadataobject(子映射)元数据对象,包含 sourceauthorratingdate 等子字段
注意:
  • 向量字段维度必须与您的嵌入模型匹配(本教程使用的 text-embedding-3-large 为 3072)
  • 元数据子字段(sourceauthorratingdate)是混合查询示例所必需的
  • 初始化向量存储时可通过 text_keyembedding_key 参数自定义字段名

初始化

以下代码使用集群信息和搜索索引名称创建向量存储对象。 首先设置嵌入:
from langchain_openai import OpenAIEmbeddings

embeddings = OpenAIEmbeddings(model="text-embedding-3-large")
然后创建向量存储:
from langchain_couchbase import CouchbaseSearchVectorStore

SEARCH_INDEX_NAME = "langchain-test-index"

vector_store = CouchbaseSearchVectorStore(
    cluster=cluster,
    bucket_name=BUCKET_NAME,
    scope_name=SCOPE_NAME,
    collection_name=COLLECTION_NAME,
    embedding=embeddings,
    index_name=SEARCH_INDEX_NAME,
)

指定文本和嵌入字段

可以通过 text_keyembedding_key 字段可选地指定文档的文本和嵌入字段。
vector_store_specific = CouchbaseSearchVectorStore(
    cluster=cluster,
    bucket_name=BUCKET_NAME,
    scope_name=SCOPE_NAME,
    collection_name=COLLECTION_NAME,
    embedding=embeddings,
    index_name=SEARCH_INDEX_NAME,
    text_key="text",
    embedding_key="embedding",
)

管理向量存储

创建向量存储后,可以通过添加和删除不同条目与其进行交互。 向向量存储添加条目 可以使用 add_documents 函数向向量存储添加条目。
from uuid import uuid4

from langchain_core.documents import Document

document_1 = Document(
    page_content="I had chocolate chip pancakes and scrambled eggs for breakfast this morning.",
    metadata={"source": "tweet"},
)

document_2 = Document(
    page_content="The weather forecast for tomorrow is cloudy and overcast, with a high of 62 degrees.",
    metadata={"source": "news"},
)

document_3 = Document(
    page_content="Building an exciting new project with LangChain - come check it out!",
    metadata={"source": "tweet"},
)

document_4 = Document(
    page_content="Robbers broke into the city bank and stole $1 million in cash.",
    metadata={"source": "news"},
)

document_5 = Document(
    page_content="Wow! That was an amazing movie. I can't wait to see it again.",
    metadata={"source": "tweet"},
)

document_6 = Document(
    page_content="Is the new iPhone worth the price? Read this review to find out.",
    metadata={"source": "website"},
)

document_7 = Document(
    page_content="The top 10 soccer players in the world right now.",
    metadata={"source": "website"},
)

document_8 = Document(
    page_content="LangGraph is the best framework for building stateful, agentic applications!",
    metadata={"source": "tweet"},
)

document_9 = Document(
    page_content="The stock market is down 500 points today due to fears of a recession.",
    metadata={"source": "news"},
)

document_10 = Document(
    page_content="I have a bad feeling I am going to get deleted :(",
    metadata={"source": "tweet"},
)

documents = [
    document_1,
    document_2,
    document_3,
    document_4,
    document_5,
    document_6,
    document_7,
    document_8,
    document_9,
    document_10,
]
uuids = [str(uuid4()) for _ in range(len(documents))]

vector_store.add_documents(documents=documents, ids=uuids)
['f125b836-f555-4449-98dc-cbda4e77ae3f',
 'a28fccde-fd32-4775-9ca8-6cdb22ca7031',
 'b1037c4b-947f-497f-84db-63a4def5080b',
 'c7082b74-b385-4c4b-bbe5-0740909c01db',
 'a7e31f62-13a5-4109-b881-8631aff7d46c',
 '9fcc2894-fdb1-41bd-9a93-8547747650f4',
 'a5b0632d-abaf-4802-99b3-df6b6c99be29',
 '0475592e-4b7f-425d-91fd-ac2459d48a36',
 '94c6db4e-ba07-43ff-aa96-3a5d577db43a',
 'd21c7feb-ad47-4e7d-84c5-785afb189160']
从向量存储删除条目
vector_store.delete(ids=[uuids[-1]])
True

查询向量存储

创建向量存储并添加相关文档后,通常需要在运行链或智能体时对其进行查询。 相似度搜索 执行简单相似度搜索的方法如下:
results = vector_store.similarity_search(
    "LangChain provides abstractions to make working with LLMs easy",
    k=2,
)
for res in results:
    print(f"* {res.page_content} [{res.metadata}]")
* Building an exciting new project with LangChain - come check it out! [{'source': 'tweet'}]
* LangGraph is the best framework for building stateful, agentic applications! [{'source': 'tweet'}]
带分数的相似度搜索 也可以通过调用 similarity_search_with_score 方法获取结果的分数。
results = vector_store.similarity_search_with_score("Will it be hot tomorrow?", k=1)
for res, score in results:
    print(f"* [SIM={score:3f}] {res.page_content} [{res.metadata}]")
* [SIM=0.553213] The weather forecast for tomorrow is cloudy and overcast, with a high of 62 degrees. [{'source': 'news'}]

过滤结果

您可以通过在文档的文本或元数据上指定 Couchbase 搜索服务支持的过滤器来过滤搜索结果。 filter 可以是 Couchbase Python SDK 支持的任何有效 SearchQuery。这些过滤器在执行向量搜索之前应用。 如果要对元数据中的某个字段进行过滤,需要使用 . 进行指定。 例如,要获取元数据中的 source 字段,需要指定 metadata.source 请注意,过滤器必须受搜索索引支持。
from couchbase import search

query = "Are there any concerning financial news?"
filter_on_source = search.MatchQuery("news", field="metadata.source")
results = vector_store.similarity_search_with_score(
    query, fields=["metadata.source"], filter=filter_on_source, k=5
)
for res, score in results:
    print(f"* {res.page_content} [{res.metadata}] {score}")
* The stock market is down 500 points today due to fears of a recession. [{'source': 'news'}] 0.38733142614364624
* Robbers broke into the city bank and stole $1 million in cash. [{'source': 'news'}] 0.20637883245944977
* The weather forecast for tomorrow is cloudy and overcast, with a high of 62 degrees. [{'source': 'news'}] 0.10403035581111908

指定返回的字段

可以使用搜索中的 fields 参数指定从文档返回的字段。这些字段作为返回文档的 metadata 对象的一部分返回。您可以获取存储在搜索索引中的任何字段。文档的 text_key 作为文档的 page_content 返回。 如果不指定任何要获取的字段,则返回索引中存储的所有字段。 如果要获取元数据中的某个字段,需要使用 . 进行指定。 例如,要获取元数据中的 source 字段,需要指定 metadata.source
query = "What did I eat for breakfast today?"
results = vector_store.similarity_search(query, fields=["metadata.source"])
print(results[0])
page_content='I had chocolate chip pancakes and scrambled eggs for breakfast this morning.' metadata={'source': 'tweet'}

转换为检索器进行查询

您还可以将向量存储转换为检索器,以便在链中更方便地使用。 以下是将向量存储转换为检索器,然后使用简单查询和过滤器调用检索器的方法:
retriever = vector_store.as_retriever(
    search_type="similarity",
    search_kwargs={"k": 1, "score_threshold": 0.5},
)
filter_on_source = search.MatchQuery("news", field="metadata.source")
retriever.invoke("Stealing from the bank is a crime", filter=filter_on_source)
[Document(id='b480c9c6-b7df-4a22-ac2e-19287af7562d', metadata={'source': 'news'}, page_content='Robbers broke into the city bank and stole $1 million in cash.')]

混合查询

Couchbase 支持将向量搜索结果与文档非向量字段(如 metadata 对象)上的搜索相结合,进行混合搜索。 结果将基于向量搜索和搜索服务支持的搜索的综合结果。每个组件搜索的分数相加,得到结果的总分。 执行混合搜索时,所有相似度搜索方法都有一个可选参数 search_optionssearch_options 的不同搜索/查询可能性可以在这里找到。 为混合搜索创建多样化元数据 为了演示混合搜索,我们创建带有多样化元数据的文档。我们向元数据添加三个字段:date(2010 至 2020 年之间)、rating(1 至 5 之间)和 author(设置为 John Doe 或 Jane Doe)。
from langchain_core.documents import Document

# 创建带有多样化元数据的文档用于混合搜索示例
hybrid_docs = [
    Document(
        page_content="The new AI model shows impressive performance on benchmark tests.",
        metadata={"source": "tech", "date": "2019-01-01", "rating": 5, "author": "John Doe"},
    ),
    Document(
        page_content="Stock markets showed mixed results today with tech sector leading gains.",
        metadata={"source": "finance", "date": "2017-01-01", "rating": 3, "author": "Jane Doe"},
    ),
    Document(
        page_content="The annual developer conference announced new framework updates.",
        metadata={"source": "tech", "date": "2018-01-01", "rating": 4, "author": "John Doe"},
    ),
    Document(
        page_content="Weather patterns indicate a mild winter ahead for the region.",
        metadata={"source": "weather", "date": "2016-01-01", "rating": 2, "author": "Jane Doe"},
    ),
    Document(
        page_content="The new smartphone release features advanced camera technology.",
        metadata={"source": "tech", "date": "2020-01-01", "rating": 4, "author": "John Doe"},
    ),
    Document(
        page_content="Economic indicators suggest steady growth in the coming quarter.",
        metadata={"source": "finance", "date": "2017-01-01", "rating": 3, "author": "Jane Doe"},
    ),
]

vector_store.add_documents(hybrid_docs)

query = "Tell me about technology news"
results = vector_store.similarity_search(query)
print(results[0].metadata)
{'author': 'John Doe', 'date': '2020-01-01', 'rating': 4, 'source': 'tech'}
按精确值查询 可以搜索文本字段的精确匹配,例如 metadata 对象中的作者字段。
query = "What are the latest technology updates?"
results = vector_store.similarity_search(
    query,
    search_options={"query": {"field": "metadata.author", "match": "John Doe"}},
    fields=["metadata.author"],
)
print(results[0])
page_content='The new smartphone release features advanced camera technology.' metadata={'author': 'John Doe'}
按模糊匹配查询 可以通过指定模糊度来搜索部分匹配。当您想搜索搜索词的细微变体或拼写错误时,这非常有用。 这里,“Jae” 与 “Jane” 接近(模糊度为 1)。
query = "What are the financial market updates?"
results = vector_store.similarity_search(
    query,
    search_options={
        "query": {"field": "metadata.author", "match": "Jae", "fuzziness": 1}
    },
    fields=["metadata.author"],
)
print(results[0])
page_content='Stock markets showed mixed results today with tech sector leading gains.' metadata={'author': 'Jane Doe'}
按日期范围查询 可以搜索日期字段(如 metadata.date)在某个日期范围内的文档。
query = "What happened in the markets?"
results = vector_store.similarity_search(
    query,
    search_options={
        "query": {
            "start": "2016-12-31",
            "end": "2018-01-02",
            "inclusive_start": True,
            "inclusive_end": False,
            "field": "metadata.date",
        }
    },
)
print(results[0])
page_content='Stock markets showed mixed results today with tech sector leading gains.' metadata={'author': 'Jane Doe', 'date': '2017-01-01', 'rating': 3, 'source': 'finance'}
按数值范围查询 可以搜索数值字段(如 metadata.rating)在某个范围内的文档。
query = "What are the economic indicators for the coming quarter?"
results = vector_store.similarity_search_with_score(
    query,
    search_options={
        "query": {
            "min": 4,
            "max": 5,
            "inclusive_min": True,
            "inclusive_max": True,
            "field": "metadata.rating",
        }
    },
)
print(results[0])
(Document(id='6aeb8413bce340bc893f175cefbb64b3', metadata={'author': 'Jane Doe', 'date': '2017-01-01', 'rating': 3, 'source': 'finance'}, page_content='Economic indicators suggest steady growth in the coming quarter.'), 0.7944117188453674)
组合多个搜索查询 可以使用 AND(conjuncts)或 OR(disjuncts)运算符组合不同的搜索查询。 以下示例检查 rating 在 3 至 4 之间且日期在 2017 年的文档。
query = "Tell me about finance"
results = vector_store.similarity_search_with_score(
    query,
    search_options={
        "query": {
            "conjuncts": [
                {"min": 3, "max": 4, "inclusive_max": True, "field": "metadata.rating"},
                {"start": "2016-12-31", "end": "2018-01-01", "field": "metadata.date"},
            ]
        }
    },
)
print(results[0])
(Document(id='0c9af73370c1483caddf9941440edb50', metadata={'author': 'Jane Doe', 'date': '2017-01-01', 'rating': 3, 'source': 'finance'}, page_content='Stock markets showed mixed results today with tech sector leading gains.'), 0.7275013146103568)
注意 混合搜索结果可能包含不满足所有搜索参数的文档。这是由分数计算方式决定的。 分数是向量搜索分数与混合搜索中查询分数的总和。如果向量搜索分数很高,综合分数将高于满足混合搜索所有查询条件的结果。 为避免此类结果,请使用 filter 参数而非混合搜索。 将混合搜索查询与过滤器结合使用 混合搜索可以与过滤器结合使用,兼顾混合搜索和过滤器的优势,以获取满足条件的结果。 以下示例检查 rating 在 3 至 5 之间且文本字段匹配 “market” 的文档。
filter_text = search.MatchQuery("market", field="text")

query = "Tell me about market updates"
results = vector_store.similarity_search_with_score(
    query,
    search_options={
        "query": {
            "min": 3,
            "max": 5,
            "inclusive_min": True,
            "inclusive_max": True,
            "field": "metadata.rating",
        }
    },
    filter=filter_text,
)

print(results[0])
(Document(id='0c9af73370c1483caddf9941440edb50', metadata={'author': 'Jane Doe', 'date': '2017-01-01', 'rating': 3, 'source': 'finance'}, page_content='Stock markets showed mixed results today with tech sector leading gains.'), 0.4503188681265006)
其他查询 类似地,您可以在 search_options 参数中使用任何受支持的查询方法,如地理距离、多边形搜索、通配符、正则表达式等。有关可用查询方法及其语法的更多详细信息,请参阅文档。

用于检索增强生成

有关如何将这些向量存储用于检索增强生成(RAG)的指南,请参阅以下章节:

常见问题

问:是否需要在创建 CouchbaseSearchVectorStore 对象之前创建搜索索引?

是的,您需要在创建 CouchbaseSearchVectorStore 对象之前创建搜索索引。

问:应该在向 CouchbaseQueryVectorStore 添加文档之前还是之后创建索引?

对于 CouchbaseQueryVectorStore,您应该在添加文档之后使用 create_index() 方法创建索引。这与 CouchbaseSearchVectorStore 不同。

问:CouchbaseSearchVectorStore 和 CouchbaseQueryVectorStore 有什么区别?

特性CouchbaseSearchVectorStoreCouchbaseQueryVectorStore
最低版本要求Couchbase Server 7.6+Couchbase Server 8.0+
索引类型搜索向量索引超大规模或复合向量索引
索引创建时机创建向量存储之前添加文档之后
过滤方式SearchQuery 对象SQL++ WHERE 子句(where_str
最适用场景混合搜索(向量 + 全文搜索 + 地理)大规模纯向量搜索或向量 + 标量过滤

问:我没有看到搜索结果中包含我指定的所有字段

在 Couchbase 中,只能返回存储在搜索索引中的字段。请确保您要在搜索结果中访问的字段是搜索索引的一部分。 一种处理方式是在索引中动态索引和存储文档字段。
  • 在 Capella 中,进入”Advanced Mode”,在”General Settings”折叠区下可以勾选”[X] Store Dynamic Fields”或”[X] Index Dynamic Fields”
  • 在 Couchbase Server 中,在索引编辑器(非快速编辑器)的”Advanced”折叠区下可以勾选”[X] Store Dynamic Fields”或”[X] Index Dynamic Fields”
请注意,这些选项会增加索引的大小。 有关动态映射的更多详情,请参阅文档

问:我在搜索结果中看不到元数据对象

这很可能是因为文档中的 metadata 字段未被 Couchbase 搜索索引索引和/或存储。要在文档中索引 metadata 字段,需要将其作为子映射添加到索引中。 如果选择映射所有字段,您将能够按所有元数据字段进行搜索。或者,为了优化索引,可以选择对 metadata 对象内的特定字段进行索引。可以参阅文档了解更多关于索引子映射的内容。 创建子映射:

问:filter 与 search_options / 混合查询有什么区别?

过滤器是预过滤器,用于限制在搜索索引中搜索的文档范围,适用于 Couchbase Server 7.6.4 及更高版本。 混合查询是可用于调整从搜索索引返回结果的附加搜索查询。 过滤器和混合搜索查询具有相同的功能,但语法略有不同。过滤器是 SearchQuery 对象,而混合搜索查询是字典

API 参考

有关所有功能和配置的详细文档: