langchain_community.vectorstores.timescalevector
.TimescaleVector¶
- class langchain_community.vectorstores.timescalevector.TimescaleVector(service_url: str, embedding: Embeddings, collection_name: str = 'langchain_store', num_dimensions: int = 1536, distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, pre_delete_collection: bool = False, logger: Optional[Logger] = None, relevance_score_fn: Optional[Callable[[float], float]] = None, time_partition_interval: Optional[timedelta] = None, **kwargs: Any)[source]¶
Timescale Postgres vector store
To use, you should have the
timescale_vector
python package installed.- Parameters
service_url (str) – Service url on timescale cloud.
embedding (Embeddings) – Any embedding function implementing langchain.embeddings.base.Embeddings interface.
collection_name (str) – The name of the collection to use. (default: langchain_store) This will become the table name used for the collection.
distance_strategy (DistanceStrategy) – The distance strategy to use. (default: COSINE)
pre_delete_collection (bool) – If True, will delete the collection if it exists. (default: False). Useful for testing.
num_dimensions (int) –
logger (Optional[logging.Logger]) –
relevance_score_fn (Optional[Callable[[float], float]]) –
time_partition_interval (Optional[timedelta]) –
kwargs (Any) –
Example
from langchain_community.vectorstores import TimescaleVector from langchain_community.embeddings.openai import OpenAIEmbeddings SERVICE_URL = "postgres://tsdbadmin:<password>@<id>.tsdb.cloud.timescale.com:<port>/tsdb?sslmode=require" COLLECTION_NAME = "state_of_the_union_test" embeddings = OpenAIEmbeddings() vectorestore = TimescaleVector.from_documents( embedding=embeddings, documents=docs, collection_name=COLLECTION_NAME, service_url=SERVICE_URL, )
Attributes
DEFAULT_INDEX_TYPE
embeddings
Access the query embedding object if available.
Methods
__init__
(service_url, embedding[, ...])aadd_documents
(documents, **kwargs)Async run more documents through the embeddings and add to the vectorstore.
aadd_embeddings
(texts, embeddings[, ...])Add embeddings to the vectorstore.
aadd_texts
(texts[, metadatas, ids])Run more texts through the embeddings and add to the vectorstore.
add_documents
(documents, **kwargs)Add or update documents in the vectorstore.
add_embeddings
(texts, embeddings[, ...])Add embeddings to the vectorstore.
add_texts
(texts[, metadatas, ids])Run more texts through the embeddings and add to the vectorstore.
adelete
([ids])Async delete by vector ID or other criteria.
afrom_documents
(documents, embedding, **kwargs)Async return VectorStore initialized from documents and embeddings.
afrom_embeddings
(text_embeddings, embedding)Construct TimescaleVector wrapper from raw documents and pre- generated embeddings.
afrom_texts
(texts, embedding[, metadatas, ...])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.
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, filter, ...])Run similarity search with TimescaleVector with distance.
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.
astreaming_upsert
(items, /, batch_size, **kwargs)aupsert
(items, /, **kwargs)create_index
([index_type])date_to_range_filter
(**kwargs)delete
([ids])Delete by vector ID or other criteria.
delete_by_metadata
(filter, **kwargs)Delete by vector ID or other criteria.
from_documents
(documents, embedding, **kwargs)Return VectorStore initialized from documents and embeddings.
from_embeddings
(text_embeddings, embedding)Construct TimescaleVector wrapper from raw documents and pre- generated embeddings.
from_existing_index
(embedding[, ...])Get instance of an existing TimescaleVector store.This method will return the instance of the store without inserting any new embeddings
from_texts
(texts, embedding[, metadatas, ...])Return VectorStore initialized from texts and embeddings.
get_by_ids
(ids, /)Get documents by their IDs.
get_service_url
(kwargs)max_marginal_relevance_search
(query[, k, ...])Return docs selected using the maximal marginal relevance.
Return docs selected using the maximal marginal relevance.
search
(query, search_type, **kwargs)Return docs most similar to query using a specified search type.
service_url_from_db_params
(host, port, ...)Return connection string from database parameters.
similarity_search
(query[, k, filter, predicates])Run similarity search with TimescaleVector with distance.
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)streaming_upsert
(items, /, batch_size, **kwargs)upsert
(items, /, **kwargs)- __init__(service_url: str, embedding: Embeddings, collection_name: str = 'langchain_store', num_dimensions: int = 1536, distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, pre_delete_collection: bool = False, logger: Optional[Logger] = None, relevance_score_fn: Optional[Callable[[float], float]] = None, time_partition_interval: Optional[timedelta] = None, **kwargs: Any) None [source]¶
- Parameters
service_url (str) –
embedding (Embeddings) –
collection_name (str) –
num_dimensions (int) –
distance_strategy (DistanceStrategy) –
pre_delete_collection (bool) –
logger (Optional[Logger]) –
relevance_score_fn (Optional[Callable[[float], float]]) –
time_partition_interval (Optional[timedelta]) –
kwargs (Any) –
- 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_embeddings(texts: Iterable[str], embeddings: List[List[float]], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) List[str] [source]¶
Add embeddings to the vectorstore.
- Parameters
texts (Iterable[str]) – Iterable of strings to add to the vectorstore.
embeddings (List[List[float]]) – List of list of embedding vectors.
metadatas (Optional[List[dict]]) – List of metadatas associated with the texts.
kwargs (Any) – vectorstore specific parameters
ids (Optional[List[str]]) –
- Return type
List[str]
- async aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) List[str] [source]¶
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.
kwargs (Any) – vectorstore specific parameters
ids (Optional[List[str]]) –
- Returns
List of ids from adding the texts into the vectorstore.
- 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) – 附加关键字参数。如果 kwargs 包含 ids 且 documents 包含 ids,则 kwargs 中的 ids 将优先使用。
- Returns
List of IDs of the added texts.
- Raises
ValueError – 如果 ids 的数量与 documents 的数量不匹配。
- Return type
List[str]
- add_embeddings(texts: Iterable[str], embeddings: List[List[float]], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) List[str] [source]¶
Add embeddings to the vectorstore.
- Parameters
texts (Iterable[str]) – Iterable of strings to add to the vectorstore.
embeddings (List[List[float]]) – List of list of embedding vectors.
metadatas (Optional[List[dict]]) – List of metadatas associated with the texts.
kwargs (Any) – vectorstore specific parameters
ids (Optional[List[str]]) –
- Return type
List[str]
- add_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) List[str] [source]¶
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.
kwargs (Any) – vectorstore specific parameters
ids (Optional[List[str]]) –
- Returns
List of ids from adding the texts into the vectorstore.
- 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]]) – 要删除的 ids 列表。如果为 None,则删除全部。默认为 None。
**kwargs (Any) – 子类可能使用的其他关键字参数。
- Returns
如果删除成功,则为 True,否则为 False;如果未实现,则为 None。
- 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]) – 要添加到向量存储的 Document 列表。
embedding (Embeddings) – 要使用的嵌入函数。
kwargs (Any) – Additional keyword arguments.
- Returns
从 documents 和 embeddings 初始化 VectorStore。
- Return type
- async classmethod afrom_embeddings(text_embeddings: List[Tuple[str, List[float]]], embedding: Embeddings, metadatas: Optional[List[dict]] = None, collection_name: str = 'langchain_store', distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, ids: Optional[List[str]] = None, pre_delete_collection: bool = False, **kwargs: Any) TimescaleVector [source]¶
Construct TimescaleVector wrapper from raw documents and pre- generated embeddings.
返回从 documents 和 embeddings 初始化的 VectorStore。需要 Postgres 连接字符串 “可以将其作为参数传递,或者设置 TIMESCALE_SERVICE_URL 环境变量。
Example
from langchain_community.vectorstores import TimescaleVector from langchain_community.embeddings import OpenAIEmbeddings embeddings = OpenAIEmbeddings() text_embeddings = embeddings.embed_documents(texts) text_embedding_pairs = list(zip(texts, text_embeddings)) tvs = TimescaleVector.from_embeddings(text_embedding_pairs, embeddings)
- Parameters
text_embeddings (List[Tuple[str, List[float]]]) –
embedding (Embeddings) –
metadatas (Optional[List[dict]]) –
collection_name (str) –
distance_strategy (DistanceStrategy) –
ids (Optional[List[str]]) –
pre_delete_collection (bool) –
kwargs (Any) –
- Return type
- async classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, collection_name: str = 'langchain_store', distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, ids: Optional[List[str]] = None, pre_delete_collection: bool = False, **kwargs: Any) TimescaleVector [source]¶
返回从 texts 和 embeddings 初始化的 VectorStore。需要 Postgres 连接字符串 “可以将其作为参数传递,或者设置 TIMESCALE_SERVICE_URL 环境变量。
- Parameters
texts (List[str]) –
embedding (Embeddings) –
metadatas (Optional[List[dict]]) –
collection_name (str) –
distance_strategy (DistanceStrategy) –
ids (Optional[List[str]]) –
pre_delete_collection (bool) –
kwargs (Any) –
- Return type
- async aget_by_ids(ids: Sequence[str], /) List[Document] ¶
Async get documents by their IDs.
返回的 document 预计其 ID 字段已设置为向量存储中 document 的 ID。
如果某些 IDs 未找到或存在重复的 IDs,则返回的 document 数量可能少于请求的数量。
用户不应假定返回的 document 的顺序与输入 IDs 的顺序匹配。相反,用户应依赖返回的 document 的 ID 字段。
如果某些 IDs 没有找到 document,此方法 **不应** 引发异常。
- Parameters
ids (Sequence[str]) – 要检索的 ids 列表。
- Returns
Document 列表。
- 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, **kwargs: Any) List[Document] ¶
Async return docs selected using the maximal marginal relevance.
最大边际相关性针对与查询的相似性以及所选文档之间的多样性进行优化。
- Parameters
query (str) – 用于查找相似文档的文本。
k (int) – 要返回的 Document 数量。默认为 4。
fetch_k (int) – 要获取以传递给 MMR 算法的 Document 数量。默认为 20。
lambda_mult (float) – 介于 0 和 1 之间的数字,它决定结果之间多样性的程度,其中 0 对应于最大多样性,而 1 对应于最小多样性。默认为 0.5。
kwargs (Any) –
- Returns
通过最大边际相关性选择的 Document 列表。
- 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.
最大边际相关性针对与查询的相似性以及所选文档之间的多样性进行优化。
- Parameters
embedding (List[float]) – 用于查找相似文档的 Embedding。
k (int) – 要返回的 Document 数量。默认为 4。
fetch_k (int) – 要获取以传递给 MMR 算法的 Document 数量。默认为 20。
lambda_mult (float) – 介于 0 和 1 之间的数字,它决定结果之间多样性的程度,其中 0 对应于最大多样性,而 1 对应于最小多样性。默认为 0.5。
**kwargs (Any) – 传递给搜索方法的参数。
- Returns
通过最大边际相关性选择的 Document 列表。
- Return type
List[Document]
- as_retriever(**kwargs: Any) VectorStoreRetriever ¶
Return VectorStoreRetriever initialized from this VectorStore.
- Parameters
**kwargs (Any) –
要传递给搜索函数的关键字参数。可以包括: search_type (Optional[str]): 定义检索器应执行的搜索类型。
可以是 “similarity”(默认)、“mmr” 或 “similarity_score_threshold”。
- search_kwargs (Optional[Dict]): 要传递给
- 搜索函数的关键字参数。可以包括如下内容
k: 要返回的文档数量(默认值:4) score_threshold: 相似度分数阈值的最小相关性阈值
用于 similarity_score_threshold
- fetch_k: 要传递给 MMR 算法的文档数量
(默认值:20)
- lambda_mult: MMR 返回的结果的多样性;
1 表示最小多样性,0 表示最大多样性。(默认值:0.5)
filter: 按文档元数据筛选
- 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
与查询最相似的 Document 列表。
- Raises
ValueError – 如果 search_type 不是 “similarity”、“mmr” 或 “similarity_score_threshold” 之一。
- Return type
List[Document]
- async asimilarity_search(query: str, k: int = 4, filter: Optional[Union[dict, list]] = None, predicates: Optional[Predicates] = None, **kwargs: Any) List[Document] [source]¶
Run similarity search with TimescaleVector with distance.
- Parameters
query (str) – 要搜索的查询文本。
k (int) – 要返回的结果数。默认为 4。
filter (Optional[Dict[str, str]]) – 按元数据筛选。默认为 None。
predicates (Optional[Predicates]) –
kwargs (Any) –
- Returns
与查询最相似的 Document 列表。
- Return type
List[Document]
- async asimilarity_search_by_vector(embedding: Optional[List[float]], k: int = 4, filter: Optional[Union[dict, list]] = None, predicates: Optional[Predicates] = None, **kwargs: Any) List[Document] [source]¶
Return docs most similar to embedding vector.
- Parameters
embedding (Optional[List[float]]) – 用于查找相似文档的 Embedding。
k (int) – 要返回的 Document 数量。默认为 4。
filter (Optional[Dict[str, str]]) – 按元数据筛选。默认为 None。
predicates (Optional[Predicates]) –
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) – 要返回的 Document 数量。默认为 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[Union[dict, list]] = None, predicates: Optional[Predicates] = None, **kwargs: Any) List[Tuple[Document, float]] [source]¶
Return docs most similar to query.
- Parameters
query (str) – 用于查找相似文档的文本。
k (int) – 要返回的 Document 数量。默认为 4。
filter (Optional[Dict[str, str]]) – 按元数据筛选。默认为 None。
predicates (Optional[Predicates]) –
kwargs (Any) –
- Returns
与查询最相似的 Document 列表以及每个 Document 的分数
- Return type
List[Tuple[Document, float]]
- async asimilarity_search_with_score_by_vector(embedding: Optional[List[float]], k: int = 4, filter: Optional[Union[dict, list]] = None, predicates: Optional[Predicates] = None, **kwargs: Any) List[Tuple[Document, float]] [source]¶
- Parameters
embedding (Optional[List[float]]) –
k (int) –
filter (Optional[Union[dict, list]]) –
predicates (Optional[Predicates]) –
kwargs (Any) –
- Return type
List[Tuple[Document, float]]
- astreaming_upsert(items: AsyncIterable[Document], /, batch_size: int, **kwargs: Any) AsyncIterator[UpsertResponse] ¶
Beta
Added in 0.2.11. The API is subject to change.
以流式方式更新文档。 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
Added in 0.2.11. The API is subject to change.
在向量存储中添加或更新文档。 upsert 的异步版本。
如果提供了 Document 对象的 ID 字段,则更新功能应使用它。如果未提供 ID,则 upsert 方法可以自由地为文档生成 ID。
当指定了 ID 并且文档已存在于向量存储中时,upsert 方法应使用新数据更新文档。如果文档不存在,则 upsert 方法应将文档添加到向量存储中。
- Parameters
items (Sequence[Document]) – 要添加到向量存储的文档序列。
kwargs (Any) – Additional keyword arguments.
- Returns
一个响应对象,其中包含向量存储中成功添加或更新的 ID 列表,以及添加或更新失败的 ID 列表。
- Return type
0.2.11 版本新增。
- create_index(index_type: Union[IndexType, str] = IndexType.TIMESCALE_VECTOR, **kwargs: Any) None [source]¶
- Parameters
index_type (Union[IndexType, str]) –
kwargs (Any) –
- Return type
None
- delete(ids: Optional[List[str]] = None, **kwargs: Any) Optional[bool] [source]¶
Delete by vector ID or other criteria.
- Parameters
ids (Optional[List[str]]) – 要删除的 id 列表。
**kwargs (Any) – 子类可能使用的其他关键字参数。
- Returns
如果删除成功,则为 True,否则为 False;如果未实现,则为 None。
- Return type
Optional[bool]
- delete_by_metadata(filter: Union[Dict[str, str], List[Dict[str, str]]], **kwargs: Any) Optional[bool] [source]¶
Delete by vector ID or other criteria.
- Parameters
ids – 要删除的 id 列表。
**kwargs (Any) – 子类可能使用的其他关键字参数。
filter (Union[Dict[str, str], List[Dict[str, str]]]) –
**kwargs –
- Returns
如果删除成功,则为 True,否则为 False;如果未实现,则为 None。
- 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]) – 要添加到向量存储的 Document 列表。
embedding (Embeddings) – 要使用的嵌入函数。
kwargs (Any) – Additional keyword arguments.
- Returns
从 documents 和 embeddings 初始化 VectorStore。
- Return type
- classmethod from_embeddings(text_embeddings: List[Tuple[str, List[float]]], embedding: Embeddings, metadatas: Optional[List[dict]] = None, collection_name: str = 'langchain_store', distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, ids: Optional[List[str]] = None, pre_delete_collection: bool = False, **kwargs: Any) TimescaleVector [source]¶
Construct TimescaleVector wrapper from raw documents and pre- generated embeddings.
返回从 documents 和 embeddings 初始化的 VectorStore。需要 Postgres 连接字符串 “可以将其作为参数传递,或者设置 TIMESCALE_SERVICE_URL 环境变量。
Example
from langchain_community.vectorstores import TimescaleVector from langchain_community.embeddings import OpenAIEmbeddings embeddings = OpenAIEmbeddings() text_embeddings = embeddings.embed_documents(texts) text_embedding_pairs = list(zip(texts, text_embeddings)) tvs = TimescaleVector.from_embeddings(text_embedding_pairs, embeddings)
- Parameters
text_embeddings (List[Tuple[str, List[float]]]) –
embedding (Embeddings) –
metadatas (Optional[List[dict]]) –
collection_name (str) –
distance_strategy (DistanceStrategy) –
ids (Optional[List[str]]) –
pre_delete_collection (bool) –
kwargs (Any) –
- Return type
- classmethod from_existing_index(embedding: Embeddings, collection_name: str = 'langchain_store', distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, pre_delete_collection: bool = False, **kwargs: Any) TimescaleVector [source]¶
Get instance of an existing TimescaleVector store.This method will return the instance of the store without inserting any new embeddings
- Parameters
embedding (Embeddings) –
collection_name (str) –
distance_strategy (DistanceStrategy) –
pre_delete_collection (bool) –
kwargs (Any) –
- Return type
- classmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, collection_name: str = 'langchain_store', distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, ids: Optional[List[str]] = None, pre_delete_collection: bool = False, **kwargs: Any) TimescaleVector [source]¶
返回从 texts 和 embeddings 初始化的 VectorStore。需要 Postgres 连接字符串 “可以将其作为参数传递,或者设置 TIMESCALE_SERVICE_URL 环境变量。
- Parameters
texts (List[str]) –
embedding (Embeddings) –
metadatas (Optional[List[dict]]) –
collection_name (str) –
distance_strategy (DistanceStrategy) –
ids (Optional[List[str]]) –
pre_delete_collection (bool) –
kwargs (Any) –
- Return type
- get_by_ids(ids: Sequence[str], /) List[Document] ¶
Get documents by their IDs.
返回的 document 预计其 ID 字段已设置为向量存储中 document 的 ID。
如果某些 IDs 未找到或存在重复的 IDs,则返回的 document 数量可能少于请求的数量。
用户不应假定返回的 document 的顺序与输入 IDs 的顺序匹配。相反,用户应依赖返回的 document 的 ID 字段。
如果某些 IDs 没有找到 document,此方法 **不应** 引发异常。
- Parameters
ids (Sequence[str]) – 要检索的 ids 列表。
- Returns
Document 列表。
- Return type
List[Document]
0.2.11 版本新增。
- classmethod get_service_url(kwargs: Dict[str, Any]) str [source]¶
- Parameters
kwargs (Dict[str, Any]) –
- Return type
str
- max_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) List[Document] ¶
Return docs selected using the maximal marginal relevance.
最大边际相关性针对与查询的相似性以及所选文档之间的多样性进行优化。
- Parameters
query (str) – 用于查找相似文档的文本。
k (int) – 要返回的 Document 数量。默认为 4。
fetch_k (int) – 要获取以传递给 MMR 算法的 Document 数量。默认为 20。
lambda_mult (float) – 介于 0 和 1 之间的数字,它决定结果之间多样性的程度,其中 0 对应于最大多样性,而 1 对应于最小多样性。默认为 0.5。
**kwargs (Any) – 传递给搜索方法的参数。
- Returns
通过最大边际相关性选择的 Document 列表。
- 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.
最大边际相关性针对与查询的相似性以及所选文档之间的多样性进行优化。
- Parameters
embedding (List[float]) – 用于查找相似文档的 Embedding。
k (int) – 要返回的 Document 数量。默认为 4。
fetch_k (int) – 要获取以传递给 MMR 算法的 Document 数量。默认为 20。
lambda_mult (float) – 介于 0 和 1 之间的数字,它决定结果之间多样性的程度,其中 0 对应于最大多样性,而 1 对应于最小多样性。默认为 0.5。
**kwargs (Any) – 传递给搜索方法的参数。
- Returns
通过最大边际相关性选择的 Document 列表。
- 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
与查询最相似的 Document 列表。
- Raises
ValueError – 如果 search_type 不是 “similarity”、“mmr” 或 “similarity_score_threshold” 之一。
- Return type
List[Document]
- classmethod service_url_from_db_params(host: str, port: int, database: str, user: str, password: str) str [source]¶
Return connection string from database parameters.
- Parameters
host (str) –
port (int) –
database (str) –
user (str) –
password (str) –
- Return type
str
- similarity_search(query: str, k: int = 4, filter: Optional[Union[dict, list]] = None, predicates: Optional[Predicates] = None, **kwargs: Any) List[Document] [source]¶
Run similarity search with TimescaleVector with distance.
- Parameters
query (str) – 要搜索的查询文本。
k (int) – 要返回的结果数。默认为 4。
filter (Optional[Dict[str, str]]) – 按元数据筛选。默认为 None。
predicates (Optional[Predicates]) –
kwargs (Any) –
- Returns
与查询最相似的 Document 列表。
- Return type
List[Document]
- similarity_search_by_vector(embedding: Optional[List[float]], k: int = 4, filter: Optional[Union[dict, list]] = None, predicates: Optional[Predicates] = None, **kwargs: Any) List[Document] [source]¶
Return docs most similar to embedding vector.
- Parameters
embedding (Optional[List[float]]) – 用于查找相似文档的 Embedding。
k (int) – 要返回的 Document 数量。默认为 4。
filter (Optional[Dict[str, str]]) – 按元数据筛选。默认为 None。
predicates (Optional[Predicates]) –
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) – 要返回的 Document 数量。默认为 4。
**kwargs (Any) –
要传递给相似性搜索的 kwargs。应包括: score_threshold: 可选,介于 0 到 1 之间的浮点值,用于
过滤检索到的文档结果集。
- Returns
文档和相似度分数的元组列表。
- Return type
List[Tuple[Document, float]]
- similarity_search_with_score(query: str, k: int = 4, filter: Optional[Union[dict, list]] = None, predicates: Optional[Predicates] = None, **kwargs: Any) List[Tuple[Document, float]] [source]¶
Return docs most similar to query.
- Parameters
query (str) – 用于查找相似文档的文本。
k (int) – 要返回的 Document 数量。默认为 4。
filter (Optional[Dict[str, str]]) – 按元数据筛选。默认为 None。
predicates (Optional[Predicates]) –
kwargs (Any) –
- Returns
与查询最相似的 Document 列表以及每个 Document 的分数
- Return type
List[Tuple[Document, float]]
- similarity_search_with_score_by_vector(embedding: Optional[List[float]], k: int = 4, filter: Optional[Union[dict, list]] = None, predicates: Optional[Predicates] = None, **kwargs: Any) List[Tuple[Document, float]] [source]¶
- Parameters
embedding (Optional[List[float]]) –
k (int) –
filter (Optional[Union[dict, list]]) –
predicates (Optional[Predicates]) –
kwargs (Any) –
- Return type
List[Tuple[Document, float]]
- streaming_upsert(items: Iterable[Document], /, batch_size: int, **kwargs: Any) Iterator[UpsertResponse] ¶
Beta
Added in 0.2.11. The API is subject to change.
以流式方式更新文档。
- 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
Added in 0.2.11. The API is subject to change.
Add or update documents in the vectorstore.
如果提供了 Document 对象的 ID 字段,则更新功能应使用它。如果未提供 ID,则 upsert 方法可以自由地为文档生成 ID。
当指定了 ID 并且文档已存在于向量存储中时,upsert 方法应使用新数据更新文档。如果文档不存在,则 upsert 方法应将文档添加到向量存储中。
- Parameters
items (Sequence[Document]) – 要添加到向量存储的文档序列。
kwargs (Any) – Additional keyword arguments.
- Returns
一个响应对象,其中包含向量存储中成功添加或更新的 ID 列表,以及添加或更新失败的 ID 列表。
- Return type
0.2.11 版本新增。