langchain_community.vectorstores.baiduvectordb.BaiduVectorDB

class langchain_community.vectorstores.baiduvectordb.BaiduVectorDB(embedding: ~langchain_core.embeddings.embeddings.Embeddings, connection_params: ~langchain_community.vectorstores.baiduvectordb.ConnectionParams, table_params: ~langchain_community.vectorstores.baiduvectordb.TableParams = <langchain_community.vectorstores.baiduvectordb.TableParams object>, database_name: str = 'LangChainDatabase', table_name: str = 'LangChainTable', drop_old: ~typing.Optional[bool] = False)[source]

Baidu VectorDB as a vector store.

In order to use this you need to have a database instance. See the following documentation for details: https://cloud.baidu.com/doc/VDB/index.html

Attributes

embeddings

Access the query embedding object if available.

field_id

field_metadata

field_text

field_vector

index_vector

Methods

__init__(embedding, connection_params[, ...])

aadd_documents(documents, **kwargs)

Async run more documents through the embeddings and add to the vectorstore.

aadd_texts(texts[, metadatas])

Async run more texts through the embeddings and add to the vectorstore.

add_documents(documents, **kwargs)

Add or update documents in the vectorstore.

add_texts(texts[, metadatas, batch_size])

Insert text data into Baidu VectorDB.

adelete([ids])

Async delete by vector ID or other criteria.

afrom_documents(documents, embedding, **kwargs)

Async return VectorStore initialized from documents and embeddings.

afrom_texts(texts, embedding[, metadatas])

Async return VectorStore initialized from texts and embeddings.

aget_by_ids(ids, /)

Async get documents by their IDs.

amax_marginal_relevance_search(query[, k, ...])

Async return docs selected using the maximal marginal relevance.

amax_marginal_relevance_search_by_vector(...)

Async return docs selected using the maximal marginal relevance.

as_retriever(**kwargs)

Return VectorStoreRetriever initialized from this VectorStore.

asearch(query, search_type, **kwargs)

Async return docs most similar to query using a specified search type.

asimilarity_search(query[, k])

Async return docs most similar to query.

asimilarity_search_by_vector(embedding[, k])

Async return docs most similar to embedding vector.

asimilarity_search_with_relevance_scores(query)

Async return docs and relevance scores in the range [0, 1].

asimilarity_search_with_score(*args, **kwargs)

Async run similarity search with distance.

astreaming_upsert(items, /, batch_size, **kwargs)

aupsert(items, /, **kwargs)

delete([ids])

Delete by vector ID or other criteria.

from_documents(documents, embedding, **kwargs)

Return VectorStore initialized from documents and embeddings.

from_texts(texts, embedding[, metadatas, ...])

Create a table, indexes it with HNSW, and insert data.

get_by_ids(ids, /)

Get documents by their IDs.

max_marginal_relevance_search(query[, k, ...])

Perform a search and return results that are reordered by MMR.

max_marginal_relevance_search_by_vector(...)

Return docs selected using the maximal marginal relevance.

search(query, search_type, **kwargs)

Return docs most similar to query using a specified search type.

similarity_search(query[, k, param, expr])

Perform a similarity search against the query string.

similarity_search_by_vector(embedding[, k, ...])

Perform a similarity search against the query string.

similarity_search_with_relevance_scores(query)

Return docs and relevance scores in the range [0, 1].

similarity_search_with_score(query[, k, ...])

Perform a search on a query string and return results with score.

streaming_upsert(items, /, batch_size, **kwargs)

upsert(items, /, **kwargs)

Parameters
__init__(embedding: ~langchain_core.embeddings.embeddings.Embeddings, connection_params: ~langchain_community.vectorstores.baiduvectordb.ConnectionParams, table_params: ~langchain_community.vectorstores.baiduvectordb.TableParams = <langchain_community.vectorstores.baiduvectordb.TableParams object>, database_name: str = 'LangChainDatabase', table_name: str = 'LangChainTable', drop_old: ~typing.Optional[bool] = False)[source]
Parameters
async aadd_documents(documents: List[Document], **kwargs: Any) List[str]

Async run more documents through the embeddings and add to the vectorstore.

Parameters
  • documents (List[Document]) – Documents to add to the vectorstore.

  • kwargs (Any) – Additional keyword arguments.

Returns

List of IDs of the added texts.

Raises

