AmazonS3Vectors#

class langchain_aws.vectorstores.s3_vectors.base.AmazonS3Vectors(
*,
vector_bucket_name: str,
index_name: str,
data_type: Literal['float32'] = 'float32',
distance_metric: Literal['euclidean', 'cosine'] = 'cosine',
non_filterable_metadata_keys: list[str] | None = None,
page_content_metadata_key: str | None = '_page_content',
create_index_if_not_exist: bool = True,
relevance_score_fn: Callable[[float], float] | None = None,
embedding: Embeddings | None = None,
region_name: str | None = None,
credentials_profile_name: str | None = None,
aws_access_key_id: str | None = None,
aws_secret_access_key: str | None = None,
aws_session_token: str | None = None,
endpoint_url: str | None = None,
config: Any = None,
client: Any = None,
**kwargs: Any,
)[source]#

S3Vectors is Amazon S3 Vectors database.

To use, you MUST first manually create a S3 vector bucket. There is no need to create a vector index. See: https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-vectors-getting-started.html

Pay attention to s3 vectors limitations and restrictions. By default, metadata for s3 vectors includes page_content and metadata for the Document. See: https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-vectors-limitations.html

Examples:

The following examples show various ways to use the AmazonS3Vectors with LangChain.

For all the following examples assume we have the following:

from langchain_aws.embeddings import BedrockEmbeddings
from langchain_aws.vectorstores.s3_vectors import AmazonS3Vectors

embedding = BedrockEmbeddings()
Initialize, create vector index if not exist, and add texts
vector_store = AmazonS3Vectors.from_texts(
    ["hello", "developer", "wife"],
    vector_bucket_name="<vector bucket name>",
    index_name="<vector index name>",
    embedding=embedding,
)
Initialize, create vector index if not exist, and add texts and add Documents
from langchain_core.documents import Document

vector_store = AmazonS3Vectors(
    vector_bucket_name="<vector bucket name>",
    index_name="<vector index name>",
    embedding=embedding,
)
vector_store.add_documents(
    [
        Document("Star Wars", id="key1", metadata={"genre": "scifi"}),
        Document("Jurassic Park", id="key2", metadata={"genre": "scifi"}),
        Document("Finding Nemo", id="key3", metadata={"genre": "family"}),
    ]
)
Search with score(distance) and metadata filter
vector_store.similarity_search_with_score(
    "adventures in space", filter={"genre": {"$eq": "family"}}
)

Create a AmazonS3Vectors.

Parameters:
  • vector_bucket_name (str) – The name of an existing S3 vector bucket

  • index_name (str) – The name of the S3 vector index. The index names must be 3 to 63 characters long, start and end with a letter or number, and contain only lowercase letters, numbers, hyphens and dots.

  • data_type (Literal["float32"]) – The data type of the vectors to be inserted into the vector index. Default is “float32”.

  • distance_metric (Literal["euclidean","cosine"]) – The distance metric to be used for similarity search. Default is “cosine”.

  • non_filterable_metadata_keys (list[str] | None) – Non-filterable metadata keys

  • page_content_metadata_key (Optional[str]) – Key of metadata to store page_content in Document. If None, embedding page_content but stored as an empty string. Default is “_page_content”.

  • create_index_if_not_exist (bool) – Automatically create vector index if it does not exist. Default is True.

  • relevance_score_fn (Optional[Callable[[float], float]]) – The ‘correct’ relevance function.

  • embedding (Optional[Embeddings]) – Embedding function to use.

  • region_name (Optional[str]) – The aws region where the Sagemaker model is deployed, eg. us-west-2.

  • credentials_profile_name (Optional[str]) – The name of the profile in the ~/.aws/credentials or ~/.aws/config files, which has either access keys or role information specified. If not specified, the default credential profile or, if on an EC2 instance, credentials from IMDS will be used. See: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html

  • aws_access_key_id (Optional[str]) – AWS access key id. If provided, aws_secret_access_key must also be provided. If not specified, the default credential profile or, if on an EC2 instance, credentials from IMDS will be used. See: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html If not provided, will be read from ‘AWS_ACCESS_KEY_ID’ environment variable.

  • aws_secret_access_key (Optional[str]) – AWS secret_access_key. If provided, aws_access_key_id must also be provided. If not specified, the default credential profile or, if on an EC2 instance, credentials from IMDS will be used. See: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html If not provided, will be read from ‘AWS_SECRET_ACCESS_KEY’ environment variable.

  • aws_session_token (Optional[str]) – AWS session token. If provided, aws_access_key_id and aws_secret_access_key must also be provided. Not required unless using temporary credentials. See: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html If not provided, will be read from ‘AWS_SESSION_TOKEN’ environment variable.

  • endpoint_url (Optional[str]) – Needed if you don’t want to default to us-east-1 endpoint

  • config (Any) – An optional botocore.config.Config instance to pass to the client.

  • client (Any) – Boto3 client for s3vectors

  • kwargs (Any) – Additional keyword arguments.

