SingleStoreDB#
- class langchain_community.vectorstores.singlestoredb.SingleStoreDB(embedding: Embeddings, *, distance_strategy: DistanceStrategy = DistanceStrategy.DOT_PRODUCT, table_name: str = 'embeddings', content_field: str = 'content', metadata_field: str = 'metadata', vector_field: str = 'vector', id_field: str = 'id', use_vector_index: bool = False, vector_index_name: str = '', vector_index_options: dict | None = None, vector_size: int = 1536, use_full_text_search: bool = False, pool_size: int = 5, max_overflow: int = 10, timeout: float = 30, **kwargs: Any)[source]#
SingleStore DB vector store.
The prerequisite for using this class is the installation of the
singlestoredb
Python package.The SingleStoreDB vectorstore can be created by providing an embedding function and the relevant parameters for the database connection, connection pool, and optionally, the names of the table and the fields to use.
Initialize with necessary components.
- Parameters:
embedding (Embeddings) – A text embedding model.
distance_strategy (DistanceStrategy, optional) –
Determines the strategy employed for calculating the distance between vectors in the embedding space. Defaults to DOT_PRODUCT. Available options are: - DOT_PRODUCT: Computes the scalar product of two vectors.
This is the default behavior
- EUCLIDEAN_DISTANCE: Computes the Euclidean distance between
two vectors. This metric considers the geometric distance in the vector space, and might be more suitable for embeddings that rely on spatial relationships. This metric is not compatible with the WEIGHTED_SUM search strategy.
table_name (str, optional) – Specifies the name of the table in use. Defaults to “embeddings”.
content_field (str, optional) – Specifies the field to store the content. Defaults to “content”.
metadata_field (str, optional) – Specifies the field to store metadata. Defaults to “metadata”.
vector_field (str, optional) – Specifies the field to store the vector. Defaults to “vector”.
id_field (str, optional) – Specifies the field to store the id. Defaults to “id”.
use_vector_index (bool, optional) – Toggles the use of a vector index. Works only with SingleStoreDB 8.5 or later. Defaults to False. If set to True, vector_size parameter is required to be set to a proper value.
vector_index_name (str, optional) – Specifies the name of the vector index. Defaults to empty. Will be ignored if use_vector_index is set to False.
vector_index_options (dict, optional) –
Specifies the options for the vector index. Defaults to {}. Will be ignored if use_vector_index is set to False. The options are: index_type (str, optional): Specifies the type of the index.
Defaults to IVF_PQFS.
For more options, please refer to the SingleStoreDB documentation: https://docs.singlestore.com/cloud/reference/sql-reference/vector-functions/vector-indexing/
vector_size (int, optional) – Specifies the size of the vector. Defaults to 1536. Required if use_vector_index is set to True. Should be set to the same value as the size of the vectors stored in the vector_field.
use_full_text_search (bool, optional) – Toggles the use a full-text index on the document content. Defaults to False. If set to True, the table will be created with a full-text index on the content field, and the simularity_search method will all using TEXT_ONLY, FILTER_BY_TEXT, FILTER_BY_VECTOR, and WIGHTED_SUM search strategies. If set to False, the simularity_search method will only allow VECTOR_ONLY search strategy.
pool (Following arguments pertain to the connection)
pool_size (int, optional) – Determines the number of active connections in the pool. Defaults to 5.
max_overflow (int, optional) – Determines the maximum number of connections allowed beyond the pool_size. Defaults to 10.
timeout (float, optional) – Specifies the maximum wait time in seconds for establishing a connection. Defaults to 30.
connection (database)
host (str, optional) – Specifies the hostname, IP address, or URL for the database connection. The default scheme is “mysql”.
user (str, optional) – Database username.
password (str, optional) – Database password.
port (int, optional) – Database port. Defaults to 3306 for non-HTTP connections, 80 for HTTP connections, and 443 for HTTPS connections.
database (str, optional) – Database name.
the (Additional optional arguments provide further customization over)
connection
pure_python (bool, optional) – Toggles the connector mode. If True, operates in pure Python mode.
local_infile (bool, optional) – Allows local file uploads.
charset (str, optional) – Specifies the character set for string values.
ssl_key (str, optional) – Specifies the path of the file containing the SSL key.
ssl_cert (str, optional) – Specifies the path of the file containing the SSL certificate.
ssl_ca (str, optional) – Specifies the path of the file containing the SSL certificate authority.
ssl_cipher (str, optional) – Sets the SSL cipher list.
ssl_disabled (bool, optional) – Disables SSL usage.
ssl_verify_cert (bool, optional) – Verifies the server’s certificate. Automatically enabled if
ssl_ca
is specified.ssl_verify_identity (bool, optional) – Verifies the server’s identity.
conv (dict[int, Callable], optional) – A dictionary of data conversion functions.
credential_type (str, optional) – Specifies the type of authentication to use: auth.PASSWORD, auth.JWT, or auth.BROWSER_SSO.
autocommit (bool, optional) – Enables autocommits.
results_type (str, optional) – Determines the structure of the query results: tuples, namedtuples, dicts.
results_format (str, optional) – Deprecated. This option has been renamed to results_type.
kwargs (Any)
Examples
Basic Usage:
from langchain_openai import OpenAIEmbeddings from langchain_community.vectorstores import SingleStoreDB vectorstore = SingleStoreDB( OpenAIEmbeddings(), host="https://user:password@127.0.0.1:3306/database" )
Advanced Usage:
from langchain_openai import OpenAIEmbeddings from langchain_community.vectorstores import SingleStoreDB vectorstore = SingleStoreDB( OpenAIEmbeddings(), distance_strategy=DistanceStrategy.EUCLIDEAN_DISTANCE, host="127.0.0.1", port=3306, user="user", password="password", database="db", table_name="my_custom_table", pool_size=10, timeout=60, )
Using environment variables:
from langchain_openai import OpenAIEmbeddings from langchain_community.vectorstores import SingleStoreDB os.environ['SINGLESTOREDB_URL'] = 'me:p455w0rd@s2-host.com/my_db' vectorstore = SingleStoreDB(OpenAIEmbeddings())
Using vector index:
from langchain_openai import OpenAIEmbeddings from langchain_community.vectorstores import SingleStoreDB os.environ['SINGLESTOREDB_URL'] = 'me:p455w0rd@s2-host.com/my_db' vectorstore = SingleStoreDB( OpenAIEmbeddings(), use_vector_index=True, )
Using full-text index:
Attributes
embeddings
Access the query embedding object if available.
Methods
__init__
(embedding, *[, distance_strategy, ...])Initialize with necessary components.
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_images
(uris[, metadatas, embeddings, ...])Run images through the embeddings and add to the vectorstore.
add_texts
(texts[, metadatas, embeddings, ...])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.
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 documents from the vectorstore.
drop
()Drop the table and delete all data from the vectorstore.
from_documents
(documents, embedding, **kwargs)Return VectorStore initialized from documents and embeddings.
from_texts
(texts, embedding[, metadatas, ...])Create a SingleStoreDB vectorstore from raw documents. This is a user-friendly interface that: 1. Embeds documents. 2. Creates a new table for the embeddings in SingleStoreDB. 3. Adds the documents to the newly created table. This is intended to be a quick way to get started. :param texts: List of texts to add to the vectorstore. :type texts: List[str] :param embedding: A text embedding model. :type embedding: Embeddings :param metadatas: Optional list of metadatas. Defaults to None. :type metadatas: Optional[List[dict]], optional :param distance_strategy: Determines the strategy employed for calculating the distance between vectors in the embedding space. Defaults to DOT_PRODUCT. Available options are: - DOT_PRODUCT: Computes the scalar product of two vectors. This is the default behavior - EUCLIDEAN_DISTANCE: Computes the Euclidean distance between two vectors. This metric considers the geometric distance in the vector space, and might be more suitable for embeddings that rely on spatial relationships. This metric is not compatible with the WEIGHTED_SUM search strategy. :type distance_strategy: DistanceStrategy, optional :param table_name: Specifies the name of the table in use. Defaults to "embeddings". :type table_name: str, optional :param content_field: Specifies the field to store the content. Defaults to "content". :type content_field: str, optional :param metadata_field: Specifies the field to store metadata. Defaults to "metadata". :type metadata_field: str, optional :param vector_field: Specifies the field to store the vector. Defaults to "vector". :type vector_field: str, optional :param id_field: Specifies the field to store the id. Defaults to "id". :type id_field: str, optional :param use_vector_index: Toggles the use of a vector index. Works only with SingleStoreDB 8.5 or later. Defaults to False. If set to True, vector_size parameter is required to be set to a proper value. :type use_vector_index: bool, optional :param vector_index_name: Specifies the name of the vector index. Defaults to empty. Will be ignored if use_vector_index is set to False. :type vector_index_name: str, optional :param vector_index_options: Specifies the options for the vector index. Defaults to {}. Will be ignored if use_vector_index is set to False. The options are: index_type (str, optional): Specifies the type of the index. Defaults to IVF_PQFS. For more options, please refer to the SingleStoreDB documentation: https://docs.singlestore.com/cloud/reference/sql-reference/vector-functions/vector-indexing/ :type vector_index_options: dict, optional :param vector_size: Specifies the size of the vector. Defaults to 1536. Required if use_vector_index is set to True. Should be set to the same value as the size of the vectors stored in the vector_field. :type vector_size: int, optional :param use_full_text_search: Toggles the use a full-text index on the document content. Defaults to False. If set to True, the table will be created with a full-text index on the content field, and the simularity_search method will all using TEXT_ONLY, FILTER_BY_TEXT, FILTER_BY_VECTOR, and WIGHTED_SUM search strategies. If set to False, the simularity_search method will only allow VECTOR_ONLY search strategy. :type use_full_text_search: bool, optional :param pool_size: Determines the number of active connections in the pool. Defaults to 5. :type pool_size: int, optional :param max_overflow: Determines the maximum number of connections allowed beyond the pool_size. Defaults to 10. :type max_overflow: int, optional :param timeout: Specifies the maximum wait time in seconds for establishing a connection. Defaults to 30. :type timeout: float, optional :param Additional optional arguments provide further customization over the: :param database connection: :param pure_python: Toggles the connector mode. If True, operates in pure Python mode. :type pure_python: bool, optional :param local_infile: Allows local file uploads. :type local_infile: bool, optional :param charset: Specifies the character set for string values. :type charset: str, optional :param ssl_key: Specifies the path of the file containing the SSL key. :type ssl_key: str, optional :param ssl_cert: Specifies the path of the file containing the SSL certificate. :type ssl_cert: str, optional :param ssl_ca: Specifies the path of the file containing the SSL certificate authority. :type ssl_ca: str, optional :param ssl_cipher: Sets the SSL cipher list. :type ssl_cipher: str, optional :param ssl_disabled: Disables SSL usage. :type ssl_disabled: bool, optional :param ssl_verify_cert: Verifies the server's certificate. Automatically enabled if
ssl_ca
is specified. :type ssl_verify_cert: bool, optional :param ssl_verify_identity: Verifies the server's identity. :type ssl_verify_identity: bool, optional :param conv: A dictionary of data conversion functions. :type conv: dict[int, Callable], optional :param credential_type: Specifies the type of authentication to use: auth.PASSWORD, auth.JWT, or auth.BROWSER_SSO. :type credential_type: str, optional :param autocommit: Enables autocommits. :type autocommit: bool, optional :param results_type: Determines the structure of the query results: tuples, namedtuples, dicts. :type results_type: str, optional :param results_format: Deprecated. This option has been renamed to results_type. :type results_format: str, optional.get_by_ids
(ids, /)Get documents by their IDs.
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.
similarity_search
(query[, k, filter, ...])Returns the most similar indexed documents to the query text.
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.
- __init__(embedding: Embeddings, *, distance_strategy: DistanceStrategy = DistanceStrategy.DOT_PRODUCT, table_name: str = 'embeddings', content_field: str = 'content', metadata_field: str = 'metadata', vector_field: str = 'vector', id_field: str = 'id', use_vector_index: bool = False, vector_index_name: str = '', vector_index_options: dict | None = None, vector_size: int = 1536, use_full_text_search: bool = False, pool_size: int = 5, max_overflow: int = 10, timeout: float = 30, **kwargs: Any)[source]#
Initialize with necessary components.
- Parameters:
embedding (Embeddings) – A text embedding model.
distance_strategy (DistanceStrategy, optional) –
Determines the strategy employed for calculating the distance between vectors in the embedding space. Defaults to DOT_PRODUCT. Available options are: - DOT_PRODUCT: Computes the scalar product of two vectors.
This is the default behavior
- EUCLIDEAN_DISTANCE: Computes the Euclidean distance between
two vectors. This metric considers the geometric distance in the vector space, and might be more suitable for embeddings that rely on spatial relationships. This metric is not compatible with the WEIGHTED_SUM search strategy.
table_name (str, optional) – Specifies the name of the table in use. Defaults to “embeddings”.
content_field (str, optional) – Specifies the field to store the content. Defaults to “content”.
metadata_field (str, optional) – Specifies the field to store metadata. Defaults to “metadata”.
vector_field (str, optional) – Specifies the field to store the vector. Defaults to “vector”.
id_field (str, optional) – Specifies the field to store the id. Defaults to “id”.
use_vector_index (bool, optional) – Toggles the use of a vector index. Works only with SingleStoreDB 8.5 or later. Defaults to False. If set to True, vector_size parameter is required to be set to a proper value.
vector_index_name (str, optional) – Specifies the name of the vector index. Defaults to empty. Will be ignored if use_vector_index is set to False.
vector_index_options (dict, optional) –
Specifies the options for the vector index. Defaults to {}. Will be ignored if use_vector_index is set to False. The options are: index_type (str, optional): Specifies the type of the index.
Defaults to IVF_PQFS.
For more options, please refer to the SingleStoreDB documentation: https://docs.singlestore.com/cloud/reference/sql-reference/vector-functions/vector-indexing/
vector_size (int, optional) – Specifies the size of the vector. Defaults to 1536. Required if use_vector_index is set to True. Should be set to the same value as the size of the vectors stored in the vector_field.
use_full_text_search (bool, optional) – Toggles the use a full-text index on the document content. Defaults to False. If set to True, the table will be created with a full-text index on the content field, and the simularity_search method will all using TEXT_ONLY, FILTER_BY_TEXT, FILTER_BY_VECTOR, and WIGHTED_SUM search strategies. If set to False, the simularity_search method will only allow VECTOR_ONLY search strategy.
pool (Following arguments pertain to the connection)
pool_size (int, optional) – Determines the number of active connections in the pool. Defaults to 5.
max_overflow (int, optional) – Determines the maximum number of connections allowed beyond the pool_size. Defaults to 10.
timeout (float, optional) – Specifies the maximum wait time in seconds for establishing a connection. Defaults to 30.
connection (database)
host (str, optional) – Specifies the hostname, IP address, or URL for the database connection. The default scheme is “mysql”.
user (str, optional) – Database username.
password (str, optional) – Database password.
port (int, optional) – Database port. Defaults to 3306 for non-HTTP connections, 80 for HTTP connections, and 443 for HTTPS connections.
database (str, optional) – Database name.
the (Additional optional arguments provide further customization over)
connection
pure_python (bool, optional) – Toggles the connector mode. If True, operates in pure Python mode.
local_infile (bool, optional) – Allows local file uploads.
charset (str, optional) – Specifies the character set for string values.
ssl_key (str, optional) – Specifies the path of the file containing the SSL key.
ssl_cert (str, optional) – Specifies the path of the file containing the SSL certificate.
ssl_ca (str, optional) – Specifies the path of the file containing the SSL certificate authority.
ssl_cipher (str, optional) – Sets the SSL cipher list.
ssl_disabled (bool, optional) – Disables SSL usage.
ssl_verify_cert (bool, optional) – Verifies the server’s certificate. Automatically enabled if
ssl_ca
is specified.ssl_verify_identity (bool, optional) – Verifies the server’s identity.
conv (dict[int, Callable], optional) – A dictionary of data conversion functions.
credential_type (str, optional) – Specifies the type of authentication to use: auth.PASSWORD, auth.JWT, or auth.BROWSER_SSO.
autocommit (bool, optional) – Enables autocommits.
results_type (str, optional) – Determines the structure of the query results: tuples, namedtuples, dicts.
results_format (str, optional) – Deprecated. This option has been renamed to results_type.
kwargs (Any)
Examples
Basic Usage:
from langchain_openai import OpenAIEmbeddings from langchain_community.vectorstores import SingleStoreDB vectorstore = SingleStoreDB( OpenAIEmbeddings(), host="https://user:password@127.0.0.1:3306/database" )
Advanced Usage:
from langchain_openai import OpenAIEmbeddings from langchain_community.vectorstores import SingleStoreDB vectorstore = SingleStoreDB( OpenAIEmbeddings(), distance_strategy=DistanceStrategy.EUCLIDEAN_DISTANCE, host="127.0.0.1", port=3306, user="user", password="password", database="db", table_name="my_custom_table", pool_size=10, timeout=60, )
Using environment variables:
from langchain_openai import OpenAIEmbeddings from langchain_community.vectorstores import SingleStoreDB os.environ['SINGLESTOREDB_URL'] = 'me:p455w0rd@s2-host.com/my_db' vectorstore = SingleStoreDB(OpenAIEmbeddings())
Using vector index:
from langchain_openai import OpenAIEmbeddings from langchain_community.vectorstores import SingleStoreDB os.environ['SINGLESTOREDB_URL'] = 'me:p455w0rd@s2-host.com/my_db' vectorstore = SingleStoreDB( OpenAIEmbeddings(), use_vector_index=True, )
Using full-text index:
- 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 (list[dict] | None) – Optional list of metadatas associated with the texts. Default is None.
ids (list[str] | None) – 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_images(uris: List[str], metadatas: List[dict] | None = None, embeddings: List[List[float]] | None = None, return_ids: bool = False, **kwargs: Any) List[str] [source]#
Run images through the embeddings and add to the vectorstore.
- Parameters:
List[str] (uris) – File path to images. Each URI will be added to the vectorstore as document content.
metadatas (Optional[List[dict]], optional) – Optional list of metadatas. Defaults to None.
embeddings (Optional[List[List[float]]], optional) – Optional pre-generated embeddings. Defaults to None.
uris (List[str])
return_ids (bool)
kwargs (Any)
- Returns:
- list of document ids added to the vectorstore
if return_ids is True. Otherwise, an empty list.
- Return type:
List[str]
- add_texts(texts: Iterable[str], metadatas: List[dict] | None = None, embeddings: List[List[float]] | None = None, return_ids: bool = False, **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.
embeddings (Optional[List[List[float]]], optional) – Optional pre-generated embeddings. Defaults to None.
return_ids (bool)
kwargs (Any)
- Returns:
- list of document ids added to the vectorstore
if return_ids is True. Otherwise, an empty list.
- 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) 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: list[dict] | None = None, *, ids: list[str] | None = 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 (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:
- 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 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: List[str] | None = None, **kwargs: Any) bool | None [source]#
Delete documents from the vectorstore.
- Parameters:
ids (List[str], optional) – List of document ids to delete. If None, all documents will be deleted. Defaults to None.
kwargs (Any)
- Returns:
True if deletion was successful, False otherwise.
- Return type:
bool
- drop() None [source]#
Drop the table and delete all data from the vectorstore. Vector store will be unusable after this operation.
- 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: Embeddings, metadatas: List[dict] | None = None, distance_strategy: DistanceStrategy = DistanceStrategy.DOT_PRODUCT, table_name: str = 'embeddings', content_field: str = 'content', metadata_field: str = 'metadata', vector_field: str = 'vector', id_field: str = 'id', use_vector_index: bool = False, vector_index_name: str = '', vector_index_options: dict | None = None, vector_size: int = 1536, use_full_text_search: bool = False, pool_size: int = 5, max_overflow: int = 10, timeout: float = 30, **kwargs: Any) SingleStoreDB [source]#
Create a SingleStoreDB vectorstore from raw documents. This is a user-friendly interface that:
Embeds documents.
Creates a new table for the embeddings in SingleStoreDB.
Adds the documents to the newly created table.
This is intended to be a quick way to get started. :param texts: List of texts to add to the vectorstore. :type texts: List[str] :param embedding: A text embedding model. :type embedding: Embeddings :param metadatas: Optional list of metadatas.
Defaults to None.
- Parameters:
distance_strategy (DistanceStrategy, optional) –
Determines the strategy employed for calculating the distance between vectors in the embedding space. Defaults to DOT_PRODUCT. Available options are: - DOT_PRODUCT: Computes the scalar product of two vectors.
This is the default behavior
- EUCLIDEAN_DISTANCE: Computes the Euclidean distance between
two vectors. This metric considers the geometric distance in the vector space, and might be more suitable for embeddings that rely on spatial relationships. This metric is not compatible with the WEIGHTED_SUM search strategy.
table_name (str, optional) – Specifies the name of the table in use. Defaults to “embeddings”.
content_field (str, optional) – Specifies the field to store the content. Defaults to “content”.
metadata_field (str, optional) – Specifies the field to store metadata. Defaults to “metadata”.
vector_field (str, optional) – Specifies the field to store the vector. Defaults to “vector”.
id_field (str, optional) – Specifies the field to store the id. Defaults to “id”.
use_vector_index (bool, optional) – Toggles the use of a vector index. Works only with SingleStoreDB 8.5 or later. Defaults to False. If set to True, vector_size parameter is required to be set to a proper value.
vector_index_name (str, optional) – Specifies the name of the vector index. Defaults to empty. Will be ignored if use_vector_index is set to False.
vector_index_options (dict, optional) –
Specifies the options for the vector index. Defaults to {}. Will be ignored if use_vector_index is set to False. The options are: index_type (str, optional): Specifies the type of the index.
Defaults to IVF_PQFS.
For more options, please refer to the SingleStoreDB documentation: https://docs.singlestore.com/cloud/reference/sql-reference/vector-functions/vector-indexing/
vector_size (int, optional) – Specifies the size of the vector. Defaults to 1536. Required if use_vector_index is set to True. Should be set to the same value as the size of the vectors stored in the vector_field.
use_full_text_search (bool, optional) – Toggles the use a full-text index on the document content. Defaults to False. If set to True, the table will be created with a full-text index on the content field, and the simularity_search method will all using TEXT_ONLY, FILTER_BY_TEXT, FILTER_BY_VECTOR, and WIGHTED_SUM search strategies. If set to False, the simularity_search method will only allow VECTOR_ONLY search strategy.
pool_size (int, optional) – Determines the number of active connections in the pool. Defaults to 5.
max_overflow (int, optional) – Determines the maximum number of connections allowed beyond the pool_size. Defaults to 10.
timeout (float, optional) – Specifies the maximum wait time in seconds for establishing a connection. Defaults to 30.
the (Additional optional arguments provide further customization over)
connection (database)
pure_python (bool, optional) – Toggles the connector mode. If True, operates in pure Python mode.
local_infile (bool, optional) – Allows local file uploads.
charset (str, optional) – Specifies the character set for string values.
ssl_key (str, optional) – Specifies the path of the file containing the SSL key.
ssl_cert (str, optional) – Specifies the path of the file containing the SSL certificate.
ssl_ca (str, optional) – Specifies the path of the file containing the SSL certificate authority.
ssl_cipher (str, optional) – Sets the SSL cipher list.
ssl_disabled (bool, optional) – Disables SSL usage.
ssl_verify_cert (bool, optional) – Verifies the server’s certificate. Automatically enabled if
ssl_ca
is specified.ssl_verify_identity (bool, optional) – Verifies the server’s identity.
conv (dict[int, Callable], optional) – A dictionary of data conversion functions.
credential_type (str, optional) – Specifies the type of authentication to use: auth.PASSWORD, auth.JWT, or auth.BROWSER_SSO.
autocommit (bool, optional) – Enables autocommits.
results_type (str, optional) – Determines the structure of the query results: tuples, namedtuples, dicts.
results_format (str, optional) – Deprecated. This option has been renamed to results_type.
texts (List[str])
embedding (Embeddings)
metadatas (Optional[List[dict]], optional)
kwargs (Any)
- Return type:
Example
from langchain_community.vectorstores import SingleStoreDB from langchain_openai import OpenAIEmbeddings s2 = SingleStoreDB.from_texts( texts, OpenAIEmbeddings(), host="username:password@localhost:3306/database" )
- 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]
Added in version 0.2.11.
- 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.
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]
- similarity_search(query: str, k: int = 4, filter: dict | None = None, search_strategy: SearchStrategy = SearchStrategy.VECTOR_ONLY, filter_threshold: float = 0, text_weight: float = 0.5, vector_weight: float = 0.5, vector_select_count_multiplier: int = 10, **kwargs: Any) List[Document] [source]#
Returns the most similar indexed documents to the query text.
Uses cosine similarity.
- Parameters:
query (str) – The query text for which to find similar documents.
k (int) – The number of documents to return. Default is 4.
filter (dict) – A dictionary of metadata fields and values to filter by. Default is None.
search_strategy (SearchStrategy) –
The search strategy to use. Default is SearchStrategy.VECTOR_ONLY. Available options are: - SearchStrategy.VECTOR_ONLY: Searches only by vector similarity. - SearchStrategy.TEXT_ONLY: Searches only by text similarity. This
option is only available if use_full_text_search is True.
- SearchStrategy.FILTER_BY_TEXT: Filters by text similarity and
searches by vector similarity. This option is only available if use_full_text_search is True.
- SearchStrategy.FILTER_BY_VECTOR: Filters by vector similarity and
searches by text similarity. This option is only available if use_full_text_search is True.
- SearchStrategy.WEIGHTED_SUM: Searches by a weighted sum of text and
vector similarity. This option is only available if use_full_text_search is True and distance_strategy is DOT_PRODUCT.
filter_threshold (float) – The threshold for filtering by text or vector similarity. Default is 0. This option has effect only if search_strategy is SearchStrategy.FILTER_BY_TEXT or SearchStrategy.FILTER_BY_VECTOR.
text_weight (float) – The weight of text similarity in the weighted sum search strategy. Default is 0.5. This option has effect only if search_strategy is SearchStrategy.WEIGHTED_SUM.
vector_weight (float) – The weight of vector similarity in the weighted sum search strategy. Default is 0.5. This option has effect only if search_strategy is SearchStrategy.WEIGHTED_SUM.
vector_select_count_multiplier (int) – The multiplier for the number of vectors to select when using the vector index. Default is 10. This parameter has effect only if use_vector_index is True and search_strategy is SearchStrategy.WEIGHTED_SUM or SearchStrategy.FILTER_BY_TEXT. The number of vectors selected will be k * vector_select_count_multiplier. This is needed due to the limitations of the vector index.
kwargs (Any)
- Returns:
A list of documents that are most similar to the query text.
- Return type:
List[Document]
Examples
Basic Usage: .. code-block:: python
from langchain_community.vectorstores import SingleStoreDB from langchain_openai import OpenAIEmbeddings
- s2 = SingleStoreDB.from_documents(
docs, OpenAIEmbeddings(), host=”username:password@localhost:3306/database”
) results = s2.similarity_search(“query text”, 1,
{“metadata_field”: “metadata_value”})
Different Search Strategies: .. code-block:: python
from langchain_community.vectorstores import SingleStoreDB from langchain_openai import OpenAIEmbeddings
- s2 = SingleStoreDB.from_documents(
docs, OpenAIEmbeddings(), host=”username:password@localhost:3306/database”, use_full_text_search=True, use_vector_index=True,
) results = s2.similarity_search(“query text”, 1,
search_strategy=SingleStoreDB.SearchStrategy.FILTER_BY_TEXT, filter_threshold=0.5)
Weighted Sum Search Strategy: .. code-block:: python
from langchain_community.vectorstores import SingleStoreDB from langchain_openai import OpenAIEmbeddings
- s2 = SingleStoreDB.from_documents(
docs, OpenAIEmbeddings(), host=”username:password@localhost:3306/database”, use_full_text_search=True, use_vector_index=True,
) results = s2.similarity_search(“query text”, 1,
search_strategy=SingleStoreDB.SearchStrategy.WEIGHTED_SUM, text_weight=0.3, vector_weight=0.7)
- similarity_search_by_vector(embedding: list[float], k: int = 4, **kwargs: Any) list[Document] #
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]
- 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, search_strategy: SearchStrategy = SearchStrategy.VECTOR_ONLY, filter_threshold: float = 1, text_weight: float = 0.5, vector_weight: float = 0.5, vector_select_count_multiplier: int = 10, **kwargs: Any) List[Tuple[Document, float]] [source]#
Return docs most similar to query. Uses cosine similarity.
- Parameters:
query (str) – Text to look up documents similar to.
k (int) – Number of Documents to return. Defaults to 4.
filter (Optional[dict]) – A dictionary of metadata fields and values to filter by. Defaults to None.
search_strategy (SearchStrategy) –
The search strategy to use. Default is SearchStrategy.VECTOR_ONLY. Available options are: - SearchStrategy.VECTOR_ONLY: Searches only by vector similarity. - SearchStrategy.TEXT_ONLY: Searches only by text similarity. This
option is only available if use_full_text_search is True.
- SearchStrategy.FILTER_BY_TEXT: Filters by text similarity and
searches by vector similarity. This option is only available if use_full_text_search is True.
- SearchStrategy.FILTER_BY_VECTOR: Filters by vector similarity and
searches by text similarity. This option is only available if use_full_text_search is True.
- SearchStrategy.WEIGHTED_SUM: Searches by a weighted sum of text and
vector similarity. This option is only available if use_full_text_search is True and distance_strategy is DOT_PRODUCT.
filter_threshold (float) – The threshold for filtering by text or vector similarity. Default is 0. This option has effect only if search_strategy is SearchStrategy.FILTER_BY_TEXT or SearchStrategy.FILTER_BY_VECTOR.
text_weight (float) – The weight of text similarity in the weighted sum search strategy. Default is 0.5. This option has effect only if search_strategy is SearchStrategy.WEIGHTED_SUM.
vector_weight (float) – The weight of vector similarity in the weighted sum search strategy. Default is 0.5. This option has effect only if search_strategy is SearchStrategy.WEIGHTED_SUM.
vector_select_count_multiplier (int) – The multiplier for the number of vectors to select when using the vector index. Default is 10. This parameter has effect only if use_vector_index is True and search_strategy is SearchStrategy.WEIGHTED_SUM or SearchStrategy.FILTER_BY_TEXT. The number of vectors selected will be k * vector_select_count_multiplier. This is needed due to the limitations of the vector index.
kwargs (Any)
- Returns:
List of Documents most similar to the query and score for each document.
- Raises:
ValueError – If the search strategy is not supported with the distance strategy.
- Return type:
List[Tuple[Document, float]]
Examples
Basic Usage: .. code-block:: python
from langchain_community.vectorstores import SingleStoreDB from langchain_openai import OpenAIEmbeddings
- s2 = SingleStoreDB.from_documents(
docs, OpenAIEmbeddings(), host=”username:password@localhost:3306/database”
) results = s2.similarity_search_with_score(“query text”, 1,
{“metadata_field”: “metadata_value”})
Different Search Strategies:
from langchain_community.vectorstores import SingleStoreDB from langchain_openai import OpenAIEmbeddings s2 = SingleStoreDB.from_documents( docs, OpenAIEmbeddings(), host="username:password@localhost:3306/database", use_full_text_search=True, use_vector_index=True, ) results = s2.similarity_search_with_score("query text", 1, search_strategy=SingleStoreDB.SearchStrategy.FILTER_BY_VECTOR, filter_threshold=0.5)
Weighted Sum Search Strategy: .. code-block:: python
from langchain_community.vectorstores import SingleStoreDB from langchain_openai import OpenAIEmbeddings
- s2 = SingleStoreDB.from_documents(
docs, OpenAIEmbeddings(), host=”username:password@localhost:3306/database”, use_full_text_search=True, use_vector_index=True,
) results = s2.similarity_search_with_score(“query text”, 1,
search_strategy=SingleStoreDB.SearchStrategy.WEIGHTED_SUM, text_weight=0.3, vector_weight=0.7)
Examples using SingleStoreDB