ValueError – If the number of IDs does not match the number of documents.

Return type

List[str]

async aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) List[str]

Async run more texts through the embeddings and add to the vectorstore.

Parameters
  • texts (Iterable[str]) – Iterable of strings to add to the vectorstore.

  • metadatas (Optional[List[dict]]) – Optional list of metadatas associated with the texts. Default is None.

  • **kwargs (Any) – vectorstore specific parameters.

Returns

List of ids from adding the texts into the vectorstore.

Raises
  • ValueError – If the number of metadatas does not match the number of texts.

  • ValueError – If the number of ids does not match the number of texts.

Return type

List[str]

add_documents(documents: List[Document], **kwargs: Any) List[str]

Add or update documents in the vectorstore.

Parameters
  • documents (List[Document]) – Documents to add to the vectorstore.

  • kwargs (Any) – Additional keyword arguments. if kwargs contains ids and documents contain ids, the ids in the kwargs will receive precedence.

Returns

List of IDs of the added texts.

Raises

ValueError – If the number of ids does not match the number of documents.

Return type

List[str]

add_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, batch_size: int = 1000, **kwargs: Any) List[str][source]

Insert text data into Baidu VectorDB.

Parameters
  • texts (Iterable[str]) –

  • metadatas (Optional[List[dict]]) –

  • batch_size (int) –

  • kwargs (Any) –

Return type

List[str]

async adelete(ids: Optional[List[str]] = None, **kwargs: Any) Optional[bool]

Async delete by vector ID or other criteria.

Parameters
  • ids (Optional[List[str]]) – List of ids to delete. If None, delete all. Default is None.

  • **kwargs (Any) – Other keyword arguments that subclasses might use.

Returns

True if deletion is successful, False otherwise, None if not implemented.

Return type

Optional[bool]

async classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) VST

Async return VectorStore initialized from documents and embeddings.

Parameters
  • documents (List[Document]) – List of Documents to add to the vectorstore.

  • embedding (Embeddings) – Embedding function to use.

  • kwargs (Any) – Additional keyword arguments.

Returns

VectorStore initialized from documents and embeddings.

Return type

VectorStore

async classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) VST

Async return VectorStore initialized from texts and embeddings.

Parameters
  • texts (List[str]) – Texts to add to the vectorstore.

  • embedding (Embeddings) – Embedding function to use.

  • metadatas (Optional[List[dict]]) – Optional list of metadatas associated with the texts. Default is None.

  • kwargs (Any) – Additional keyword arguments.

Returns

VectorStore initialized from texts and embeddings.

Return type

VectorStore

async aget_by_ids(ids: Sequence[str], /) List[Document]

Async get documents by their IDs.

The returned documents are expected to have the ID field set to the ID of the document in the vector store.

Fewer documents may be returned than requested if some IDs are not found or if there are duplicated IDs.

Users should not assume that the order of the returned documents matches the order of the input IDs. Instead, users should rely on the ID field of the returned documents.

This method should NOT raise exceptions if no documents are found for some IDs.

Parameters

ids (Sequence[str]) – List of ids to retrieve.

Returns

List of Documents.

Return type

List[Document]

New in version 0.2.11.

Async return docs selected using the maximal marginal relevance.

最大边际相关性 (MMR) 优化查询的相似性和所选文档之间的多样性。

Parameters
  • query (str) – 用于查找相似文档的文本。

  • k (int) – 返回的文档数量。默认为 4。

  • fetch_k (int) – 获取用于传递给 MMR 算法的文档数量。默认为 20。

  • lambda_mult (float) – 介于 0 和 1 之间的数字,用于确定结果之间多样性的程度,0 对应于最大多样性,1 对应于最小多样性。默认为 0.5。

  • kwargs (Any) –

Returns

由最大边际相关性 (MMR) 选择的文档列表。

Return type

List[Document]

async amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) List[Document]

Async return docs selected using the maximal marginal relevance.

最大边际相关性 (MMR) 优化查询的相似性和所选文档之间的多样性。

Parameters
  • embedding (List[float]) – 用于查找相似文档的嵌入向量。

  • k (int) – 返回的文档数量。默认为 4。

  • fetch_k (int) – 获取用于传递给 MMR 算法的文档数量。默认为 20。

  • lambda_mult (float) – 介于 0 和 1 之间的数字,用于确定结果之间多样性的程度,0 对应于最大多样性,1 对应于最小多样性。默认为 0.5。

  • **kwargs (Any) – 传递给搜索方法的参数。

