langchain.vectorstores.singlestoredb.SingleStoreDB

class langchain.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', 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.

  • 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”.

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

Examples

Basic Usage:

from langchain.embeddings import OpenAIEmbeddings
from langchain.vectorstores import SingleStoreDB

vectorstore = SingleStoreDB(
    OpenAIEmbeddings(),
    host="https://user:password@127.0.0.1:3306/database"
)

Advanced Usage:

from langchain.embeddings import OpenAIEmbeddings
from langchain.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.embeddings import OpenAIEmbeddings
from langchain.vectorstores import SingleStoreDB

os.environ['SINGLESTOREDB_URL'] = 'me:p455w0rd@s2-host.com/my_db'
vectorstore = SingleStoreDB(OpenAIEmbeddings())

Attributes

embeddings

Access the query embedding object if available.

Methods

__init__(embedding, *[, distance_strategy, ...])

Initialize with necessary components.

aadd_documents(documents, **kwargs)

Run more documents through the embeddings and add to the vectorstore.

aadd_texts(texts[, metadatas])

Run more texts through the embeddings and add to the vectorstore.

add_documents(documents, **kwargs)

Run more documents through the embeddings and add to the vectorstore.

add_texts(texts[, metadatas, embeddings])

Add more texts to the vectorstore.

adelete([ids])

Delete by vector ID or other criteria.

afrom_documents(documents, embedding, **kwargs)

Return VectorStore initialized from documents and embeddings.

afrom_texts(texts, embedding[, metadatas])

Return VectorStore initialized from texts and embeddings.

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

Return docs selected using the maximal marginal relevance.

amax_marginal_relevance_search_by_vector(...)

Return docs selected using the maximal marginal relevance.

as_retriever(**kwargs)

Return VectorStoreRetriever initialized from this VectorStore.

asearch(query, search_type, **kwargs)

Return docs most similar to query using specified search type.

asimilarity_search(query[, k])

Return docs most similar to query.

asimilarity_search_by_vector(embedding[, k])

Return docs most similar to embedding vector.

asimilarity_search_with_relevance_scores(query)

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

asimilarity_search_with_score(*args, **kwargs)

Run similarity search with distance asynchronously.

delete([ids])

Delete by vector ID or other criteria.

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. .. rubric:: Example.

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 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.

similarity_search_with_relevance_scores(query)

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

similarity_search_with_score(query[, k, filter])

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', 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.

  • 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”.

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

Examples

Basic Usage:

from langchain.embeddings import OpenAIEmbeddings
from langchain.vectorstores import SingleStoreDB

vectorstore = SingleStoreDB(
    OpenAIEmbeddings(),
    host="https://user:password@127.0.0.1:3306/database"
)

Advanced Usage:

from langchain.embeddings import OpenAIEmbeddings
from langchain.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.embeddings import OpenAIEmbeddings
from langchain.vectorstores import SingleStoreDB

os.environ['SINGLESTOREDB_URL'] = 'me:p455w0rd@s2-host.com/my_db'
vectorstore = SingleStoreDB(OpenAIEmbeddings())
async aadd_documents(documents: List[Document], **kwargs: Any) List[str]

Run more documents through the embeddings and add to the vectorstore.

Parameters

(List[Document] (documents) – Documents to add to the vectorstore.

Returns

List of IDs of the added texts.

Return type

List[str]

async aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) List[str]

Run more texts through the embeddings and add to the vectorstore.

add_documents(documents: List[Document], **kwargs: Any) List[str]

Run more documents through the embeddings and add to the vectorstore.

Parameters

(List[Document] (documents) – Documents to add to the vectorstore.

Returns

List of IDs of the added texts.

Return type

List[str]

add_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, embeddings: Optional[List[List[float]]] = None, **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.

Returns

empty list

Return type

List[str]

async adelete(ids: Optional[List[str]] = None, **kwargs: Any) Optional[bool]

Delete by vector ID or other criteria.

Parameters
  • ids – List of ids to delete.

  • **kwargs – 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

Return VectorStore initialized from documents and embeddings.

async classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) VST

Return VectorStore initialized from texts and embeddings.

Return docs selected using the maximal marginal relevance.

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]

Return docs selected using the maximal marginal relevance.

as_retriever(**kwargs: Any) VectorStoreRetriever

Return VectorStoreRetriever initialized from this VectorStore.

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

VectorStoreRetriever

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]

Return docs most similar to query using specified search type.

Return docs most similar to query.

async asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) List[Document]

Return docs most similar to embedding vector.

async asimilarity_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], asynchronously.

0 is dissimilar, 1 is most similar.

Parameters
  • query – input text

  • k – Number of Documents to return. Defaults to 4.

  • **kwargs

    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)

async asimilarity_search_with_score(*args: Any, **kwargs: Any) List[Tuple[Document, float]]

Run similarity search with distance asynchronously.

delete(ids: Optional[List[str]] = None, **kwargs: Any) Optional[bool]

Delete by vector ID or other criteria.

Parameters
  • ids – List of ids to delete.

  • **kwargs – Other keyword arguments that subclasses might use.

Returns

True if deletion is successful, False otherwise, None if not implemented.

Return type

Optional[bool]

classmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) VST

Return VectorStore initialized from documents and embeddings.

classmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, distance_strategy: DistanceStrategy = DistanceStrategy.DOT_PRODUCT, table_name: str = 'embeddings', content_field: str = 'content', metadata_field: str = 'metadata', vector_field: str = 'vector', 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:

  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. .. rubric:: Example

Return docs selected using the maximal marginal relevance.

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

Parameters
  • query – Text to look up documents similar to.

  • k – Number of Documents to return. Defaults to 4.

  • fetch_k – Number of Documents to fetch to pass to MMR algorithm.

  • lambda_mult – Number between 0 and 1 that determines the degree of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. Defaults to 0.5.

Returns

List of Documents selected by maximal marginal relevance.

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

  • k – Number of Documents to return. Defaults to 4.

  • fetch_k – Number of Documents to fetch to pass to MMR algorithm.

  • lambda_mult – Number between 0 and 1 that determines the degree of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. Defaults to 0.5.

Returns

List of Documents selected by maximal marginal relevance.

search(query: str, search_type: str, **kwargs: Any) List[Document]

Return docs most similar to query using specified search type.

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.

Returns

A list of documents that are most similar to the query text.

Return type

List[Document]

Examples

similarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) List[Document]

Return docs most similar to embedding vector.

Parameters
  • embedding – Embedding to look up documents similar to.

  • k – Number of Documents to return. Defaults to 4.

Returns

List of Documents most similar to the query vector.

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 – input text

  • k – Number of Documents to return. Defaults to 4.

  • **kwargs

    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)

similarity_search_with_score(query: str, k: int = 4, filter: Optional[dict] = None) List[Tuple[Document, float]][source]

Return docs most similar to query. Uses cosine similarity.

Parameters
  • query – Text to look up documents similar to.

  • k – Number of Documents to return. Defaults to 4.

  • filter – A dictionary of metadata fields and values to filter by. Defaults to None.

Returns

List of Documents most similar to the query and score for each

Examples using SingleStoreDB