Attributes

embeddings

Access the query embedding object if available.

Methods

__init__(*, vector_bucket_name, index_name)

Create a AmazonS3Vectors.

aadd_documents(documents, **kwargs)

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

aadd_texts(texts[, metadatas, ids])

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, ids, batch_size])

Add more texts 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_texts(texts, embedding[, metadatas, ids])

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 AmazonS3VectorsRetriever initialized from this AmazonS3Vectors.

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.

delete([ids, batch_size])

Delete by vector ID or delete index.

from_documents(documents, embedding, **kwargs)

Return VectorStore initialized from documents and embeddings.

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

Return AmazonS3Vectors initialized from texts and embeddings.

get_by_ids(ids, /, *[, batch_size])

Get documents by their IDs.

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

Return docs selected using the maximal marginal relevance.

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, filter])

Return docs most similar to query.

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

Return docs most similar to embedding vector.

similarity_search_with_relevance_scores(query)

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

similarity_search_with_score(query[, k, filter])

Run similarity search with score(distance).

__init__(
*,
vector_bucket_name: str,
index_name: str,
data_type: Literal['float32'] = 'float32',
distance_metric: Literal['euclidean', 'cosine'] = 'cosine',
non_filterable_metadata_keys: list[str] | None = None,
page_content_metadata_key: str | None = '_page_content',
create_index_if_not_exist: bool = True,
relevance_score_fn: Callable[[float], float] | None = None,
embedding: Embeddings | None = None,
region_name: str | None = None,
credentials_profile_name: str | None = None,
aws_access_key_id: str | None = None,
aws_secret_access_key: str | None = None,
aws_session_token: str | None = None,
endpoint_url: str | None = None,
config: Any = None,
client: Any = None,
**kwargs: Any,
)[source]#

Create a AmazonS3Vectors.

Parameters:
  • vector_bucket_name (str) – The name of an existing S3 vector bucket

  • index_name (str) – The name of the S3 vector index. The index names must be 3 to 63 characters long, start and end with a letter or number, and contain only lowercase letters, numbers, hyphens and dots.

  • data_type (Literal["float32"]) – The data type of the vectors to be inserted into the vector index. Default is “float32”.

  • distance_metric (Literal["euclidean","cosine"]) – The distance metric to be used for similarity search. Default is “cosine”.

  • non_filterable_metadata_keys (list[str] | None) – Non-filterable metadata keys

  • page_content_metadata_key (Optional[str]) – Key of metadata to store page_content in Document. If None, embedding page_content but stored as an empty string. Default is “_page_content”.

  • create_index_if_not_exist (bool) – Automatically create vector index if it does not exist. Default is True.

  • relevance_score_fn (Optional[Callable[[float], float]]) – The ‘correct’ relevance function.

  • embedding (Optional[Embeddings]) – Embedding function to use.

  • region_name (Optional[str]) – The aws region where the Sagemaker model is deployed, eg. us-west-2.

  • credentials_profile_name (Optional[str]) – The name of the profile in the ~/.aws/credentials or ~/.aws/config files, which has either access keys or role information specified. If not specified, the default credential profile or, if on an EC2 instance, credentials from IMDS will be used. See: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html

  • aws_access_key_id (Optional[str]) – AWS access key id. If provided, aws_secret_access_key must also be provided. If not specified, the default credential profile or, if on an EC2 instance, credentials from IMDS will be used. See: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html If not provided, will be read from ‘AWS_ACCESS_KEY_ID’ environment variable.

  • aws_secret_access_key (Optional[str]) – AWS secret_access_key. If provided, aws_access_key_id must also be provided. If not specified, the default credential profile or, if on an EC2 instance, credentials from IMDS will be used. See: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html If not provided, will be read from ‘AWS_SECRET_ACCESS_KEY’ environment variable.

  • aws_session_token (Optional[str]) – AWS session token. If provided, aws_access_key_id and aws_secret_access_key must also be provided. Not required unless using temporary credentials. See: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html If not provided, will be read from ‘AWS_SESSION_TOKEN’ environment variable.

  • endpoint_url (Optional[str]) – Needed if you don’t want to default to us-east-1 endpoint

  • config (Any) – An optional botocore.config.Config instance to pass to the client.

  • client (Any) – Boto3 client for s3vectors

  • kwargs (Any) – Additional keyword arguments.

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: list[dict] | None = None,
*,
ids: list[str] | None = 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.

  • ids (Optional[list[str]]) – Optional list

  • **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: List[dict] | None = None,