Returns

由最大边际相关性 (MMR) 选择的文档列表。

Return type

List[Document]

as_retriever(**kwargs: Any) VectorStoreRetriever

Return VectorStoreRetriever initialized from this VectorStore.

Parameters

**kwargs (Any) –

传递给搜索函数的关键字参数。可以包括: search_type (Optional[str]): 定义 Retriever 应执行的搜索类型。

可以是 “similarity”(默认),“mmr” 或 “similarity_score_threshold”。

search_kwargs (Optional[Dict]): 传递给搜索函数的关键字参数。
可以包括诸如:

k: 返回的文档数量 (默认: 4) score_threshold: 相似度分数阈值的最小相关性阈值

用于 similarity_score_threshold

fetch_k: 传递给 MMR 算法的文档数量 (默认: 20)

(默认: 20)

lambda_mult: MMR 返回结果的多样性;

1 表示最小多样性,0 表示最大多样性。(默认:0.5)

filter: 按文档元数据过滤

Returns

VectorStore 的 Retriever 类。

Return type

VectorStoreRetriever

示例

# Retrieve more documents with higher diversity
# Useful if your dataset has many similar documents
docsearch.as_retriever(
    search_type="mmr",
    search_kwargs={'k': 6, 'lambda_mult': 0.25}
)

# Fetch more documents for the MMR algorithm to consider
# But only return the top 5
docsearch.as_retriever(
    search_type="mmr",
    search_kwargs={'k': 5, 'fetch_k': 50}
)

# Only retrieve documents that have a relevance score
# Above a certain threshold
docsearch.as_retriever(
    search_type="similarity_score_threshold",
    search_kwargs={'score_threshold': 0.8}
)

# Only get the single most similar document from the dataset
docsearch.as_retriever(search_kwargs={'k': 1})

# Use a filter to only retrieve documents from a specific paper
docsearch.as_retriever(
    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}
)
async asearch(query: str, search_type: str, **kwargs: Any) List[Document]

Async return docs most similar to query using a specified search type.

Parameters
  • query (str) – 输入文本。

  • search_type (str) – 要执行的搜索类型。可以是 “similarity”, “mmr”, 或 “similarity_score_threshold”。

  • **kwargs (Any) – 传递给搜索方法的参数。

Returns

与查询最相似的文档列表。

Raises

ValueError – 如果 search_type 不是 “similarity”, “mmr”, 或 “similarity_score_threshold” 之一。

Return type

List[Document]

Async return docs most similar to query.

Parameters
  • query (str) – 输入文本。

  • k (int) – 返回的文档数量。默认为 4。

  • **kwargs (Any) – 传递给搜索方法的参数。

Returns

与查询最相似的文档列表。

Return type

List[Document]

async asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) List[Document]

Async return docs most similar to embedding vector.

Parameters
  • embedding (List[float]) – 用于查找相似文档的嵌入向量。

  • k (int) – 返回的文档数量。默认为 4。

  • **kwargs (Any) – 传递给搜索方法的参数。

Returns

与查询向量最相似的文档列表。

Return type

List[Document]

async asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) List[Tuple[Document, float]]

Async return docs and relevance scores in the range [0, 1].

0 表示不相似,1 表示最相似。

Parameters
  • query (str) – 输入文本。

  • k (int) – 返回的文档数量。默认为 4。

  • **kwargs (Any) –

    要传递给相似性搜索的 kwargs。应包括: score_threshold: 可选参数,介于 0 到 1 之间的浮点值,用于

    过滤检索到的文档结果集

Returns

元组 (doc, similarity_score) 的列表

Return type

List[Tuple[Document, float]]

async asimilarity_search_with_score(*args: Any, **kwargs: Any) List[Tuple[Document, float]]

Async run similarity search with distance.

Parameters
  • *args (Any) – 传递给搜索方法的参数。

  • **kwargs (Any) – 传递给搜索方法的参数。

Returns

元组 (doc, similarity_score) 的列表。

Return type

List[Tuple[Document, float]]

astreaming_upsert(items: AsyncIterable[Document], /, batch_size: int, **kwargs: Any) AsyncIterator[UpsertResponse]

Beta

添加于 0.2.11。API 可能会发生变化。

