langchain_community.vectorstores.cassandra
.Cassandra¶
- class langchain_community.vectorstores.cassandra.Cassandra(embedding: Embeddings, session: Optional[Session] = None, keyspace: Optional[str] = None, table_name: str = '', ttl_seconds: Optional[int] = None, *, body_index_options: Optional[List[Tuple[str, Any]]] = None, setup_mode: SetupMode = SetupMode.SYNC, metadata_indexing: Union[Tuple[str, Iterable[str]], str] = 'all')[source]¶
Apache Cassandra(R) for vector-store workloads.
To use it, you need a recent installation of the cassio library and a Cassandra cluster / Astra DB instance supporting vector capabilities.
Visit the cassio.org website for extensive quickstarts and code examples.
Example
from langchain_community.vectorstores import Cassandra from langchain_openai import OpenAIEmbeddings embeddings = OpenAIEmbeddings() session = ... # create your Cassandra session object keyspace = 'my_keyspace' # the keyspace should exist already table_name = 'my_vector_store' vectorstore = Cassandra(embeddings, session, keyspace, table_name)
- Parameters
embedding (Embeddings) – Embedding function to use.
session (Optional[Session]) – Cassandra driver session. If not provided, it is resolved from cassio.
keyspace (Optional[str]) – Cassandra keyspace. If not provided, it is resolved from cassio.
table_name (str) – Cassandra table (required).
ttl_seconds (Optional[int]) – Optional time-to-live for the added texts.
body_index_options (Optional[List[Tuple[str, Any]]]) – Optional options used to create the body index. Eg. body_index_options = [cassio.table.cql.STANDARD_ANALYZER]
setup_mode (SetupMode) – mode used to create the Cassandra table (SYNC, ASYNC or OFF).
metadata_indexing (Union[Tuple[str, Iterable[str]], str]) –
Optional specification of a metadata indexing policy, i.e. to fine-tune which of the metadata fields are indexed. It can be a string (“all” or “none”), or a 2-tuple. The following means that all fields except ‘f1’, ‘f2’ … are NOT indexed
metadata_indexing=(“allowlist”, [“f1”, “f2”, …])
- The following means all fields EXCEPT ‘g1’, ‘g2’, … are indexed
metadata_indexing(“denylist”, [“g1”, “g2”, …])
The default is to index every metadata field. Note: if you plan to have massive unique text metadata entries, consider not indexing them for performance (and to overcome max-length limitations).
Attributes
embeddings
Access the query embedding object if available.
Methods
__init__
(embedding[, session, keyspace, ...])Apache Cassandra(R) for vector-store workloads.
aadd_documents
(documents, **kwargs)Async run more documents through the embeddings and add to the vectorstore.
aadd_texts
(texts[, metadatas, ids, ...])Run more texts through the embeddings and add to the vectorstore.
aclear
()Empty the table.
add_documents
(documents, **kwargs)Add or update documents in the vectorstore.
add_texts
(texts[, metadatas, ids, ...])Run more texts through the embeddings and add to the vectorstore.
adelete
([ids])Delete by vector IDs.
adelete_by_document_id
(document_id)Delete by document ID.
Just an alias for aclear (to better align with other VectorStore implementations).
afrom_documents
(documents, embedding, *[, ...])Create a Cassandra vectorstore from a document list.
afrom_texts
(texts, embedding[, metadatas, ...])Create a Cassandra vectorstore from raw texts.
aget_by_ids
(ids, /)Async get documents by their IDs.
amax_marginal_relevance_search
(query[, k, ...])Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. :param query: Text to look up documents similar to. :param k: Number of Documents to return. :param fetch_k: Number of Documents to fetch to pass to MMR algorithm. :param lambda_mult: Number between 0 and 1 that determines the degree of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. Defaults to 0.5. :param filter: Filter on the metadata to apply. :param body_search: Document textual search terms to apply. Only supported by Astra DB at the moment.
Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. :param embedding: Embedding to look up documents similar to. :param k: Number of Documents to return. Defaults to 4. :param fetch_k: Number of Documents to fetch to pass to MMR algorithm. Defaults to 20. :param lambda_mult: Number between 0 and 1 that determines the degree of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. Defaults to 0.5. :param filter: Filter on the metadata to apply. :param body_search: Document textual search terms to apply. Only supported by Astra DB at the moment.
as_retriever
([search_type, search_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, filter, ...])Return docs most similar to query.
asimilarity_search_by_vector
(embedding[, k, ...])Return docs most similar to embedding vector.
Async return docs and relevance scores in the range [0, 1].
asimilarity_search_with_score
(query[, k, ...])Return docs most similar to query.
Return docs most similar to embedding vector.
asimilarity_search_with_score_id
(query[, k, ...])Return docs most similar to query.
Return docs most similar to embedding vector.
astreaming_upsert
(items, /, batch_size, **kwargs)aupsert
(items, /, **kwargs)clear
()Empty the table.
delete
([ids])Delete by vector IDs.
delete_by_document_id
(document_id)Delete by document ID.
Just an alias for clear (to better align with other VectorStore implementations).
from_documents
(documents, embedding, *[, ...])Create a Cassandra vectorstore from a document list.
from_texts
(texts, embedding[, metadatas, ...])Create a Cassandra vectorstore from raw texts.
get_by_ids
(ids, /)Get documents by their IDs.
max_marginal_relevance_search
(query[, k, ...])Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. :param query: Text to look up documents similar to. :param k: Number of Documents to return. Defaults to 4. :param fetch_k: Number of Documents to fetch to pass to MMR algorithm. Defaults to 20. :param lambda_mult: Number between 0 and 1 that determines the degree of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. Defaults to 0.5. :param filter: Filter on the metadata to apply. :param body_search: Document textual search terms to apply. Only supported by Astra DB at the moment.
Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. :param embedding: Embedding to look up documents similar to. :param k: Number of Documents to return. Defaults to 4. :param fetch_k: Number of Documents to fetch to pass to MMR algorithm. Defaults to 20. :param lambda_mult: Number between 0 and 1 that determines the degree of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. Defaults to 0.5. :param filter: Filter on the metadata to apply. :param body_search: Document textual search terms to apply. Only supported by Astra DB at the moment.
search
(query, search_type, **kwargs)Return docs most similar to query using a specified search type.
similarity_search
(query[, k, filter, ...])Return docs most similar to query.
similarity_search_by_vector
(embedding[, k, ...])Return docs most similar to embedding vector.
Return docs and relevance scores in the range [0, 1].
similarity_search_with_score
(query[, k, ...])Return docs most similar to query.
similarity_search_with_score_by_vector
(embedding)Return docs most similar to embedding vector.
similarity_search_with_score_id
(query[, k, ...])Return docs most similar to query.
Return docs most similar to embedding vector.
streaming_upsert
(items, /, batch_size, **kwargs)upsert
(items, /, **kwargs)- __init__(embedding: Embeddings, session: Optional[Session] = None, keyspace: Optional[str] = None, table_name: str = '', ttl_seconds: Optional[int] = None, *, body_index_options: Optional[List[Tuple[str, Any]]] = None, setup_mode: SetupMode = SetupMode.SYNC, metadata_indexing: Union[Tuple[str, Iterable[str]], str] = 'all') None [source]¶
Apache Cassandra(R) for vector-store workloads.
To use it, you need a recent installation of the cassio library and a Cassandra cluster / Astra DB instance supporting vector capabilities.
Visit the cassio.org website for extensive quickstarts and code examples.
Example
from langchain_community.vectorstores import Cassandra from langchain_openai import OpenAIEmbeddings embeddings = OpenAIEmbeddings() session = ... # create your Cassandra session object keyspace = 'my_keyspace' # the keyspace should exist already table_name = 'my_vector_store' vectorstore = Cassandra(embeddings, session, keyspace, table_name)
- Parameters
embedding (Embeddings) – Embedding function to use.
session (Optional[Session]) – Cassandra driver session. If not provided, it is resolved from cassio.
keyspace (Optional[str]) – Cassandra keyspace. If not provided, it is resolved from cassio.
table_name (str) – Cassandra table (required).
ttl_seconds (Optional[int]) – Optional time-to-live for the added texts.
body_index_options (Optional[List[Tuple[str, Any]]]) – Optional options used to create the body index. Eg. body_index_options = [cassio.table.cql.STANDARD_ANALYZER]
setup_mode (SetupMode) – mode used to create the Cassandra table (SYNC, ASYNC or OFF).
metadata_indexing (Union[Tuple[str, Iterable[str]], str]) –
Optional specification of a metadata indexing policy, i.e. to fine-tune which of the metadata fields are indexed. It can be a string (“all” or “none”), or a 2-tuple. The following means that all fields except ‘f1’, ‘f2’ … are NOT indexed
metadata_indexing=(“allowlist”, [“f1”, “f2”, …])
- The following means all fields EXCEPT ‘g1’, ‘g2’, … are indexed
metadata_indexing(“denylist”, [“g1”, “g2”, …])
The default is to index every metadata field. Note: if you plan to have massive unique text metadata entries, consider not indexing them for performance (and to overcome max-length limitations).
- Return type
None
- 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, ids: Optional[List[str]] = None, concurrency: int = 16, ttl_seconds: Optional[int] = None, **kwargs: Any) List[str] [source]¶
Run more texts through the embeddings and add to the vectorstore.
- Parameters
texts (Iterable[str]) – Texts to add to the vectorstore.
metadatas (Optional[List[dict]]) – Optional list of metadatas.
ids (Optional[List[str]]) – Optional list of IDs.
concurrency (int) – Number of concurrent queries to the database. Defaults to 16.
ttl_seconds (Optional[int]) – Optional time-to-live for the added texts.
kwargs (Any) –
- Returns
List of IDs of the added 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, ids: Optional[List[str]] = None, batch_size: int = 16, ttl_seconds: Optional[int] = None, **kwargs: Any) List[str] [source]¶
Run more texts through the embeddings and add to the vectorstore.
- Parameters
texts (Iterable[str]) – Texts to add to the vectorstore.
metadatas (Optional[List[dict]]) – Optional list of metadatas.
ids (Optional[List[str]]) – Optional list of IDs.
batch_size (int) – Number of concurrent requests to send to the server.
ttl_seconds (Optional[int]) – Optional time-to-live for the added texts.
kwargs (Any) –
- Returns
List of IDs of the added texts.
- Return type
List[str]
- async adelete(ids: Optional[List[str]] = None, **kwargs: Any) Optional[bool] [source]¶
Delete by vector IDs.
- Parameters
ids (Optional[List[str]]) – List of ids to delete.
kwargs (Any) –
- Returns
如果删除成功,则为 True;否则为 False;如果未实现,则为 None。
- Return type
Optional[bool]
- async adelete_by_document_id(document_id: str) None [source]¶
Delete by document ID.
- Parameters
document_id (str) – 要删除的文档 ID。
- Return type
None
- async adelete_collection() None [source]¶
Just an alias for aclear (to better align with other VectorStore implementations).
- Return type
None
- async classmethod afrom_documents(documents: List[Document], embedding: Embeddings, *, session: Optional[Session] = None, keyspace: Optional[str] = None, table_name: str = '', ids: Optional[List[str]] = None, concurrency: int = 16, ttl_seconds: Optional[int] = None, body_index_options: Optional[List[Tuple[str, Any]]] = None, metadata_indexing: Union[Tuple[str, Iterable[str]], str] = 'all', **kwargs: Any) CVST [source]¶
Create a Cassandra vectorstore from a document list.
- Parameters
documents (List[Document]) – Documents to add to the vectorstore.
embedding (Embeddings) – Embedding function to use.
session (Optional[Session]) – Cassandra driver session. If not provided, it is resolved from cassio.
keyspace (Optional[str]) – Cassandra 键空间。如果未提供,则从 cassio 解析。
table_name (str) – Cassandra table (required).
ids (Optional[List[str]]) – 与文档关联的可选 ID 列表。
concurrency (int) – 发送到数据库的并发查询数。默认为 16。
ttl_seconds (Optional[int]) – 添加文档的可选生存时间(TTL),单位为秒。
body_index_options (Optional[List[Tuple[str, Any]]]) – Optional options used to create the body index. Eg. body_index_options = [cassio.table.cql.STANDARD_ANALYZER]
metadata_indexing (Union[Tuple[str, Iterable[str]], str]) –
kwargs (Any) –
- Returns
一个 Cassandra 向量存储。
- Return type
CVST
- async classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, *, session: Optional[Session] = None, keyspace: Optional[str] = None, table_name: str = '', ids: Optional[List[str]] = None, concurrency: int = 16, ttl_seconds: Optional[int] = None, body_index_options: Optional[List[Tuple[str, Any]]] = None, metadata_indexing: Union[Tuple[str, Iterable[str]], str] = 'all', **kwargs: Any) CVST [source]¶
Create a Cassandra vectorstore from raw texts.
- Parameters
texts (List[str]) – 要添加到向量存储的文本列表。
embedding (Embeddings) – Embedding function to use.
metadatas (Optional[List[dict]]) – 与文本关联的可选元数据列表。
session (Optional[Session]) – Cassandra driver session. If not provided, it is resolved from cassio.
keyspace (Optional[str]) – Cassandra 键空间。如果未提供,则从 cassio 解析。
table_name (str) – Cassandra table (required).
ids (Optional[List[str]]) – 与文本关联的可选 ID 列表。
concurrency (int) – 发送到数据库的并发查询数。默认为 16。
ttl_seconds (Optional[int]) – Optional time-to-live for the added texts.
body_index_options (Optional[List[Tuple[str, Any]]]) – Optional options used to create the body index. Eg. body_index_options = [cassio.table.cql.STANDARD_ANALYZER]
metadata_indexing (Union[Tuple[str, Iterable[str]], str]) –
kwargs (Any) –
- Returns
一个 Cassandra 向量存储。
- Return type
CVST
- async aget_by_ids(ids: Sequence[str], /) List[Document] ¶
Async get documents by their IDs.
返回的文档应设置 ID 字段为向量存储中文档的 ID。
如果某些 ID 未找到或存在重复 ID,则返回的文档可能少于请求的数量。
用户不应假设返回文档的顺序与输入 ID 的顺序匹配。相反,用户应依赖返回文档的 ID 字段。
如果某些 ID 没有找到文档,此方法不应引发异常。
- Parameters
ids (Sequence[str]) – 要检索的 ID 列表。
- Returns
文档列表。
- Return type
List[Document]
0.2.11 版本新增。
- async amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[Dict[str, str]] = None, body_search: Optional[Union[str, List[str]]] = None, **kwargs: Any) List[Document] [source]¶
返回使用最大边际相关性 (MMR) 选择的文档。最大边际相关性优化了与查询的相似性和所选文档之间的多样性。 :param query: 用于查找相似文档的文本。 :param k: 要返回的文档数量。 :param fetch_k: 要获取并传递给 MMR 算法的文档数量。 :param lambda_mult: 介于 0 和 1 之间的数字,用于确定结果之间多样性的程度,0 表示最大多样性,1 表示最小多样性。默认为 0.5。
of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. Defaults to 0.5.
- Parameters
filter (Optional[Dict[str, str]]) – 应用于元数据的过滤器。
body_search (Optional[Union[str, List[str]]]) – 要应用的文档文本搜索词。目前仅 Astra DB 支持。
query (str) –
k (int) –
fetch_k (int) –
lambda_mult (float) –
kwargs (Any) –
- Returns
由最大边际相关性选择的文档列表。
- 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, filter: Optional[Dict[str, str]] = None, body_search: Optional[Union[str, List[str]]] = None, **kwargs: Any) List[Document] [source]¶
返回使用最大边际相关性 (MMR) 选择的文档。最大边际相关性优化了与查询的相似性和所选文档之间的多样性。 :param embedding: 用于查找相似文档的嵌入向量。 :param k: 要返回的文档数量。默认为 4。 :param fetch_k: 要获取并传递给 MMR 算法的文档数量。
默认为 20。
- Parameters
lambda_mult (float) – 介于 0 和 1 之间的数字,用于确定结果之间多样性的程度,0 表示最大多样性,1 表示最小多样性。默认为 0.5。
filter (Optional[Dict[str, str]]) – 应用于元数据的过滤器。
body_search (Optional[Union[str, List[str]]]) – 要应用的文档文本搜索词。目前仅 Astra DB 支持。
embedding (List[float]) –
k (int) –
fetch_k (int) –
kwargs (Any) –
- Returns
由最大边际相关性选择的文档列表。
- Return type
List[Document]
- as_retriever(search_type: str = 'similarity', search_kwargs: Optional[Dict[str, Any]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) VectorStoreRetriever [source]¶
Return VectorStoreRetriever initialized from this VectorStore.
- Parameters
search_type (str) – 定义检索器应执行的搜索类型。可以是 “similarity”(默认)、“mmr” 或 “similarity_score_threshold”。
search_kwargs (Optional[Dict[str, Any]]) –
传递给搜索函数的关键字参数。可以包括例如:
k: 要返回的文档数量(默认值:4) score_threshold: similarity_score_threshold 的最小相关性阈值
for similarity_score_threshold
fetch_k: 要传递给 MMR 算法的文档数量(默认值:20) lambda_mult: MMR 返回结果的多样性;
1 表示最小多样性,0 表示最大多样性。(默认值:0.5)
filter: 按文档元数据过滤
tags (Optional[List[str]]) – 与检索器关联的标签列表。
metadata (Optional[Dict[str, Any]]) – 与检索器关联的元数据。
kwargs (Any) – 传递给 VectorStoreRetriever init 的其他参数。
- Returns
VectorStore 的检索器。
- Return type
示例
# 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 asimilarity_search(query: str, k: int = 4, filter: Optional[Dict[str, str]] = None, body_search: Optional[Union[str, List[str]]] = None, **kwargs: Any) List[Document] [source]¶
Return docs most similar to query.
- Parameters
query (str) – 用于查找相似文档的文本。
k (int) – 要返回的文档数量。默认为 4。
filter (Optional[Dict[str, str]]) – 应用于元数据的过滤器。
body_search (Optional[Union[str, List[str]]]) – 要应用的文档文本搜索词。目前仅 Astra DB 支持。
kwargs (Any) –
- Returns
Document 列表,与查询向量最相似的文档。
- Return type
List[Document]
- async asimilarity_search_by_vector(embedding: List[float], k: int = 4, filter: Optional[Dict[str, str]] = None, body_search: Optional[Union[str, List[str]]] = None, **kwargs: Any) List[Document] [source]¶
Return docs most similar to embedding vector.
- Parameters
embedding (List[float]) – 用于查找相似文档的嵌入向量。
k (int) – 要返回的文档数量。默认为 4。
filter (Optional[Dict[str, str]]) – 应用于元数据的过滤器。
body_search (Optional[Union[str, List[str]]]) – 要应用的文档文本搜索词。目前仅 Astra DB 支持。
kwargs (Any) –
- Returns
Document 列表,与查询向量最相似的文档。
- 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(query: str, k: int = 4, filter: Optional[Dict[str, str]] = None, body_search: Optional[Union[str, List[str]]] = None) List[Tuple[Document, float]] [source]¶
Return docs most similar to query.
- Parameters
query (str) – 用于查找相似文档的文本。
k (int) – 要返回的文档数量。默认为 4。
filter (Optional[Dict[str, str]]) – 应用于元数据的过滤器。
body_search (Optional[Union[str, List[str]]]) – 要应用的文档文本搜索词。目前仅 Astra DB 支持。
- Returns
(Document,分数)列表,与查询向量最相似的文档。
- Return type
List[Tuple[Document, float]]
- async asimilarity_search_with_score_by_vector(embedding: List[float], k: int = 4, filter: Optional[Dict[str, str]] = None, body_search: Optional[Union[str, List[str]]] = None) List[Tuple[Document, float]] [source]¶
Return docs most similar to embedding vector.
- Parameters
embedding (List[float]) – 用于查找相似文档的嵌入向量。
k (int) – 要返回的文档数量。默认为 4。
filter (Optional[Dict[str, str]]) – 应用于元数据的过滤器。
body_search (Optional[Union[str, List[str]]]) – 要应用的文档文本搜索词。目前仅 Astra DB 支持。
- Returns
(Document,分数)列表,与查询向量最相似的文档。
- Return type
List[Tuple[Document, float]]
- async asimilarity_search_with_score_id(query: str, k: int = 4, filter: Optional[Dict[str, str]] = None, body_search: Optional[Union[str, List[str]]] = None) List[Tuple[Document, float, str]] [source]¶
Return docs most similar to query.
- Parameters
query (str) – 用于查找相似文档的文本。
k (int) – 要返回的文档数量。默认为 4。
filter (Optional[Dict[str, str]]) – 应用于元数据的过滤器。
body_search (Optional[Union[str, List[str]]]) – 要应用的文档文本搜索词。目前仅 Astra DB 支持。
- Returns
(Document,分数,id)列表,与查询向量最相似的文档。
- Return type
List[Tuple[Document, float, str]]
- async asimilarity_search_with_score_id_by_vector(embedding: List[float], k: int = 4, filter: Optional[Dict[str, str]] = None, body_search: Optional[Union[str, List[str]]] = None) List[Tuple[Document, float, str]] [source]¶
Return docs most similar to embedding vector.
- Parameters
embedding (List[float]) – 用于查找相似文档的嵌入向量。
k (int) – 要返回的文档数量。默认为 4。
filter (Optional[Dict[str, str]]) – 应用于元数据的过滤器。
body_search (Optional[Union[str, List[str]]]) – 要应用的文档文本搜索词。目前仅 Astra DB 支持。
- Returns
(Document,分数,id)列表,与查询向量最相似的文档。
- Return type
List[Tuple[Document, float, str]]
- astreaming_upsert(items: AsyncIterable[Document], /, batch_size: int, **kwargs: Any) AsyncIterator[UpsertResponse] ¶
Beta 版本
添加于 0.2.11 版本。API 可能会发生变化。
以流式方式更新插入文档。`streaming_upsert` 的异步版本。
- Parameters
items (AsyncIterable[Document]) – 要添加到向量数据库的文档的可迭代对象。
batch_size (int) – 每次更新插入的批次大小。
kwargs (Any) – 额外的关键字参数。 kwargs 应该只包含所有文档通用的参数。(例如,索引超时、重试策略等)kwargs 不应包含 ids,以避免语义模糊。相反,ID 应该作为 Document 对象的一部分提供。
- Yields:
UpsertResponse – 响应对象,其中包含成功添加到或更新到向量数据库的 ID 列表,以及未能添加或更新的 ID 列表。
- Return type
AsyncIterator[UpsertResponse]
0.2.11 版本新增。
- async aupsert(items: Sequence[Document], /, **kwargs: Any) UpsertResponse ¶
Beta 版本
添加于 0.2.11 版本。API 可能会发生变化。
在向量数据库中添加或更新文档。`upsert` 的异步版本。
如果提供了 Document 对象的 ID 字段,更新插入功能应使用它。如果未提供 ID,则更新插入方法可以自由地为文档生成 ID。
当指定了 ID 并且文档已存在于向量数据库中时,更新插入方法应使用新数据更新文档。如果文档不存在,则更新插入方法应将文档添加到向量数据库中。
- Parameters
items (Sequence[Document]) – 要添加到向量数据库的文档序列。
kwargs (Any) – Additional keyword arguments.
- Returns
一个响应对象,其中包含成功添加到或更新到向量数据库的 ID 列表,以及未能添加或更新的 ID 列表。
- Return type
0.2.11 版本新增。
- delete(ids: Optional[List[str]] = None, **kwargs: Any) Optional[bool] [source]¶
Delete by vector IDs.
- Parameters
ids (Optional[List[str]]) – List of ids to delete.
kwargs (Any) –
- Returns
如果删除成功,则为 True;否则为 False;如果未实现,则为 None。
- Return type
Optional[bool]
- delete_by_document_id(document_id: str) None [source]¶
Delete by document ID.
- Parameters
document_id (str) – 要删除的文档 ID。
- Return type
None
- delete_collection() None [source]¶
Just an alias for clear (to better align with other VectorStore implementations).
- Return type
None
- classmethod from_documents(documents: List[Document], embedding: Embeddings, *, session: Optional[Session] = None, keyspace: Optional[str] = None, table_name: str = '', ids: Optional[List[str]] = None, batch_size: int = 16, ttl_seconds: Optional[int] = None, body_index_options: Optional[List[Tuple[str, Any]]] = None, metadata_indexing: Union[Tuple[str, Iterable[str]], str] = 'all', **kwargs: Any) CVST [source]¶
Create a Cassandra vectorstore from a document list.
- Parameters
documents (List[Document]) – Documents to add to the vectorstore.
embedding (Embeddings) – Embedding function to use.
session (Optional[Session]) – Cassandra driver session. If not provided, it is resolved from cassio.
keyspace (Optional[str]) – Cassandra 键空间。如果未提供,则从 cassio 解析。
table_name (str) – Cassandra table (required).
ids (Optional[List[str]]) – 与文档关联的可选 ID 列表。
batch_size (int) – 发送到服务器的并发请求数。默认为 16。
ttl_seconds (Optional[int]) – 添加文档的可选生存时间(TTL),单位为秒。
body_index_options (Optional[List[Tuple[str, Any]]]) – Optional options used to create the body index. Eg. body_index_options = [cassio.table.cql.STANDARD_ANALYZER]
metadata_indexing (Union[Tuple[str, Iterable[str]], str]) –
kwargs (Any) –
- Returns
一个 Cassandra 向量存储。
- Return type
CVST
- classmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, *, session: Optional[Session] = None, keyspace: Optional[str] = None, table_name: str = '', ids: Optional[List[str]] = None, batch_size: int = 16, ttl_seconds: Optional[int] = None, body_index_options: Optional[List[Tuple[str, Any]]] = None, metadata_indexing: Union[Tuple[str, Iterable[str]], str] = 'all', **kwargs: Any) CVST [source]¶
Create a Cassandra vectorstore from raw texts.
- Parameters
texts (List[str]) – 要添加到向量存储的文本列表。
embedding (Embeddings) – Embedding function to use.
metadatas (Optional[List[dict]]) – 与文本关联的可选元数据列表。
session (Optional[Session]) – Cassandra driver session. If not provided, it is resolved from cassio.
keyspace (Optional[str]) – Cassandra 键空间。如果未提供,则从 cassio 解析。
table_name (str) – Cassandra table (required).
ids (Optional[List[str]]) – 与文本关联的可选 ID 列表。
batch_size (int) – 发送到服务器的并发请求数。默认为 16。
ttl_seconds (Optional[int]) – Optional time-to-live for the added texts.
body_index_options (Optional[List[Tuple[str, Any]]]) – Optional options used to create the body index. Eg. body_index_options = [cassio.table.cql.STANDARD_ANALYZER]
metadata_indexing (Union[Tuple[str, Iterable[str]], str]) –
kwargs (Any) –
- Returns
一个 Cassandra 向量存储。
- Return type
CVST
- get_by_ids(ids: Sequence[str], /) List[Document] ¶
Get documents by their IDs.
返回的文档应设置 ID 字段为向量存储中文档的 ID。
如果某些 ID 未找到或存在重复 ID,则返回的文档可能少于请求的数量。
用户不应假设返回文档的顺序与输入 ID 的顺序匹配。相反,用户应依赖返回文档的 ID 字段。
如果某些 ID 没有找到文档,此方法不应引发异常。
- Parameters
ids (Sequence[str]) – 要检索的 ID 列表。
- Returns
文档列表。
- Return type
List[Document]
0.2.11 版本新增。
- max_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[Dict[str, str]] = None, body_search: Optional[Union[str, List[str]]] = None, **kwargs: Any) List[Document] [source]¶
返回使用最大边际相关性选择的文档。最大边际相关性优化查询的相似性和所选文档之间的多样性。 :param query: 用于查找相似文档的文本。 :param k: 要返回的文档数量。默认为 4。 :param fetch_k: 要获取并传递给 MMR 算法的文档数量。
默认为 20。
- Parameters
lambda_mult (float) – 介于 0 和 1 之间的数字,用于确定结果之间多样性的程度,0 表示最大多样性,1 表示最小多样性。默认为 0.5。
filter (Optional[Dict[str, str]]) – 应用于元数据的过滤器。
body_search (Optional[Union[str, List[str]]]) – 要应用的文档文本搜索词。目前仅 Astra DB 支持。
query (str) –
k (int) –
fetch_k (int) –
kwargs (Any) –
- Returns
由最大边际相关性选择的文档列表。
- 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, filter: Optional[Dict[str, str]] = None, body_search: Optional[Union[str, List[str]]] = None, **kwargs: Any) List[Document] [source]¶
返回使用最大边际相关性 (MMR) 选择的文档。最大边际相关性优化了与查询的相似性和所选文档之间的多样性。 :param embedding: 用于查找相似文档的嵌入向量。 :param k: 要返回的文档数量。默认为 4。 :param fetch_k: 要获取并传递给 MMR 算法的文档数量。
默认为 20。
- Parameters
lambda_mult (float) – 介于 0 和 1 之间的数字,用于确定结果之间多样性的程度,0 表示最大多样性,1 表示最小多样性。默认为 0.5。
filter (Optional[Dict[str, str]]) – 应用于元数据的过滤器。
body_search (Optional[Union[str, List[str]]]) – 要应用的文档文本搜索词。目前仅 Astra DB 支持。
embedding (List[float]) –
k (int) –
fetch_k (int) –
kwargs (Any) –
- Returns
由最大边际相关性选择的文档列表。
- 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) – Input text
search_type (str) – 要执行的搜索类型。可以是 “similarity”、“mmr” 或 “similarity_score_threshold”。
**kwargs (Any) – 传递给搜索方法的参数。
- Returns
与查询最相似的文档列表。
- Raises
ValueError – 如果 search_type 不是 “similarity”、“mmr” 或 “similarity_score_threshold” 之一。
- Return type
List[Document]
- similarity_search(query: str, k: int = 4, filter: Optional[Dict[str, str]] = None, body_search: Optional[Union[str, List[str]]] = None, **kwargs: Any) List[Document] [source]¶
Return docs most similar to query.
- Parameters
query (str) – 用于查找相似文档的文本。
k (int) – 要返回的文档数量。默认为 4。
filter (Optional[Dict[str, str]]) – 应用于元数据的过滤器。
body_search (Optional[Union[str, List[str]]]) – 要应用的文档文本搜索词。目前仅 Astra DB 支持。
kwargs (Any) –
- Returns
Document 列表,与查询向量最相似的文档。
- Return type
List[Document]
- similarity_search_by_vector(embedding: List[float], k: int = 4, filter: Optional[Dict[str, str]] = None, body_search: Optional[Union[str, List[str]]] = None, **kwargs: Any) List[Document] [source]¶
Return docs most similar to embedding vector.
- Parameters
embedding (List[float]) – 用于查找相似文档的嵌入向量。
k (int) – 要返回的文档数量。默认为 4。
filter (Optional[Dict[str, str]]) – 应用于元数据的过滤器。
body_search (Optional[Union[str, List[str]]]) – 要应用的文档文本搜索词。目前仅 Astra DB 支持。
kwargs (Any) –
- Returns
Document 列表,与查询向量最相似的文档。
- 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
List of Tuples of (doc, similarity_score).
- Return type
List[Tuple[Document, float]]
- similarity_search_with_score(query: str, k: int = 4, filter: Optional[Dict[str, str]] = None, body_search: Optional[Union[str, List[str]]] = None) List[Tuple[Document, float]] [source]¶
Return docs most similar to query.
- Parameters
query (str) – 用于查找相似文档的文本。
k (int) – 要返回的文档数量。默认为 4。
filter (Optional[Dict[str, str]]) – 应用于元数据的过滤器。
body_search (Optional[Union[str, List[str]]]) – 要应用的文档文本搜索词。目前仅 Astra DB 支持。
- Returns
(Document,分数)列表,与查询向量最相似的文档。
- Return type
List[Tuple[Document, float]]
- similarity_search_with_score_by_vector(embedding: List[float], k: int = 4, filter: Optional[Dict[str, str]] = None, body_search: Optional[Union[str, List[str]]] = None) List[Tuple[Document, float]] [source]¶
Return docs most similar to embedding vector.
- Parameters
embedding (List[float]) – 用于查找相似文档的嵌入向量。
k (int) – 要返回的文档数量。默认为 4。
filter (Optional[Dict[str, str]]) – 应用于元数据的过滤器。
body_search (Optional[Union[str, List[str]]]) – 要应用的文档文本搜索词。目前仅 Astra DB 支持。
- Returns
(Document,分数)列表,与查询向量最相似的文档。
- Return type
List[Tuple[Document, float]]
- similarity_search_with_score_id(query: str, k: int = 4, filter: Optional[Dict[str, str]] = None, body_search: Optional[Union[str, List[str]]] = None) List[Tuple[Document, float, str]] [source]¶
Return docs most similar to query.
- Parameters
query (str) – 用于查找相似文档的文本。
k (int) – 要返回的文档数量。默认为 4。
filter (Optional[Dict[str, str]]) – 应用于元数据的过滤器。
body_search (Optional[Union[str, List[str]]]) – 要应用的文档文本搜索词。目前仅 Astra DB 支持。
- Returns
(Document,分数,id)列表,与查询向量最相似的文档。
- Return type
List[Tuple[Document, float, str]]
- similarity_search_with_score_id_by_vector(embedding: List[float], k: int = 4, filter: Optional[Dict[str, str]] = None, body_search: Optional[Union[str, List[str]]] = None) List[Tuple[Document, float, str]] [source]¶
Return docs most similar to embedding vector.
- Parameters
embedding (List[float]) – 用于查找相似文档的嵌入向量。
k (int) – 要返回的文档数量。默认为 4。
filter (Optional[Dict[str, str]]) – 应用于元数据的过滤器。
body_search (Optional[Union[str, List[str]]]) – 要应用的文档文本搜索词。目前仅 Astra DB 支持。
- Returns
(Document,分数,id)列表,与查询向量最相似的文档。
- Return type
List[Tuple[Document, float, str]]
- streaming_upsert(items: Iterable[Document], /, batch_size: int, **kwargs: Any) Iterator[UpsertResponse] ¶
Beta 版本
添加于 0.2.11 版本。API 可能会发生变化。
以流式方式更新文档。
- Parameters
items (Iterable[Document]) – 要添加到向量存储的可迭代文档。
batch_size (int) – 每次更新插入的批次大小。
kwargs (Any) – 额外的关键词参数。 kwargs 应该只包含所有文档通用的参数。(例如,索引超时、重试策略等)kwargs 不应包含 ids 以避免语义模糊。相反,ID 应该作为 Document 对象的一部分提供。
- Yields:
UpsertResponse – 响应对象,其中包含成功添加到或更新到向量数据库的 ID 列表,以及未能添加或更新的 ID 列表。
- Return type
Iterator[UpsertResponse]
0.2.11 版本新增。
- upsert(items: Sequence[Document], /, **kwargs: Any) UpsertResponse ¶
Beta 版本
添加于 0.2.11 版本。API 可能会发生变化。
Add or update documents in the vectorstore.
如果提供了 Document 对象的 ID 字段,更新插入功能应使用它。如果未提供 ID,则更新插入方法可以自由地为文档生成 ID。
当指定了 ID 并且文档已存在于向量数据库中时,更新插入方法应使用新数据更新文档。如果文档不存在,则更新插入方法应将文档添加到向量数据库中。
- Parameters
items (Sequence[Document]) – 要添加到向量数据库的文档序列。
kwargs (Any) – Additional keyword arguments.
- Returns
一个响应对象,其中包含成功添加到或更新到向量数据库的 ID 列表,以及未能添加或更新的 ID 列表。
- Return type
0.2.11 版本新增。