*,
ids: List[str | None] | None = None,
batch_size: int = 200,
**kwargs: Any,
) List[str][source]#

Add more texts to the vectorstore.

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

  • metadatas (Optional[List[dict]], optional) – Optional list of metadatas. Defaults to None.

  • embedding (Optional[List[List[float]]], optional) – Optional pre-generated embedding. Defaults to None.

  • ids (Optional[list[str | None]]) – Optional list of IDs associated with the texts.

  • batch_size (int) – Batch size for put_vectors.

  • kwargs (Any) – Additional keyword arguments.

Returns:

List of ids added to the vectorstore

Return type:

List[str]

async adelete(
ids: list[str] | None = None,
**kwargs: Any,
) bool | None#

Async delete by vector ID or other criteria.

Parameters:
  • ids (list[str] | None) – 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,
) Self#

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: list[dict] | None = None,
*,
ids: list[str] | None = None,
**kwargs: Any,
) Self#

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 (list[dict] | None) – Optional list of metadatas associated with the texts. Default is None.

  • ids (list[str] | None) – Optional list of IDs associated with the texts.

  • 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]

Added in version 0.2.11.

Async return docs selected using the maximal marginal relevance.

Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents.

Parameters:
  • query (str) – Text to look up documents similar to.

  • k (int) – Number of Documents to return. Defaults to 4.

  • fetch_k (int) – Number of Documents to fetch to pass to MMR algorithm. Default is 20.

  • lambda_mult (float) – 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.

  • **kwargs (Any) – Arguments to pass to the search method.

Returns:

List of Documents selected by maximal marginal relevance.

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.

Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents.

Parameters:
  • embedding (list[float]) – Embedding to look up documents similar to.

  • k (int) – Number of Documents to return. Defaults to 4.

  • fetch_k (int) – Number of Documents to fetch to pass to MMR algorithm. Default is 20.

  • lambda_mult (float) – 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.

  • **kwargs (Any) – Arguments to pass to the search method.

Returns:

List of Documents selected by maximal marginal relevance.

Return type:

list[Document]

as_retriever(
**kwargs: Any,
) AmazonS3VectorsRetriever[source]#

Return AmazonS3VectorsRetriever initialized from this AmazonS3Vectors.

Parameters:

kwargs (Any)

Return type:

AmazonS3VectorsRetriever

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) – Input text.

  • search_type (str) – Type of search to perform. Can be “similarity”, “mmr”, or “similarity_score_threshold”.

  • **kwargs (Any) – Arguments to pass to the search method.

Returns:

List of Documents most similar to the query.

Raises:

ValueError – If search_type is not one of “similarity”, “mmr”, or “similarity_score_threshold”.

Return type:

list[Document]

Async return docs most similar to query.

Parameters:
  • query (str) – Input text.

  • k (int) – Number of Documents to return. Defaults to 4.

  • **kwargs (Any) – Arguments to pass to the search method.