以流式方式 Upsert 文档。streaming_upsert 的异步版本。

Parameters
  • items (AsyncIterable[Document]) – 要添加到向量存储的文档的可迭代对象。

  • batch_size (int) – 每次 upsert 的批量大小。

  • kwargs (Any) – 附加关键字参数。kwargs 应仅包含所有文档通用的参数。(例如,索引超时,重试策略等)kwargs 不应包含 ids 以避免语义模糊。相反,ID 应作为 Document 对象的一部分提供。

Yields

UpsertResponse – 响应对象,其中包含已成功添加到或更新到向量存储中的 ID 列表,以及未能添加或更新的 ID 列表。

Return type

AsyncIterator[UpsertResponse]

New in version 0.2.11.

async aupsert(items: Sequence[Document], /, **kwargs: Any) UpsertResponse

Beta

添加于 0.2.11。API 可能会发生变化。

在向量存储中添加或更新文档。upsert 的异步版本。

如果提供了 Document 对象的 ID 字段,则 upsert 功能应使用该字段。如果未提供 ID,则 upsert 方法可以自由地为文档生成 ID。

当指定了 ID 并且文档已存在于向量存储中时,upsert 方法应使用新数据更新文档。如果文档不存在,则 upsert 方法应将文档添加到向量存储中。

Parameters
  • items (Sequence[Document]) – 要添加到向量存储的文档序列。

  • kwargs (Any) – Additional keyword arguments.

Returns

响应对象,其中包含已成功添加到或更新到向量存储中的 ID 列表,以及未能添加或更新的 ID 列表。

Return type

UpsertResponse

New in version 0.2.11.

delete(ids: Optional[List[str]] = None, **kwargs: Any) Optional[bool]

Delete by vector ID or other criteria.

Parameters
  • ids (Optional[List[str]]) – List of ids to delete. If None, delete all. Default is None.

  • **kwargs (Any) – Other keyword arguments that subclasses might use.

Returns

True if deletion is successful, False otherwise, None if not implemented.

Return type

Optional[bool]

classmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) VST

Return VectorStore initialized from documents and embeddings.

Parameters
  • documents (List[Document]) – List of Documents to add to the vectorstore.

  • embedding (Embeddings) – Embedding function to use.

  • kwargs (Any) – Additional keyword arguments.

Returns

VectorStore initialized from documents and embeddings.

Return type

VectorStore

classmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, connection_params: Optional[ConnectionParams] = None, table_params: Optional[TableParams] = None, database_name: str = 'LangChainDatabase', table_name: str = 'LangChainTable', drop_old: Optional[bool] = False, **kwargs: Any) BaiduVectorDB[source]

Create a table, indexes it with HNSW, and insert data.

Parameters
  • texts (List[str]) –

  • embedding (Embeddings) –

  • metadatas (Optional[List[dict]]) –

  • connection_params (Optional[ConnectionParams]) –

  • table_params (Optional[TableParams]) –

  • database_name (str) –

  • table_name (str) –

  • drop_old (Optional[bool]) –

  • kwargs (Any) –

Return type

BaiduVectorDB

get_by_ids(ids: Sequence[str], /) List[Document]

Get documents by their IDs.

The returned documents are expected to have the ID field set to the ID of the document in the vector store.

Fewer documents may be returned than requested if some IDs are not found or if there are duplicated IDs.

Users should not assume that the order of the returned documents matches the order of the input IDs. Instead, users should rely on the ID field of the returned documents.

This method should NOT raise exceptions if no documents are found for some IDs.

Parameters

ids (Sequence[str]) – List of ids to retrieve.

Returns

List of Documents.

Return type

List[Document]

New in version 0.2.11.

Perform a search and return results that are reordered by MMR.

Parameters
  • query (str) –

  • k (int) –

  • fetch_k (int) –

  • lambda_mult (float) –

  • param (Optional[dict]) –

  • expr (Optional[str]) –

  • kwargs (Any) –

Return type

List[Document]

max_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) List[Document]

Return docs selected using the maximal marginal relevance.

最大边际相关性 (MMR) 优化查询的相似性和所选文档之间的多样性。

