langchain_community.vectorstores.deeplake
.DeepLake¶
- class langchain_community.vectorstores.deeplake.DeepLake(dataset_path: str = './deeplake/', token: Optional[str] = None, embedding: Optional[Embeddings] = None, embedding_function: Optional[Embeddings] = None, read_only: bool = False, ingestion_batch_size: int = 1024, num_workers: int = 0, verbose: bool = True, exec_option: Optional[str] = None, runtime: Optional[Dict] = None, index_params: Optional[Dict[str, Union[str, int]]] = None, **kwargs: Any)[source]¶
Activeloop Deep Lake vector store.
We integrated deeplake’s similarity search and filtering for fast prototyping. Now, it supports Tensor Query Language (TQL) for production use cases over billion rows.
Why Deep Lake?
Not only stores embeddings, but also the original data with version control.
- Serverless, doesn’t require another service and can be used with major
cloud providers (S3, GCS, etc.)
- More than just a multi-modal vector store. You can use the dataset
to fine-tune your own LLM models.
To use, you should have the
deeplake
python package installed.Example
from langchain_community.vectorstores import DeepLake from langchain_community.embeddings.openai import OpenAIEmbeddings embeddings = OpenAIEmbeddings() vectorstore = DeepLake("langchain_store", embeddings.embed_query)
Creates an empty DeepLakeVectorStore or loads an existing one.
The DeepLakeVectorStore is located at the specified
path
.Examples
>>> # Create a vector store with default tensors >>> deeplake_vectorstore = DeepLake( ... path = <path_for_storing_Data>, ... ) >>> >>> # Create a vector store in the Deep Lake Managed Tensor Database >>> data = DeepLake( ... path = "hub://org_id/dataset_name", ... runtime = {"tensor_db": True}, ... )
- Parameters
dataset_path (str) –
The full path for storing to the Deep Lake Vector Store. It can be: - a Deep Lake cloud path of the form
hub://org_id/dataset_name
.Requires registration with Deep Lake.
- an s3 path of the form
s3://bucketname/path/to/dataset
. Credentials are required in either the environment or passed to the creds argument.
- an s3 path of the form
- a local file system path of the form
./path/to/dataset
or
~/path/to/dataset
orpath/to/dataset
.
- a local file system path of the form
- a memory path of the form
mem://path/to/dataset
which doesn’t save the dataset but keeps it in memory instead. Should be used only for testing as it does not persist. Defaults to _LANGCHAIN_DEFAULT_DEEPLAKE_PATH.
- a memory path of the form
token (str, optional) – Activeloop token, for fetching credentials to the dataset at path if it is a Deep Lake dataset. Tokens are normally autogenerated. Optional.
embedding (Embeddings, optional) – Function to convert either documents or query. Optional.
embedding_function (Embeddings, optional) – Function to convert either documents or query. Optional. Deprecated: keeping this parameter for backwards compatibility.
read_only (bool) – Open dataset in read-only mode. Default is False.
ingestion_batch_size (int) – During data ingestion, data is divided into batches. Batch size is the size of each batch. Default is 1024.
num_workers (int) – Number of workers to use during data ingestion. Default is 0.
verbose (bool) – Print dataset summary after each operation. Default is True.
exec_option (str, optional) –
Default method for search execution. It could be either
"auto"
,"python"
,"compute_engine"
or"tensor_db"
. Defaults to"auto"
. If None, it’s set to “auto”. -auto
- Selects the best execution method based on the storagelocation of the Vector Store. It is the default option.
python
- Pure-python implementation that runs on the client andcan be used for data stored anywhere. WARNING: using this option with big datasets is discouraged because it can lead to memory issues.
compute_engine
- Performant C++ implementation of the Deep LakeCompute Engine that runs on the client and can be used for any data stored in or connected to Deep Lake. It cannot be used with in-memory or local datasets.
tensor_db
- Performant and fully-hosted Managed Tensor Databasethat is responsible for storage and query execution. Only available for data stored in the Deep Lake Managed Database. Store datasets in this database by specifying runtime = {“tensor_db”: True} during dataset creation.
runtime (Dict, optional) – Parameters for creating the Vector Store in Deep Lake’s Managed Tensor Database. Not applicable when loading an existing Vector Store. To create a Vector Store in the Managed Tensor Database, set runtime = {“tensor_db”: True}.
index_params (Optional[Dict[str, Union[int, str]]], optional) –
Dictionary containing information about vector index that will be created. Defaults to None, which will utilize
DEFAULT_VECTORSTORE_INDEX_PARAMS
fromdeeplake.constants
. The specified key-values override the default ones. - threshold: The threshold for the dataset size above which an indexwill be created for the embedding tensor. When the threshold value is set to -1, index creation is turned off. Defaults to -1, which turns off the index.
- distance_metric: This key specifies the method of calculating the
distance between vectors when creating the vector database (VDB) index. It can either be a string that corresponds to a member of the DistanceType enumeration, or the string value itself. - If no value is provided, it defaults to “L2”. - “L2” corresponds to DistanceType.L2_NORM. - “COS” corresponds to DistanceType.COSINE_SIMILARITY.
additional_params: Additional parameters for fine-tuning the index.
**kwargs – Other optional keyword arguments.
- Raises
ValueError – If some condition is not met.
Attributes
embeddings
Access the query embedding object if available.
Methods
__init__
([dataset_path, token, embedding, ...])Creates an empty DeepLakeVectorStore or loads an existing one.
aadd_documents
(documents, **kwargs)Async run more documents through the embeddings and add to the vectorstore.
aadd_texts
(texts[, metadatas])Async run more texts through the embeddings and add to the vectorstore.
add_documents
(documents, **kwargs)Add or update documents in the vectorstore.
add_texts
(texts[, metadatas, 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_texts
(texts, embedding[, metadatas])Async return VectorStore initialized from texts and embeddings.
aget_by_ids
(ids, /)Async get documents by their IDs.
amax_marginal_relevance_search
(query[, k, ...])Async return docs selected using the maximal marginal relevance.
Async return docs selected using the maximal marginal relevance.
as_retriever
(**kwargs)Return VectorStoreRetriever initialized from this VectorStore.
asearch
(query, search_type, **kwargs)Async return docs most similar to query using a specified search type.
asimilarity_search
(query[, k])Async return docs most similar to query.
asimilarity_search_by_vector
(embedding[, k])Async return docs most similar to embedding vector.
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])Delete the entities in the dataset.
Delete the collection.
ds
()force_delete_by_path
(path)Force delete dataset by path.
from_documents
(documents, embedding, **kwargs)Return VectorStore initialized from documents and embeddings.
from_texts
(texts[, embedding, metadatas, ...])Create a Deep Lake dataset from a raw documents.
get_by_ids
(ids, /)Get documents by their IDs.
max_marginal_relevance_search
(query[, k, ...])Return docs selected using 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.
similarity_search
(query[, k])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])Run similarity search with Deep Lake with distance returned.
- __init__(dataset_path: str = './deeplake/', token: Optional[str] = None, embedding: Optional[Embeddings] = None, embedding_function: Optional[Embeddings] = None, read_only: bool = False, ingestion_batch_size: int = 1024, num_workers: int = 0, verbose: bool = True, exec_option: Optional[str] = None, runtime: Optional[Dict] = None, index_params: Optional[Dict[str, Union[str, int]]] = None, **kwargs: Any) None [source]¶
Creates an empty DeepLakeVectorStore or loads an existing one.
The DeepLakeVectorStore is located at the specified
path
.Examples
>>> # Create a vector store with default tensors >>> deeplake_vectorstore = DeepLake( ... path = <path_for_storing_Data>, ... ) >>> >>> # Create a vector store in the Deep Lake Managed Tensor Database >>> data = DeepLake( ... path = "hub://org_id/dataset_name", ... runtime = {"tensor_db": True}, ... )
- Parameters
dataset_path (str) –
The full path for storing to the Deep Lake Vector Store. It can be: - a Deep Lake cloud path of the form
hub://org_id/dataset_name
.Requires registration with Deep Lake.
- an s3 path of the form
s3://bucketname/path/to/dataset
. Credentials are required in either the environment or passed to the creds argument.
- an s3 path of the form
- a local file system path of the form
./path/to/dataset
or
~/path/to/dataset
orpath/to/dataset
.
- a local file system path of the form
- a memory path of the form
mem://path/to/dataset
which doesn’t save the dataset but keeps it in memory instead. Should be used only for testing as it does not persist. Defaults to _LANGCHAIN_DEFAULT_DEEPLAKE_PATH.
- a memory path of the form
token (str, optional) – Activeloop token, for fetching credentials to the dataset at path if it is a Deep Lake dataset. Tokens are normally autogenerated. Optional.
embedding (Embeddings, optional) – Function to convert either documents or query. Optional.
embedding_function (Embeddings, optional) – Function to convert either documents or query. Optional. Deprecated: keeping this parameter for backwards compatibility.
read_only (bool) – Open dataset in read-only mode. Default is False.
ingestion_batch_size (int) – During data ingestion, data is divided into batches. Batch size is the size of each batch. Default is 1024.
num_workers (int) – Number of workers to use during data ingestion. Default is 0.
verbose (bool) – Print dataset summary after each operation. Default is True.
exec_option (str, optional) –
Default method for search execution. It could be either
"auto"
,"python"
,"compute_engine"
or"tensor_db"
. Defaults to"auto"
. If None, it’s set to “auto”. -auto
- Selects the best execution method based on the storagelocation of the Vector Store. It is the default option.
python
- Pure-python implementation that runs on the client andcan be used for data stored anywhere. WARNING: using this option with big datasets is discouraged because it can lead to memory issues.
compute_engine
- Performant C++ implementation of the Deep LakeCompute Engine that runs on the client and can be used for any data stored in or connected to Deep Lake. It cannot be used with in-memory or local datasets.
tensor_db
- Performant and fully-hosted Managed Tensor Databasethat is responsible for storage and query execution. Only available for data stored in the Deep Lake Managed Database. Store datasets in this database by specifying runtime = {“tensor_db”: True} during dataset creation.
runtime (Dict, optional) – Parameters for creating the Vector Store in Deep Lake’s Managed Tensor Database. Not applicable when loading an existing Vector Store. To create a Vector Store in the Managed Tensor Database, set runtime = {“tensor_db”: True}.
index_params (Optional[Dict[str, Union[int, str]]], optional) –
Dictionary containing information about vector index that will be created. Defaults to None, which will utilize
DEFAULT_VECTORSTORE_INDEX_PARAMS
fromdeeplake.constants
. The specified key-values override the default ones. - threshold: The threshold for the dataset size above which an indexwill be created for the embedding tensor. When the threshold value is set to -1, index creation is turned off. Defaults to -1, which turns off the index.
- distance_metric: This key specifies the method of calculating the
distance between vectors when creating the vector database (VDB) index. It can either be a string that corresponds to a member of the DistanceType enumeration, or the string value itself. - If no value is provided, it defaults to “L2”. - “L2” corresponds to DistanceType.L2_NORM. - “COS” corresponds to DistanceType.COSINE_SIMILARITY.
additional_params: Additional parameters for fine-tuning the index.
**kwargs – Other optional keyword arguments.
- Raises
ValueError – If some condition is not met.
- 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, **kwargs: Any) List[str] ¶
Async run more texts through the embeddings and add to the vectorstore.
- Parameters
texts (Iterable[str]) – Iterable of strings to add to the vectorstore.
metadatas (Optional[List[dict]]) – Optional list of metadatas associated with the texts. Default is None.
**kwargs (Any) – vectorstore specific parameters.
- Returns
List of ids from adding the texts into the vectorstore.
- Raises
ValueError – If the number of metadatas does not match the number of texts.
ValueError – If the number of ids does not match the number of texts.
- Return type
List[str]
- add_documents(documents: List[Document], **kwargs: Any) List[str] ¶
Add or update documents in the vectorstore.
- Parameters
documents (List[Document]) – Documents to add to the vectorstore.
kwargs (Any) – Additional keyword arguments. if kwargs contains ids and documents contain ids, the ids in the kwargs will receive precedence.
- Returns
List of IDs of the added texts.
- Raises
ValueError – If the number of ids does not match the number of documents.
- Return type
List[str]
- add_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) List[str] [source]¶
Run more texts through the embeddings and add to the vectorstore.
Examples
>>> ids = deeplake_vectorstore.add_texts( ... texts = <list_of_texts>, ... metadatas = <list_of_metadata_jsons>, ... ids = <list_of_ids>, ... )
- Parameters
texts (Iterable[str]) – Texts to add to the vectorstore.
metadatas (Optional[List[dict]], optional) – Optional list of metadatas.
ids (Optional[List[str]], optional) – Optional list of IDs.
embedding_function (Optional[Embeddings], optional) – Embedding function to use to convert the text into embeddings.
**kwargs (Any) – Any additional keyword arguments passed is not supported by this method.
- Returns
List of IDs of the added texts.
- Return type
List[str]
- async adelete(ids: Optional[List[str]] = None, **kwargs: Any) Optional[bool] ¶
Async delete by vector ID or other criteria.
- Parameters
ids (Optional[List[str]]) – List of ids to delete. If None, delete all. Default is None.
**kwargs (Any) – Other keyword arguments that subclasses might use.
- Returns
True if deletion is successful, False otherwise, None if not implemented.
- Return type
Optional[bool]
- async classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) VST ¶
Async return VectorStore initialized from documents and embeddings.
- Parameters
documents (List[Document]) – List of Documents to add to the vectorstore.
embedding (Embeddings) – Embedding function to use.
kwargs (Any) – Additional keyword arguments.
- Returns
VectorStore initialized from documents and embeddings.
- Return type
- async classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) VST ¶
Async return VectorStore initialized from texts and embeddings.
- Parameters
texts (List[str]) – Texts to add to the vectorstore.
embedding (Embeddings) – Embedding function to use.
metadatas (Optional[List[dict]]) – Optional list of metadatas associated with the texts. Default is None.
kwargs (Any) – Additional keyword arguments.
- Returns
VectorStore initialized from texts and embeddings.
- Return type
- async aget_by_ids(ids: Sequence[str], /) List[Document] ¶
Async get documents by their IDs.
The returned documents are expected to have the ID field set to the ID of the document in the vector store.
Fewer documents may be returned than requested if some IDs are not found or if there are duplicated IDs.
Users should not assume that the order of the returned documents matches the order of the input IDs. Instead, users should rely on the ID field of the returned documents.
This method should NOT raise exceptions if no documents are found for some IDs.
- Parameters
ids (Sequence[str]) – List of ids to retrieve.
- Returns
List of Documents.
- Return type
List[Document]
New in version 0.2.11.
- async 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.
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) –
- 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) VectorStoreRetriever ¶
Return VectorStoreRetriever initialized from this VectorStore.
- Parameters
**kwargs (Any) –
Keyword arguments to pass to the search function. Can include: search_type (Optional[str]): Defines the type of search that
the Retriever should perform. Can be “similarity” (default), “mmr”, or “similarity_score_threshold”.
- search_kwargs (Optional[Dict]): Keyword arguments to pass to the
- search function. Can include things like:
k: Amount of documents to return (Default: 4) score_threshold: Minimum relevance threshold
for similarity_score_threshold
- fetch_k: Amount of documents to pass to MMR algorithm
(Default: 20)
- lambda_mult: Diversity of results returned by MMR;
1 for minimum diversity and 0 for maximum. (Default: 0.5)
filter: Filter by document metadata
- Returns
Retriever class for VectorStore.
- Return type
Examples:
# 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) – 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 asimilarity_search(query: str, k: int = 4, **kwargs: Any) 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: Optional[List[str]] = None, **kwargs: Any) bool [source]¶
Delete the entities in the dataset.
- Parameters
ids (Optional[List[str]], optional) – The document_ids to delete. Defaults to None.
**kwargs – Other keyword arguments that subclasses might use. - filter (Optional[Dict[str, str]], optional): The filter to delete by. - delete_all (Optional[bool], optional): Whether to drop the dataset.
- Returns
Whether the delete operation was successful.
- Return type
bool
- classmethod force_delete_by_path(path: str) None [source]¶
Force delete dataset by path.
- Parameters
path (str) – path of the dataset to delete.
- Raises
ValueError – if deeplake is not installed.
- Return type
None
- classmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) VST ¶
Return VectorStore initialized from documents and embeddings.
- Parameters
documents (List[Document]) – List of Documents to add to the vectorstore.
embedding (Embeddings) – Embedding function to use.
kwargs (Any) – Additional keyword arguments.
- Returns
VectorStore initialized from documents and embeddings.
- Return type
- classmethod from_texts(texts: List[str], embedding: Optional[Embeddings] = None, metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, dataset_path: str = './deeplake/', **kwargs: Any) DeepLake [source]¶
Create a Deep Lake dataset from a raw documents.
If a dataset_path is specified, the dataset will be persisted in that location, otherwise by default at ./deeplake
Examples: >>> # Search using an embedding >>> vector_store = DeepLake.from_texts( … texts = <the_texts_that_you_want_to_embed>, … embedding_function = <embedding_function_for_query>, … k = <number_of_items_to_return>, … exec_option = <preferred_exec_option>, … )
- Parameters
dataset_path (str) –
The full path to the dataset. Can be:
- Deep Lake cloud path of the form
hub://username/dataset_name
. To write to Deep Lake cloud datasets, ensure that you are logged in to Deep Lake (use ‘activeloop login’ from command line)
- Deep Lake cloud path of the form
- AWS S3 path of the form
s3://bucketname/path/to/dataset
. Credentials are required in either the environment
- AWS S3 path of the form
- Google Cloud Storage path of the form
gcs://bucketname/path/to/dataset
Credentials are required in either the environment
- Local file system path of the form
./path/to/dataset
or ~/path/to/dataset
orpath/to/dataset
.
- Local file system path of the form
- In-memory path of the form
mem://path/to/dataset
which doesn’t save the dataset, but keeps it in memory instead. Should be used only for testing as it does not persist.
- In-memory path of the form
texts (List[Document]) – List of documents to add.
embedding (Optional[Embeddings]) – Embedding function. Defaults to None. Note, in other places, it is called embedding_function.
metadatas (Optional[List[dict]]) – List of metadatas. Defaults to None.
ids (Optional[List[str]]) – List of document IDs. Defaults to None.
kwargs (Any) – Additional keyword arguments.
- Returns
Deep Lake dataset.
- Return type
- get_by_ids(ids: Sequence[str], /) List[Document] ¶
Get documents by their IDs.
The returned documents are expected to have the ID field set to the ID of the document in the vector store.
Fewer documents may be returned than requested if some IDs are not found or if there are duplicated IDs.
Users should not assume that the order of the returned documents matches the order of the input IDs. Instead, users should rely on the ID field of the returned documents.
This method should NOT raise exceptions if no documents are found for some IDs.
- Parameters
ids (Sequence[str]) – List of ids to retrieve.
- Returns
List of Documents.
- Return type
List[Document]
New in version 0.2.11.
- max_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, exec_option: Optional[str] = None, **kwargs: Any) List[Document] [source]¶
Return docs selected using maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents.
Examples: >>> # Search using an embedding >>> data = vector_store.max_marginal_relevance_search( … query = <query_to_search>, … embedding_function = <embedding_function_for_query>, … k = <number_of_items_to_return>, … exec_option = <preferred_exec_option>, … )
- 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 for MMR algorithm.
lambda_mult (float) – Value between 0 and 1. 0 corresponds to maximum diversity and 1 to minimum. Defaults to 0.5.
exec_option (str) –
Supports 3 ways to perform searching. - “python” - Pure-python implementation running on the client.
Can be used for data stored anywhere. WARNING: using this option with big datasets is discouraged due to potential memory issues.
- ”compute_engine” - Performant C++ implementation of the Deep
Lake Compute Engine. Runs on the client and can be used for any data stored in or connected to Deep Lake. It cannot be used with in-memory or local datasets.
- ”tensor_db” - Performant, fully-hosted Managed Tensor Database.
Responsible for storage and query execution. Only available for data stored in the Deep Lake Managed Database. To store datasets in this database, specify runtime = {“db_engine”: True} during dataset creation.
deep_memory (bool) – Whether to use the Deep Memory model for improving search results. Defaults to False if deep_memory is not specified in the Vector Store initialization. If True, the distance metric is set to “deepmemory_distance”, which represents the metric with which the model was trained. The search is performed using the Deep Memory model. If False, the distance metric is set to “COS” or whatever distance metric user specifies.
kwargs (Any) – Additional keyword arguments
- Returns
List of Documents selected by maximal marginal relevance.
- Raises
ValueError – when MRR search is on but embedding function is not specified.
- 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, exec_option: Optional[str] = None, **kwargs: Any) List[Document] [source]¶
Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected docs.
Examples: >>> data = vector_store.max_marginal_relevance_search_by_vector( … embedding=<your_embedding>, … fetch_k=<elements_to_fetch_before_mmr_search>, … k=<number_of_items_to_return>, … exec_option=<preferred_exec_option>, … )
- 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 for MMR algorithm.
lambda_mult (float) – Number between 0 and 1 determining the degree of diversity. 0 corresponds to max diversity and 1 to min diversity. Defaults to 0.5.
exec_option (str) –
DeepLakeVectorStore supports 3 ways for searching. Could be “python”, “compute_engine” or “tensor_db”. Defaults to “python”. - “python” - Pure-python implementation running on the client.
Can be used for data stored anywhere. WARNING: using this option with big datasets is discouraged due to potential memory issues.
- ”compute_engine” - Performant C++ implementation of the Deep
Lake Compute Engine. Runs on the client and can be used for any data stored in or connected to Deep Lake. It cannot be used with in-memory or local datasets.
- ”tensor_db” - Performant, fully-hosted Managed Tensor Database.
Responsible for storage and query execution. Only available for data stored in the Deep Lake Managed Database. To store datasets in this database, specify runtime = {“db_engine”: True} during dataset creation.
deep_memory (bool) – Whether to use the Deep Memory model for improving search results. Defaults to False if deep_memory is not specified in the Vector Store initialization. If True, the distance metric is set to “deepmemory_distance”, which represents the metric with which the model was trained. The search is performed using the Deep Memory model. If False, the distance metric is set to “COS” or whatever distance metric user specifies.
kwargs (Any) – Additional keyword arguments.
- Returns
List[Documents] - A list of documents.
- 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]
- similarity_search(query: str, k: int = 4, **kwargs: Any) List[Document] [source]¶
Return docs most similar to query.
Examples
>>> # Search using an embedding >>> data = vector_store.similarity_search( ... query=<your_query>, ... k=<num_items>, ... exec_option=<preferred_exec_option>, ... ) >>> # Run tql search: >>> data = vector_store.similarity_search( ... query=None, ... tql="SELECT * WHERE id == <id>", ... exec_option="compute_engine", ... )
- Parameters
k (int) – Number of Documents to return. Defaults to 4.
query (str) – Text to look up similar documents.
kwargs (Any) –
Additional keyword arguments include: embedding (Callable): Embedding function to use. Defaults to None. distance_metric (str): ‘L2’ for Euclidean, ‘L1’ for Nuclear, ‘max’
for L-infinity, ‘cos’ for cosine, ‘dot’ for dot product. Defaults to ‘L2’.
- filter (Union[Dict, Callable], optional): Additional filter
before embedding search. - Dict: Key-value search on tensors of htype json,
(sample must satisfy all key-value filters) Dict = {“tensor_1”: {“key”: value}, “tensor_2”: {“key”: value}}
Function: Compatible with deeplake.filter.
Defaults to None.
- exec_option (str): Supports 3 ways to perform searching.
’python’, ‘compute_engine’, or ‘tensor_db’. Defaults to ‘python’. - ‘python’: Pure-python implementation for the client.
WARNING: not recommended for big datasets.
- ’compute_engine’: C++ implementation of the Compute Engine for
the client. Not for in-memory or local datasets.
- ’tensor_db’: Managed Tensor Database for storage and query.
Only for data in Deep Lake Managed Database. Use runtime = {“db_engine”: True} during dataset creation.
- deep_memory (bool): Whether to use the Deep Memory model for improving
search results. Defaults to False if deep_memory is not specified in the Vector Store initialization. If True, the distance metric is set to “deepmemory_distance”, which represents the metric with which the model was trained. The search is performed using the Deep Memory model. If False, the distance metric is set to “COS” or whatever distance metric user specifies.
- Returns
List of Documents most similar to the query vector.
- Return type
List[Document]
- similarity_search_by_vector(embedding: Union[List[float], ndarray], k: int = 4, **kwargs: Any) List[Document] [source]¶
Return docs most similar to embedding vector.
Examples
>>> # Search using an embedding >>> data = vector_store.similarity_search_by_vector( ... embedding=<your_embedding>, ... k=<num_items_to_return>, ... exec_option=<preferred_exec_option>, ... )
- Parameters
embedding (Union[List[float], np.ndarray]) – Embedding to find similar docs.
k (int) – Number of Documents to return. Defaults to 4.
kwargs (Any) –
Additional keyword arguments including: filter (Union[Dict, Callable], optional):
Additional filter before embedding search. -
Dict
- Key-value search on tensors of htype json. Trueif all key-value filters are satisfied. Dict = {“tensor_name_1”: {“key”: value},
”tensor_name_2”: {“key”: value}}
Function
- Any function compatible withdeeplake.filter.
Defaults to None.
- exec_option (str): Options for search execution include
”python”, “compute_engine”, or “tensor_db”. Defaults to “python”. - “python” - Pure-python implementation running on the client.
Can be used for data stored anywhere. WARNING: using this option with big datasets is discouraged due to potential memory issues.
- ”compute_engine” - Performant C++ implementation of the Deep
Lake Compute Engine. Runs on the client and can be used for any data stored in or connected to Deep Lake. It cannot be used with in-memory or local datasets.
- ”tensor_db” - Performant, fully-hosted Managed Tensor Database.
Responsible for storage and query execution. Only available for data stored in the Deep Lake Managed Database. To store datasets in this database, specify runtime = {“db_engine”: True} during dataset creation.
- distance_metric (str): L2 for Euclidean, L1 for Nuclear,
max for L-infinity distance, cos for cosine similarity, ‘dot’ for dot product. Defaults to L2.
- deep_memory (bool): Whether to use the Deep Memory model for improving
search results. Defaults to False if deep_memory is not specified in the Vector Store initialization. If True, the distance metric is set to “deepmemory_distance”, which represents the metric with which the model was trained. The search is performed using the Deep Memory model. If False, the distance metric is set to “COS” or whatever distance metric user specifies.
- 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, **kwargs: Any) List[Tuple[Document, float]] [source]¶
Run similarity search with Deep Lake with distance returned.
Examples: >>> data = vector_store.similarity_search_with_score( … query=<your_query>, … embedding=<your_embedding_function> … k=<number_of_items_to_return>, … exec_option=<preferred_exec_option>, … )
- Parameters
query (str) – Query text to search for.
k (int) – Number of results to return. Defaults to 4.
kwargs (Any) –
Additional keyword arguments. Some of these arguments are: distance_metric: L2 for Euclidean, L1 for Nuclear, max L-infinity
distance, cos for cosine similarity, ‘dot’ for dot product. Defaults to L2.
- filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.
embedding_function (Callable): Embedding function to use. Defaults to None.
- exec_option (str): DeepLakeVectorStore supports 3 ways to perform
searching. It could be either “python”, “compute_engine” or “tensor_db”. Defaults to “python”. - “python” - Pure-python implementation running on the client.
Can be used for data stored anywhere. WARNING: using this option with big datasets is discouraged due to potential memory issues.
- ”compute_engine” - Performant C++ implementation of the Deep
Lake Compute Engine. Runs on the client and can be used for any data stored in or connected to Deep Lake. It cannot be used with in-memory or local datasets.
- ”tensor_db” - Performant, fully-hosted Managed Tensor Database.
Responsible for storage and query execution. Only available for data stored in the Deep Lake Managed Database. To store datasets in this database, specify runtime = {“db_engine”: True} during dataset creation.
- deep_memory (bool): Whether to use the Deep Memory model for improving
search results. Defaults to False if deep_memory is not specified in the Vector Store initialization. If True, the distance metric is set to “deepmemory_distance”, which represents the metric with which the model was trained. The search is performed using the Deep Memory model. If False, the distance metric is set to “COS” or whatever distance metric user specifies.
- Returns
- List of documents most similar to the query
text with distance in float.
- Return type
List[Tuple[Document, float]]