Returns:

List of Documents most similar to the query.

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]) – Embedding to look up documents similar to.

  • k (int) – Number of Documents to return. Defaults to 4.

  • **kwargs (Any) – Arguments to pass to the search method.

Returns:

List of Documents most similar to the query vector.

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 is dissimilar, 1 is most similar.

Parameters:
  • query (str) – Input text.

  • k (int) – Number of Documents to return. Defaults to 4.

  • **kwargs (Any) –

    kwargs to be passed to similarity search. Should include: score_threshold: Optional, a floating point value between 0 to 1 to

    filter the resulting set of retrieved docs

Returns:

List of Tuples of (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) – Arguments to pass to the search method.

  • **kwargs (Any) – Arguments to pass to the search method.

Returns:

List of Tuples of (doc, similarity_score).

Return type:

list[tuple[Document, float]]

delete(
ids: list[str] | None = None,
*,
batch_size: int = 500,
**kwargs: Any,
) bool | None[source]#

Delete by vector ID or delete index.

Parameters:
  • ids (list[str] | None) – List of ids to delete vectors. If None, delete index with all vectors. Default is None.

  • batch_size (int) – Batch size for delete_vectors.

  • **kwargs (Any) – Additional keyword arguments.

Returns:

Always True.

Return type:

Optional[bool]

classmethod from_documents(
documents: list[Document],
embedding: Embeddings,
**kwargs: Any,
) Self#

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: list[dict] | None = None,
*,
ids: list[str] | None = None,
vector_bucket_name: str,
index_name: str,
data_type: Literal['float32'] = 'float32',
distance_metric: Literal['euclidean', 'cosine'] = 'cosine',
non_filterable_metadata_keys: list[str] | None = None,
page_content_metadata_key: str | None = '_page_content',
create_index_if_not_exist: bool = True,
relevance_score_fn: Callable[[float], float] | None = None,
region_name: str | None = None,
credentials_profile_name: str | None = None,
aws_access_key_id: str | None = None,
aws_secret_access_key: str | None = None,
aws_session_token: str | None = None,
endpoint_url: str | None = None,
config: Any = None,
client: Any = None,
**kwargs: Any,
) AmazonS3Vectors[source]#

Return AmazonS3Vectors initialized from texts and embeddings.

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

  • embedding (Embeddings) – Embedding function to use.

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

  • ids (list[str] | None) – Optional list of IDs associated with the texts.

  • vector_bucket_name (str) – The name of an existing S3 vector bucket

  • index_name (str) – The name of the S3 vector index. The index names must be 3 to 63 characters long, start and end with a letter or number, and contain only lowercase letters, numbers, hyphens and dots.

  • data_type (Literal["float32"]) – The data type of the vectors to be inserted into the vector index. Default is “float32”.

  • distance_metric (Literal["euclidean","cosine"]) – The distance metric to be used for similarity search. Default is “cosine”.

  • non_filterable_metadata_keys (list[str] | None) – Non-filterable metadata keys

  • page_content_metadata_key (Optional[str]) – Key of metadata to store page_content in Document. If None, embedding page_content but stored as an empty string. Default is “_page_content”.

  • create_index_if_not_exist (bool) – Automatically create vector index if it does not exist. Default is True.

  • relevance_score_fn (Optional[Callable[[float], float]]) – The ‘correct’ relevance function.

  • region_name (Optional[str]) – The aws region where the Sagemaker model is deployed, eg. us-west-2.

  • credentials_profile_name (Optional[str]) – The name of the profile in the ~/.aws/credentials or ~/.aws/config files, which has either access keys or role information specified. If not specified, the default credential profile or, if on an EC2 instance, credentials from IMDS will be used. See: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html

  • aws_access_key_id (Optional[str]) – AWS access key id. If provided, aws_secret_access_key must also be provided. If not specified, the default credential profile or, if on an EC2 instance, credentials from IMDS will be used. See: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html If not provided, will be read from ‘AWS_ACCESS_KEY_ID’ environment variable.

  • aws_secret_access_key (Optional[str]) – AWS secret_access_key. If provided, aws_access_key_id must also be provided. If not specified, the default credential profile or, if on an EC2 instance, credentials from IMDS will be used. See: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html If not provided, will be read from ‘AWS_SECRET_ACCESS_KEY’ environment variable.

  • aws_session_token (Optional[str]) – AWS session token. If provided, aws_access_key_id and aws_secret_access_key must also be provided. Not required unless using temporary credentials. See: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html If not provided, will be read from ‘AWS_SESSION_TOKEN’ environment variable.

  • endpoint_url (Optional[str]) – Needed if you don’t want to default to us-east-1 endpoint

  • config (Any) – An optional botocore.config.Config instance to pass to the client.

  • client (Any) – Boto3 client for s3vectors

  • kwargs (Any) – Arguments to pass to AmazonS3Vectors.