Parameters
  • embedding (List[float]) – 用于查找相似文档的嵌入向量。

  • k (int) – 返回的文档数量。默认为 4。

  • fetch_k (int) – 获取用于传递给 MMR 算法的文档数量。默认为 20。

  • lambda_mult (float) – 介于 0 和 1 之间的数字,用于确定结果之间多样性的程度,0 对应于最大多样性,1 对应于最小多样性。默认为 0.5。

  • **kwargs (Any) – 传递给搜索方法的参数。

Returns

由最大边际相关性 (MMR) 选择的文档列表。

Return type

List[Document]

search(query: str, search_type: str, **kwargs: Any) List[Document]

Return docs most similar to query using a specified search type.

Parameters
  • query (str) – 输入文本

  • search_type (str) – 要执行的搜索类型。可以是 “similarity”, “mmr”, 或 “similarity_score_threshold”。

  • **kwargs (Any) – 传递给搜索方法的参数。

Returns

与查询最相似的文档列表。

Raises

ValueError – 如果 search_type 不是 “similarity”, “mmr”, 或 “similarity_score_threshold” 之一。

Return type

List[Document]

Perform a similarity search against the query string.

Parameters
  • query (str) –

  • k (int) –

  • param (Optional[dict]) –

  • expr (Optional[str]) –

  • kwargs (Any) –

Return type

List[Document]

similarity_search_by_vector(embedding: List[float], k: int = 4, param: Optional[dict] = None, expr: Optional[str] = None, **kwargs: Any) List[Document][source]

Perform a similarity search against the query string.

Parameters
  • embedding (List[float]) – 嵌入向量 (List[float])

  • k (int) –

  • param (Optional[dict]) –

  • expr (Optional[str]) –

  • kwargs (Any) –

Return type

List[Document]

similarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) List[Tuple[Document, float]]

Return docs and relevance scores in the range [0, 1].

0 表示不相似,1 表示最相似。

Parameters
  • query (str) – 输入文本。

  • k (int) – 返回的文档数量。默认为 4。

  • **kwargs (Any) –

    要传递给相似性搜索的 kwargs。应包括: score_threshold: 可选参数,介于 0 到 1 之间的浮点值,用于

    filter the resulting set of retrieved docs.

Returns

元组 (doc, similarity_score) 的列表。

Return type

List[Tuple[Document, float]]

similarity_search_with_score(query: str, k: int = 4, param: Optional[dict] = None, expr: Optional[str] = None, **kwargs: Any) List[Tuple[Document, float]][source]

Perform a search on a query string and return results with score.

Parameters
  • query (str) –

  • k (int) –

  • param (Optional[dict]) –

  • expr (Optional[str]) –

  • kwargs (Any) –

Return type

List[Tuple[Document, float]]

streaming_upsert(items: Iterable[Document], /, batch_size: int, **kwargs: Any) Iterator[UpsertResponse]

Beta

添加于 0.2.11。API 可能会发生变化。

以流式方式 Upsert 文档。

Parameters
  • items (Iterable[Document]) – 要添加到向量存储的可迭代文档 (Iterable of Documents to add to the vectorstore)。

  • batch_size (int) – 每次 upsert 的批量大小。

  • kwargs (Any) – 附加的关键字参数。kwargs 应该只包含所有文档通用的参数。(例如,索引超时、重试策略等)kwargs 不应包含 ids 以避免语义模糊。相反,ID 应该作为 Document 对象的一部分提供。

Yields

UpsertResponse – 响应对象,其中包含已成功添加到或更新到向量存储中的 ID 列表,以及未能添加或更新的 ID 列表。

Return type

Iterator[UpsertResponse]

New in version 0.2.11.

upsert(items: Sequence[Document], /, **kwargs: Any) UpsertResponse

Beta

添加于 0.2.11。API 可能会发生变化。

Add or update documents in the vectorstore.

如果提供了 Document 对象的 ID 字段,则 upsert 功能应使用该字段。如果未提供 ID,则 upsert 方法可以自由地为文档生成 ID。

当指定了 ID 并且文档已存在于向量存储中时,upsert 方法应使用新数据更新文档。如果文档不存在,则 upsert 方法应将文档添加到向量存储中。

Parameters
  • items (Sequence[Document]) – 要添加到向量存储的文档序列。

  • kwargs (Any) – Additional keyword arguments.

Returns

响应对象,其中包含已成功添加到或更新到向量存储中的 ID 列表,以及未能添加或更新的 ID 列表。

Return type

UpsertResponse

New in version 0.2.11.

BaiduVectorDB 的使用示例