Returns:

AmazonS3Vectors initialized from texts and embeddings.

Return type:

AmazonS3Vectors

get_by_ids(
ids: Sequence[str],
/,
*,
batch_size: int = 100,
) list[Document][source]#

Get documents by their IDs.

Parameters:
  • ids (Sequence[str]) – List of id.

  • batch_size (int) – Batch size for get_vectors.

Returns:

List of Documents.

Return type:

list[Document]

Return docs selected using the maximal marginal relevance.

Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents.

Parameters:
  • query (str) – Text to look up documents similar to.

  • k (int) – Number of Documents to return. Defaults to 4.

  • fetch_k (int) – Number of Documents to fetch to pass to MMR algorithm. Default is 20.

  • lambda_mult (float) – 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.

  • **kwargs (Any) – Arguments to pass to the search method.

Returns:

List of Documents selected by maximal marginal relevance.

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.

Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents.

Parameters:
  • embedding (list[float]) – Embedding to look up documents similar to.

  • k (int) – Number of Documents to return. Defaults to 4.

  • fetch_k (int) – Number of Documents to fetch to pass to MMR algorithm. Default is 20.

  • lambda_mult (float) – 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.

  • **kwargs (Any) – Arguments to pass to the search method.

Returns:

List of Documents selected by maximal marginal relevance.

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) – Type of search to perform. Can be “similarity”, “mmr”, or “similarity_score_threshold”.

  • **kwargs (Any) – Arguments to pass to the search method.

Returns:

List of Documents most similar to the query.

Raises:

ValueError – If search_type is not one of “similarity”, “mmr”, or “similarity_score_threshold”.

Return type:

list[Document]

Return docs most similar to query.

Parameters:
  • query (str) – Input text.

  • k (int) – Number of Documents to return. Defaults to 4.

  • filter (dict | None) – Metadata filter to apply during the query. See:https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-vectors-metadata-filtering.html

  • **kwargs (Any) – Arguments to pass to the search method.

Returns:

List of Documents most similar to the query.

Return type:

list[Document]

similarity_search_by_vector(
embedding: list[float],
k: int = 4,
*,
filter: dict | None = None,
**kwargs: Any,
) list[Document][source]#

Return docs most similar to embedding vector.

Parameters:
  • embedding (list[float]) – Embedding to look up documents similar to.

  • k (int) – Number of Documents to return. Defaults to 4.

  • filter (dict | None) – Metadata filter to apply during the query. See:https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-vectors-metadata-filtering.html

  • **kwargs (Any) – Additional keyword arguments.

Returns:

List of Documents most similar to the query vector.

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 is dissimilar, 1 is most similar.

Parameters:
  • query (str) – Input text.

  • k (int) – Number of Documents to return. Defaults to 4.

  • **kwargs (Any) –

    kwargs to be passed to similarity search. Should include: score_threshold: Optional, a floating point value between 0 to 1 to

    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: dict | None = None,
**kwargs: Any,
) list[tuple[Document, float]][source]#

Run similarity search with score(distance).

Parameters:
  • query (str) – Input text.

  • k (int) – Number of Documents to return. Defaults to 4.

  • filter (dict | None) – Metadata filter to apply during the query. See:https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-vectors-metadata-filtering.html

  • **kwargs (Any) – Additional keyword arguments.

Returns:

List of Tuples of (doc, distance).

Return type:

list[tuple[Document, float]]