Skip to content

Python API Reference (SaaS)

This section contains the API reference for the LanceDB Cloud Python API.

Installation

pip install lancedb

Connection

lancedb.connect

connect(uri: URI, *, api_key: Optional[str] = None, region: str = 'us-east-1', host_override: Optional[str] = None, read_consistency_interval: Optional[timedelta] = None, request_thread_pool: Optional[Union[int, ThreadPoolExecutor]] = None, client_config: Union[ClientConfig, Dict[str, Any], None] = None, storage_options: Optional[Dict[str, str]] = None, **kwargs: Any) -> DBConnection

Connect to a LanceDB database.

Parameters:

  • uri (URI) –

    The uri of the database.

  • api_key (Optional[str], default: None ) –

    If presented, connect to LanceDB cloud. Otherwise, connect to a database on file system or cloud storage. Can be set via environment variable LANCEDB_API_KEY.

  • region (str, default: 'us-east-1' ) –

    The region to use for LanceDB Cloud.

  • host_override (Optional[str], default: None ) –

    The override url for LanceDB Cloud.

  • read_consistency_interval (Optional[timedelta], default: None ) –

    (For LanceDB OSS only) The interval at which to check for updates to the table from other processes. If None, then consistency is not checked. For performance reasons, this is the default. For strong consistency, set this to zero seconds. Then every read will check for updates from other processes. As a compromise, you can set this to a non-zero timedelta for eventual consistency. If more than that interval has passed since the last check, then the table will be checked for updates. Note: this consistency only applies to read operations. Write operations are always consistent.

  • client_config (Union[ClientConfig, Dict[str, Any], None], default: None ) –

    Configuration options for the LanceDB Cloud HTTP client. If a dict, then the keys are the attributes of the ClientConfig class. If None, then the default configuration is used.

  • storage_options (Optional[Dict[str, str]], default: None ) –

    Additional options for the storage backend. See available options at https://lancedb.github.io/lancedb/guides/storage/

Examples:

For a local directory, provide a path for the database:

>>> import lancedb
>>> db = lancedb.connect("~/.lancedb")

For object storage, use a URI prefix:

>>> db = lancedb.connect("s3://my-bucket/lancedb",
...                      storage_options={"aws_access_key_id": "***"})

Connect to LanceDB cloud:

>>> db = lancedb.connect("db://my_database", api_key="ldb_...",
...                      client_config={"retry_config": {"retries": 5}})

Returns:

  • conn ( DBConnection ) –

    A connection to a LanceDB database.

Source code in lancedb/__init__.py
def connect(
    uri: URI,
    *,
    api_key: Optional[str] = None,
    region: str = "us-east-1",
    host_override: Optional[str] = None,
    read_consistency_interval: Optional[timedelta] = None,
    request_thread_pool: Optional[Union[int, ThreadPoolExecutor]] = None,
    client_config: Union[ClientConfig, Dict[str, Any], None] = None,
    storage_options: Optional[Dict[str, str]] = None,
    **kwargs: Any,
) -> DBConnection:
    """Connect to a LanceDB database.

    Parameters
    ----------
    uri: str or Path
        The uri of the database.
    api_key: str, optional
        If presented, connect to LanceDB cloud.
        Otherwise, connect to a database on file system or cloud storage.
        Can be set via environment variable `LANCEDB_API_KEY`.
    region: str, default "us-east-1"
        The region to use for LanceDB Cloud.
    host_override: str, optional
        The override url for LanceDB Cloud.
    read_consistency_interval: timedelta, default None
        (For LanceDB OSS only)
        The interval at which to check for updates to the table from other
        processes. If None, then consistency is not checked. For performance
        reasons, this is the default. For strong consistency, set this to
        zero seconds. Then every read will check for updates from other
        processes. As a compromise, you can set this to a non-zero timedelta
        for eventual consistency. If more than that interval has passed since
        the last check, then the table will be checked for updates. Note: this
        consistency only applies to read operations. Write operations are
        always consistent.
    client_config: ClientConfig or dict, optional
        Configuration options for the LanceDB Cloud HTTP client. If a dict, then
        the keys are the attributes of the ClientConfig class. If None, then the
        default configuration is used.
    storage_options: dict, optional
        Additional options for the storage backend. See available options at
        <https://lancedb.github.io/lancedb/guides/storage/>

    Examples
    --------

    For a local directory, provide a path for the database:

    >>> import lancedb
    >>> db = lancedb.connect("~/.lancedb")

    For object storage, use a URI prefix:

    >>> db = lancedb.connect("s3://my-bucket/lancedb",
    ...                      storage_options={"aws_access_key_id": "***"})

    Connect to LanceDB cloud:

    >>> db = lancedb.connect("db://my_database", api_key="ldb_...",
    ...                      client_config={"retry_config": {"retries": 5}})

    Returns
    -------
    conn : DBConnection
        A connection to a LanceDB database.
    """
    from .remote.db import RemoteDBConnection

    if isinstance(uri, str) and uri.startswith("db://"):
        if api_key is None:
            api_key = os.environ.get("LANCEDB_API_KEY")
        if api_key is None:
            raise ValueError(f"api_key is required to connected LanceDB cloud: {uri}")
        if isinstance(request_thread_pool, int):
            request_thread_pool = ThreadPoolExecutor(request_thread_pool)
        return RemoteDBConnection(
            uri,
            api_key,
            region,
            host_override,
            # TODO: remove this (deprecation warning downstream)
            request_thread_pool=request_thread_pool,
            client_config=client_config,
            storage_options=storage_options,
            **kwargs,
        )

    if kwargs:
        raise ValueError(f"Unknown keyword arguments: {kwargs}")
    return LanceDBConnection(
        uri,
        read_consistency_interval=read_consistency_interval,
        storage_options=storage_options,
    )

lancedb.remote.db.RemoteDBConnection

Bases: DBConnection

A connection to a remote LanceDB database.

Source code in lancedb/remote/db.py
class RemoteDBConnection(DBConnection):
    """A connection to a remote LanceDB database."""

    def __init__(
        self,
        db_url: str,
        api_key: str,
        region: str,
        host_override: Optional[str] = None,
        request_thread_pool: Optional[ThreadPoolExecutor] = None,
        client_config: Union[ClientConfig, Dict[str, Any], None] = None,
        connection_timeout: Optional[float] = None,
        read_timeout: Optional[float] = None,
        storage_options: Optional[Dict[str, str]] = None,
    ):
        """Connect to a remote LanceDB database."""
        if isinstance(client_config, dict):
            client_config = ClientConfig(**client_config)
        elif client_config is None:
            client_config = ClientConfig()

        # These are legacy options from the old Python-based client. We keep them
        # here for backwards compatibility, but will remove them in a future release.
        if request_thread_pool is not None:
            warnings.warn(
                "request_thread_pool is no longer used and will be removed in "
                "a future release.",
                DeprecationWarning,
            )

        if connection_timeout is not None:
            warnings.warn(
                "connection_timeout is deprecated and will be removed in a future "
                "release. Please use client_config.timeout_config.connect_timeout "
                "instead.",
                DeprecationWarning,
            )
            client_config.timeout_config.connect_timeout = timedelta(
                seconds=connection_timeout
            )

        if read_timeout is not None:
            warnings.warn(
                "read_timeout is deprecated and will be removed in a future release. "
                "Please use client_config.timeout_config.read_timeout instead.",
                DeprecationWarning,
            )
            client_config.timeout_config.read_timeout = timedelta(seconds=read_timeout)

        parsed = urlparse(db_url)
        if parsed.scheme != "db":
            raise ValueError(f"Invalid scheme: {parsed.scheme}, only accepts db://")
        self.db_name = parsed.netloc

        self.client_config = client_config

        self._conn = LOOP.run(
            connect_async(
                db_url,
                api_key=api_key,
                region=region,
                host_override=host_override,
                client_config=client_config,
                storage_options=storage_options,
            )
        )

    def __repr__(self) -> str:
        return f"RemoteConnect(name={self.db_name})"

    @override
    def table_names(
        self, page_token: Optional[str] = None, limit: int = 10
    ) -> Iterable[str]:
        """List the names of all tables in the database.

        Parameters
        ----------
        page_token: str
            The last token to start the new page.
        limit: int, default 10
            The maximum number of tables to return for each page.

        Returns
        -------
        An iterator of table names.
        """
        return LOOP.run(self._conn.table_names(start_after=page_token, limit=limit))

    @override
    def open_table(
        self,
        name: str,
        *,
        storage_options: Optional[Dict[str, str]] = None,
        index_cache_size: Optional[int] = None,
    ) -> Table:
        """Open a Lance Table in the database.

        Parameters
        ----------
        name: str
            The name of the table.

        Returns
        -------
        A LanceTable object representing the table.
        """
        from .table import RemoteTable

        if index_cache_size is not None:
            logging.info(
                "index_cache_size is ignored in LanceDb Cloud"
                " (there is no local cache to configure)"
            )

        table = LOOP.run(self._conn.open_table(name))
        return RemoteTable(table, self.db_name)

    @override
    def create_table(
        self,
        name: str,
        data: DATA = None,
        schema: Optional[Union[pa.Schema, LanceModel]] = None,
        on_bad_vectors: str = "error",
        fill_value: float = 0.0,
        mode: Optional[str] = None,
        embedding_functions: Optional[List[EmbeddingFunctionConfig]] = None,
    ) -> Table:
        """Create a [Table][lancedb.table.Table] in the database.

        Parameters
        ----------
        name: str
            The name of the table.
        data: The data to initialize the table, *optional*
            User must provide at least one of `data` or `schema`.
            Acceptable types are:

            - dict or list-of-dict

            - pandas.DataFrame

            - pyarrow.Table or pyarrow.RecordBatch
        schema: The schema of the table, *optional*
            Acceptable types are:

            - pyarrow.Schema

            - [LanceModel][lancedb.pydantic.LanceModel]
        on_bad_vectors: str, default "error"
            What to do if any of the vectors are not the same size or contains NaNs.
            One of "error", "drop", "fill".
        fill_value: float
            The value to use when filling vectors. Only used if on_bad_vectors="fill".

        Returns
        -------
        LanceTable
            A reference to the newly created table.

        !!! note

            The vector index won't be created by default.
            To create the index, call the `create_index` method on the table.

        Examples
        --------

        Can create with list of tuples or dictionaries:

        >>> import lancedb
        >>> db = lancedb.connect("db://...", api_key="...", # doctest: +SKIP
        ...                      region="...")              # doctest: +SKIP
        >>> data = [{"vector": [1.1, 1.2], "lat": 45.5, "long": -122.7},
        ...         {"vector": [0.2, 1.8], "lat": 40.1, "long":  -74.1}]
        >>> db.create_table("my_table", data) # doctest: +SKIP
        LanceTable(my_table)

        You can also pass a pandas DataFrame:

        >>> import pandas as pd
        >>> data = pd.DataFrame({
        ...    "vector": [[1.1, 1.2], [0.2, 1.8]],
        ...    "lat": [45.5, 40.1],
        ...    "long": [-122.7, -74.1]
        ... })
        >>> db.create_table("table2", data) # doctest: +SKIP
        LanceTable(table2)

        >>> custom_schema = pa.schema([
        ...   pa.field("vector", pa.list_(pa.float32(), 2)),
        ...   pa.field("lat", pa.float32()),
        ...   pa.field("long", pa.float32())
        ... ])
        >>> db.create_table("table3", data, schema = custom_schema) # doctest: +SKIP
        LanceTable(table3)

        It is also possible to create an table from `[Iterable[pa.RecordBatch]]`:

        >>> import pyarrow as pa
        >>> def make_batches():
        ...     for i in range(5):
        ...         yield pa.RecordBatch.from_arrays(
        ...             [
        ...                 pa.array([[3.1, 4.1], [5.9, 26.5]],
        ...                     pa.list_(pa.float32(), 2)),
        ...                 pa.array(["foo", "bar"]),
        ...                 pa.array([10.0, 20.0]),
        ...             ],
        ...             ["vector", "item", "price"],
        ...         )
        >>> schema=pa.schema([
        ...     pa.field("vector", pa.list_(pa.float32(), 2)),
        ...     pa.field("item", pa.utf8()),
        ...     pa.field("price", pa.float32()),
        ... ])
        >>> db.create_table("table4", make_batches(), schema=schema) # doctest: +SKIP
        LanceTable(table4)

        """
        validate_table_name(name)
        if embedding_functions is not None:
            logging.warning(
                "embedding_functions is not yet supported on LanceDB Cloud."
                "Please vote https://github.com/lancedb/lancedb/issues/626 "
                "for this feature."
            )

        from .table import RemoteTable

        table = LOOP.run(
            self._conn.create_table(
                name,
                data,
                mode=mode,
                schema=schema,
                on_bad_vectors=on_bad_vectors,
                fill_value=fill_value,
            )
        )
        return RemoteTable(table, self.db_name)

    @override
    def drop_table(self, name: str):
        """Drop a table from the database.

        Parameters
        ----------
        name: str
            The name of the table.
        """
        LOOP.run(self._conn.drop_table(name))

    @override
    def rename_table(self, cur_name: str, new_name: str):
        """Rename a table in the database.

        Parameters
        ----------
        cur_name: str
            The current name of the table.
        new_name: str
            The new name of the table.
        """
        LOOP.run(self._conn.rename_table(cur_name, new_name))

    async def close(self):
        """Close the connection to the database."""
        self._client.close()

__init__

__init__(db_url: str, api_key: str, region: str, host_override: Optional[str] = None, request_thread_pool: Optional[ThreadPoolExecutor] = None, client_config: Union[ClientConfig, Dict[str, Any], None] = None, connection_timeout: Optional[float] = None, read_timeout: Optional[float] = None, storage_options: Optional[Dict[str, str]] = None)

Connect to a remote LanceDB database.

Source code in lancedb/remote/db.py
def __init__(
    self,
    db_url: str,
    api_key: str,
    region: str,
    host_override: Optional[str] = None,
    request_thread_pool: Optional[ThreadPoolExecutor] = None,
    client_config: Union[ClientConfig, Dict[str, Any], None] = None,
    connection_timeout: Optional[float] = None,
    read_timeout: Optional[float] = None,
    storage_options: Optional[Dict[str, str]] = None,
):
    """Connect to a remote LanceDB database."""
    if isinstance(client_config, dict):
        client_config = ClientConfig(**client_config)
    elif client_config is None:
        client_config = ClientConfig()

    # These are legacy options from the old Python-based client. We keep them
    # here for backwards compatibility, but will remove them in a future release.
    if request_thread_pool is not None:
        warnings.warn(
            "request_thread_pool is no longer used and will be removed in "
            "a future release.",
            DeprecationWarning,
        )

    if connection_timeout is not None:
        warnings.warn(
            "connection_timeout is deprecated and will be removed in a future "
            "release. Please use client_config.timeout_config.connect_timeout "
            "instead.",
            DeprecationWarning,
        )
        client_config.timeout_config.connect_timeout = timedelta(
            seconds=connection_timeout
        )

    if read_timeout is not None:
        warnings.warn(
            "read_timeout is deprecated and will be removed in a future release. "
            "Please use client_config.timeout_config.read_timeout instead.",
            DeprecationWarning,
        )
        client_config.timeout_config.read_timeout = timedelta(seconds=read_timeout)

    parsed = urlparse(db_url)
    if parsed.scheme != "db":
        raise ValueError(f"Invalid scheme: {parsed.scheme}, only accepts db://")
    self.db_name = parsed.netloc

    self.client_config = client_config

    self._conn = LOOP.run(
        connect_async(
            db_url,
            api_key=api_key,
            region=region,
            host_override=host_override,
            client_config=client_config,
            storage_options=storage_options,
        )
    )

table_names

table_names(page_token: Optional[str] = None, limit: int = 10) -> Iterable[str]

List the names of all tables in the database.

Parameters:

  • page_token (Optional[str], default: None ) –

    The last token to start the new page.

  • limit (int, default: 10 ) –

    The maximum number of tables to return for each page.

Returns:

  • An iterator of table names.
Source code in lancedb/remote/db.py
@override
def table_names(
    self, page_token: Optional[str] = None, limit: int = 10
) -> Iterable[str]:
    """List the names of all tables in the database.

    Parameters
    ----------
    page_token: str
        The last token to start the new page.
    limit: int, default 10
        The maximum number of tables to return for each page.

    Returns
    -------
    An iterator of table names.
    """
    return LOOP.run(self._conn.table_names(start_after=page_token, limit=limit))

open_table

open_table(name: str, *, storage_options: Optional[Dict[str, str]] = None, index_cache_size: Optional[int] = None) -> Table

Open a Lance Table in the database.

Parameters:

  • name (str) –

    The name of the table.

Returns:

  • A LanceTable object representing the table.
Source code in lancedb/remote/db.py
@override
def open_table(
    self,
    name: str,
    *,
    storage_options: Optional[Dict[str, str]] = None,
    index_cache_size: Optional[int] = None,
) -> Table:
    """Open a Lance Table in the database.

    Parameters
    ----------
    name: str
        The name of the table.

    Returns
    -------
    A LanceTable object representing the table.
    """
    from .table import RemoteTable

    if index_cache_size is not None:
        logging.info(
            "index_cache_size is ignored in LanceDb Cloud"
            " (there is no local cache to configure)"
        )

    table = LOOP.run(self._conn.open_table(name))
    return RemoteTable(table, self.db_name)

create_table

create_table(name: str, data: DATA = None, schema: Optional[Union[Schema, LanceModel]] = None, on_bad_vectors: str = 'error', fill_value: float = 0.0, mode: Optional[str] = None, embedding_functions: Optional[List[EmbeddingFunctionConfig]] = None) -> Table

Create a Table in the database.

Parameters:

  • name (str) –

    The name of the table.

  • data (DATA, default: None ) –

    User must provide at least one of data or schema. Acceptable types are:

    • dict or list-of-dict

    • pandas.DataFrame

    • pyarrow.Table or pyarrow.RecordBatch

  • schema (Optional[Union[Schema, LanceModel]], default: None ) –

    Acceptable types are:

  • on_bad_vectors (str, default: 'error' ) –

    What to do if any of the vectors are not the same size or contains NaNs. One of "error", "drop", "fill".

  • fill_value (float, default: 0.0 ) –

    The value to use when filling vectors. Only used if on_bad_vectors="fill".

Returns:

  • LanceTable

    A reference to the newly created table.

  • !!! note

    The vector index won't be created by default. To create the index, call the create_index method on the table.

Examples:

Can create with list of tuples or dictionaries:

>>> import lancedb
>>> db = lancedb.connect("db://...", api_key="...",
...                      region="...")
>>> data = [{"vector": [1.1, 1.2], "lat": 45.5, "long": -122.7},
...         {"vector": [0.2, 1.8], "lat": 40.1, "long":  -74.1}]
>>> db.create_table("my_table", data)
LanceTable(my_table)

You can also pass a pandas DataFrame:

>>> import pandas as pd
>>> data = pd.DataFrame({
...    "vector": [[1.1, 1.2], [0.2, 1.8]],
...    "lat": [45.5, 40.1],
...    "long": [-122.7, -74.1]
... })
>>> db.create_table("table2", data)
LanceTable(table2)
>>> custom_schema = pa.schema([
...   pa.field("vector", pa.list_(pa.float32(), 2)),
...   pa.field("lat", pa.float32()),
...   pa.field("long", pa.float32())
... ])
>>> db.create_table("table3", data, schema = custom_schema)
LanceTable(table3)

It is also possible to create an table from [Iterable[pa.RecordBatch]]:

>>> import pyarrow as pa
>>> def make_batches():
...     for i in range(5):
...         yield pa.RecordBatch.from_arrays(
...             [
...                 pa.array([[3.1, 4.1], [5.9, 26.5]],
...                     pa.list_(pa.float32(), 2)),
...                 pa.array(["foo", "bar"]),
...                 pa.array([10.0, 20.0]),
...             ],
...             ["vector", "item", "price"],
...         )
>>> schema=pa.schema([
...     pa.field("vector", pa.list_(pa.float32(), 2)),
...     pa.field("item", pa.utf8()),
...     pa.field("price", pa.float32()),
... ])
>>> db.create_table("table4", make_batches(), schema=schema)
LanceTable(table4)
Source code in lancedb/remote/db.py
@override
def create_table(
    self,
    name: str,
    data: DATA = None,
    schema: Optional[Union[pa.Schema, LanceModel]] = None,
    on_bad_vectors: str = "error",
    fill_value: float = 0.0,
    mode: Optional[str] = None,
    embedding_functions: Optional[List[EmbeddingFunctionConfig]] = None,
) -> Table:
    """Create a [Table][lancedb.table.Table] in the database.

    Parameters
    ----------
    name: str
        The name of the table.
    data: The data to initialize the table, *optional*
        User must provide at least one of `data` or `schema`.
        Acceptable types are:

        - dict or list-of-dict

        - pandas.DataFrame

        - pyarrow.Table or pyarrow.RecordBatch
    schema: The schema of the table, *optional*
        Acceptable types are:

        - pyarrow.Schema

        - [LanceModel][lancedb.pydantic.LanceModel]
    on_bad_vectors: str, default "error"
        What to do if any of the vectors are not the same size or contains NaNs.
        One of "error", "drop", "fill".
    fill_value: float
        The value to use when filling vectors. Only used if on_bad_vectors="fill".

    Returns
    -------
    LanceTable
        A reference to the newly created table.

    !!! note

        The vector index won't be created by default.
        To create the index, call the `create_index` method on the table.

    Examples
    --------

    Can create with list of tuples or dictionaries:

    >>> import lancedb
    >>> db = lancedb.connect("db://...", api_key="...", # doctest: +SKIP
    ...                      region="...")              # doctest: +SKIP
    >>> data = [{"vector": [1.1, 1.2], "lat": 45.5, "long": -122.7},
    ...         {"vector": [0.2, 1.8], "lat": 40.1, "long":  -74.1}]
    >>> db.create_table("my_table", data) # doctest: +SKIP
    LanceTable(my_table)

    You can also pass a pandas DataFrame:

    >>> import pandas as pd
    >>> data = pd.DataFrame({
    ...    "vector": [[1.1, 1.2], [0.2, 1.8]],
    ...    "lat": [45.5, 40.1],
    ...    "long": [-122.7, -74.1]
    ... })
    >>> db.create_table("table2", data) # doctest: +SKIP
    LanceTable(table2)

    >>> custom_schema = pa.schema([
    ...   pa.field("vector", pa.list_(pa.float32(), 2)),
    ...   pa.field("lat", pa.float32()),
    ...   pa.field("long", pa.float32())
    ... ])
    >>> db.create_table("table3", data, schema = custom_schema) # doctest: +SKIP
    LanceTable(table3)

    It is also possible to create an table from `[Iterable[pa.RecordBatch]]`:

    >>> import pyarrow as pa
    >>> def make_batches():
    ...     for i in range(5):
    ...         yield pa.RecordBatch.from_arrays(
    ...             [
    ...                 pa.array([[3.1, 4.1], [5.9, 26.5]],
    ...                     pa.list_(pa.float32(), 2)),
    ...                 pa.array(["foo", "bar"]),
    ...                 pa.array([10.0, 20.0]),
    ...             ],
    ...             ["vector", "item", "price"],
    ...         )
    >>> schema=pa.schema([
    ...     pa.field("vector", pa.list_(pa.float32(), 2)),
    ...     pa.field("item", pa.utf8()),
    ...     pa.field("price", pa.float32()),
    ... ])
    >>> db.create_table("table4", make_batches(), schema=schema) # doctest: +SKIP
    LanceTable(table4)

    """
    validate_table_name(name)
    if embedding_functions is not None:
        logging.warning(
            "embedding_functions is not yet supported on LanceDB Cloud."
            "Please vote https://github.com/lancedb/lancedb/issues/626 "
            "for this feature."
        )

    from .table import RemoteTable

    table = LOOP.run(
        self._conn.create_table(
            name,
            data,
            mode=mode,
            schema=schema,
            on_bad_vectors=on_bad_vectors,
            fill_value=fill_value,
        )
    )
    return RemoteTable(table, self.db_name)

drop_table

drop_table(name: str)

Drop a table from the database.

Parameters:

  • name (str) –

    The name of the table.

Source code in lancedb/remote/db.py
@override
def drop_table(self, name: str):
    """Drop a table from the database.

    Parameters
    ----------
    name: str
        The name of the table.
    """
    LOOP.run(self._conn.drop_table(name))

rename_table

rename_table(cur_name: str, new_name: str)

Rename a table in the database.

Parameters:

  • cur_name (str) –

    The current name of the table.

  • new_name (str) –

    The new name of the table.

Source code in lancedb/remote/db.py
@override
def rename_table(self, cur_name: str, new_name: str):
    """Rename a table in the database.

    Parameters
    ----------
    cur_name: str
        The current name of the table.
    new_name: str
        The new name of the table.
    """
    LOOP.run(self._conn.rename_table(cur_name, new_name))

close async

close()

Close the connection to the database.

Source code in lancedb/remote/db.py
async def close(self):
    """Close the connection to the database."""
    self._client.close()

Table

lancedb.remote.table.RemoteTable

Bases: Table

Source code in lancedb/remote/table.py
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
class RemoteTable(Table):
    def __init__(
        self,
        table: AsyncTable,
        db_name: str,
    ):
        self._table = table
        self.db_name = db_name

    @property
    def name(self) -> str:
        """The name of the table"""
        return self._table.name

    def __repr__(self) -> str:
        return f"RemoteTable({self.db_name}.{self.name})"

    def __len__(self) -> int:
        self.count_rows(None)

    @property
    def schema(self) -> pa.Schema:
        """The [Arrow Schema](https://arrow.apache.org/docs/python/api/datatypes.html#)
        of this Table

        """
        return LOOP.run(self._table.schema())

    @property
    def version(self) -> int:
        """Get the current version of the table"""
        return LOOP.run(self._table.version())

    @cached_property
    def embedding_functions(self) -> Dict[str, EmbeddingFunctionConfig]:
        """
        Get the embedding functions for the table

        Returns
        -------
        funcs: dict
            A mapping of the vector column to the embedding function
            or empty dict if not configured.
        """
        return EmbeddingFunctionRegistry.get_instance().parse_functions(
            self.schema.metadata
        )

    def list_versions(self):
        """List all versions of the table"""
        return LOOP.run(self._table.list_versions())

    def to_arrow(self) -> pa.Table:
        """to_arrow() is not yet supported on LanceDB cloud."""
        raise NotImplementedError("to_arrow() is not yet supported on LanceDB cloud.")

    def to_pandas(self):
        """to_pandas() is not yet supported on LanceDB cloud."""
        return NotImplementedError("to_pandas() is not yet supported on LanceDB cloud.")

    def checkout(self, version):
        return LOOP.run(self._table.checkout(version))

    def checkout_latest(self):
        return LOOP.run(self._table.checkout_latest())

    def list_indices(self) -> Iterable[IndexConfig]:
        """List all the indices on the table"""
        return LOOP.run(self._table.list_indices())

    def index_stats(self, index_uuid: str) -> Optional[IndexStatistics]:
        """List all the stats of a specified index"""
        return LOOP.run(self._table.index_stats(index_uuid))

    def create_scalar_index(
        self,
        column: str,
        index_type: Literal["BTREE", "BITMAP", "LABEL_LIST", "scalar"] = "scalar",
        *,
        replace: bool = False,
    ):
        """Creates a scalar index
        Parameters
        ----------
        column : str
            The column to be indexed.  Must be a boolean, integer, float,
            or string column.
        index_type : str
            The index type of the scalar index. Must be "scalar" (BTREE),
            "BTREE", "BITMAP", or "LABEL_LIST",
        replace : bool
            If True, replace the existing index with the new one.
        """
        if index_type == "scalar" or index_type == "BTREE":
            config = BTree()
        elif index_type == "BITMAP":
            config = Bitmap()
        elif index_type == "LABEL_LIST":
            config = LabelList()
        else:
            raise ValueError(f"Unknown index type: {index_type}")

        LOOP.run(self._table.create_index(column, config=config, replace=replace))

    def create_fts_index(
        self,
        column: str,
        *,
        replace: bool = False,
        with_position: bool = True,
        # tokenizer configs:
        base_tokenizer: str = "simple",
        language: str = "English",
        max_token_length: Optional[int] = 40,
        lower_case: bool = True,
        stem: bool = False,
        remove_stop_words: bool = False,
        ascii_folding: bool = False,
    ):
        config = FTS(
            with_position=with_position,
            base_tokenizer=base_tokenizer,
            language=language,
            max_token_length=max_token_length,
            lower_case=lower_case,
            stem=stem,
            remove_stop_words=remove_stop_words,
            ascii_folding=ascii_folding,
        )
        LOOP.run(self._table.create_index(column, config=config, replace=replace))

    def create_index(
        self,
        metric="L2",
        vector_column_name: str = VECTOR_COLUMN_NAME,
        index_cache_size: Optional[int] = None,
        num_partitions: Optional[int] = None,
        num_sub_vectors: Optional[int] = None,
        replace: Optional[bool] = None,
        accelerator: Optional[str] = None,
        index_type="vector",
    ):
        """Create an index on the table.
        Currently, the only parameters that matter are
        the metric and the vector column name.

        Parameters
        ----------
        metric : str
            The metric to use for the index. Default is "L2".
        vector_column_name : str
            The name of the vector column. Default is "vector".

        Examples
        --------
        >>> import lancedb
        >>> import uuid
        >>> from lancedb.schema import vector
        >>> db = lancedb.connect("db://...", api_key="...", # doctest: +SKIP
        ...                      region="...") # doctest: +SKIP
        >>> table_name = uuid.uuid4().hex
        >>> schema = pa.schema(
        ...     [
        ...             pa.field("id", pa.uint32(), False),
        ...            pa.field("vector", vector(128), False),
        ...             pa.field("s", pa.string(), False),
        ...     ]
        ... )
        >>> table = db.create_table( # doctest: +SKIP
        ...     table_name, # doctest: +SKIP
        ...     schema=schema, # doctest: +SKIP
        ... )
        >>> table.create_index("L2", "vector") # doctest: +SKIP
        """

        if num_partitions is not None:
            logging.warning(
                "num_partitions is not supported on LanceDB cloud."
                "This parameter will be tuned automatically."
            )
        if num_sub_vectors is not None:
            logging.warning(
                "num_sub_vectors is not supported on LanceDB cloud."
                "This parameter will be tuned automatically."
            )
        if accelerator is not None:
            logging.warning(
                "GPU accelerator is not yet supported on LanceDB cloud."
                "If you have 100M+ vectors to index,"
                "please contact us at contact@lancedb.com"
            )
        if replace is not None:
            logging.warning(
                "replace is not supported on LanceDB cloud."
                "Existing indexes will always be replaced."
            )

        index_type = index_type.upper()
        if index_type == "VECTOR" or index_type == "IVF_PQ":
            config = IvfPq(distance_type=metric)
        elif index_type == "IVF_HNSW_PQ":
            config = HnswPq(distance_type=metric)
        elif index_type == "IVF_HNSW_SQ":
            config = HnswSq(distance_type=metric)
        else:
            raise ValueError(
                f"Unknown vector index type: {index_type}. Valid options are"
                " 'IVF_PQ', 'IVF_HNSW_PQ', 'IVF_HNSW_SQ'"
            )

        LOOP.run(self._table.create_index(vector_column_name, config=config))

    def add(
        self,
        data: DATA,
        mode: str = "append",
        on_bad_vectors: str = "error",
        fill_value: float = 0.0,
    ) -> int:
        """Add more data to the [Table](Table). It has the same API signature as
        the OSS version.

        Parameters
        ----------
        data: DATA
            The data to insert into the table. Acceptable types are:

            - dict or list-of-dict

            - pandas.DataFrame

            - pyarrow.Table or pyarrow.RecordBatch
        mode: str
            The mode to use when writing the data. Valid values are
            "append" and "overwrite".
        on_bad_vectors: str, default "error"
            What to do if any of the vectors are not the same size or contains NaNs.
            One of "error", "drop", "fill".
        fill_value: float, default 0.
            The value to use when filling vectors. Only used if on_bad_vectors="fill".

        """
        LOOP.run(
            self._table.add(
                data, mode=mode, on_bad_vectors=on_bad_vectors, fill_value=fill_value
            )
        )

    def search(
        self,
        query: Union[VEC, str] = None,
        vector_column_name: Optional[str] = None,
        query_type="auto",
        fts_columns: Optional[Union[str, List[str]]] = None,
        fast_search: bool = False,
    ) -> LanceVectorQueryBuilder:
        """Create a search query to find the nearest neighbors
        of the given query vector. We currently support [vector search][search]

        All query options are defined in [Query][lancedb.query.Query].

        Examples
        --------
        >>> import lancedb
        >>> db = lancedb.connect("db://...", api_key="...", # doctest: +SKIP
        ...                      region="...") # doctest: +SKIP
        >>> data = [
        ...    {"original_width": 100, "caption": "bar", "vector": [0.1, 2.3, 4.5]},
        ...    {"original_width": 2000, "caption": "foo",  "vector": [0.5, 3.4, 1.3]},
        ...    {"original_width": 3000, "caption": "test", "vector": [0.3, 6.2, 2.6]}
        ... ]
        >>> table = db.create_table("my_table", data) # doctest: +SKIP
        >>> query = [0.4, 1.4, 2.4]
        >>> (table.search(query) # doctest: +SKIP
        ...     .where("original_width > 1000", prefilter=True) # doctest: +SKIP
        ...     .select(["caption", "original_width"]) # doctest: +SKIP
        ...     .limit(2) # doctest: +SKIP
        ...     .to_pandas()) # doctest: +SKIP
          caption  original_width           vector  _distance # doctest: +SKIP
        0     foo            2000  [0.5, 3.4, 1.3]   5.220000 # doctest: +SKIP
        1    test            3000  [0.3, 6.2, 2.6]  23.089996 # doctest: +SKIP

        Parameters
        ----------
        query: list/np.ndarray/str/PIL.Image.Image, default None
            The targetted vector to search for.

            - *default None*.
            Acceptable types are: list, np.ndarray, PIL.Image.Image

        vector_column_name: str, optional
            The name of the vector column to search.

            - If not specified then the vector column is inferred from
            the table schema

            - If the table has multiple vector columns then the *vector_column_name*
            needs to be specified. Otherwise, an error is raised.

        fast_search: bool, optional
            Skip a flat search of unindexed data. This may improve
            search performance but search results will not include unindexed data.

            - *default False*.

        Returns
        -------
        LanceQueryBuilder
            A query builder object representing the query.
            Once executed, the query returns

            - selected columns

            - the vector

            - and also the "_distance" column which is the distance between the query
            vector and the returned vector.
        """
        return LanceQueryBuilder.create(
            self,
            query,
            query_type,
            vector_column_name=vector_column_name,
            fts_columns=fts_columns,
            fast_search=fast_search,
        )

    def _execute_query(
        self, query: Query, batch_size: Optional[int] = None
    ) -> pa.RecordBatchReader:
        return LOOP.run(self._table._execute_query(query, batch_size=batch_size))

    def merge_insert(self, on: Union[str, Iterable[str]]) -> LanceMergeInsertBuilder:
        """Returns a [`LanceMergeInsertBuilder`][lancedb.merge.LanceMergeInsertBuilder]
        that can be used to create a "merge insert" operation.

        See [`Table.merge_insert`][lancedb.table.Table.merge_insert] for more details.
        """
        return super().merge_insert(on)

    def _do_merge(
        self,
        merge: LanceMergeInsertBuilder,
        new_data: DATA,
        on_bad_vectors: str,
        fill_value: float,
    ):
        LOOP.run(self._table._do_merge(merge, new_data, on_bad_vectors, fill_value))

    def delete(self, predicate: str):
        """Delete rows from the table.

        This can be used to delete a single row, many rows, all rows, or
        sometimes no rows (if your predicate matches nothing).

        Parameters
        ----------
        predicate: str
            The SQL where clause to use when deleting rows.

            - For example, 'x = 2' or 'x IN (1, 2, 3)'.

            The filter must not be empty, or it will error.

        Examples
        --------
        >>> import lancedb
        >>> data = [
        ...    {"x": 1, "vector": [1, 2]},
        ...    {"x": 2, "vector": [3, 4]},
        ...    {"x": 3, "vector": [5, 6]}
        ... ]
        >>> db = lancedb.connect("db://...", api_key="...", # doctest: +SKIP
        ...                      region="...") # doctest: +SKIP
        >>> table = db.create_table("my_table", data) # doctest: +SKIP
        >>> table.search([10,10]).to_pandas() # doctest: +SKIP
           x      vector  _distance # doctest: +SKIP
        0  3  [5.0, 6.0]       41.0 # doctest: +SKIP
        1  2  [3.0, 4.0]       85.0 # doctest: +SKIP
        2  1  [1.0, 2.0]      145.0 # doctest: +SKIP
        >>> table.delete("x = 2") # doctest: +SKIP
        >>> table.search([10,10]).to_pandas() # doctest: +SKIP
           x      vector  _distance # doctest: +SKIP
        0  3  [5.0, 6.0]       41.0 # doctest: +SKIP
        1  1  [1.0, 2.0]      145.0 # doctest: +SKIP

        If you have a list of values to delete, you can combine them into a
        stringified list and use the `IN` operator:

        >>> to_remove = [1, 3] # doctest: +SKIP
        >>> to_remove = ", ".join([str(v) for v in to_remove]) # doctest: +SKIP
        >>> table.delete(f"x IN ({to_remove})") # doctest: +SKIP
        >>> table.search([10,10]).to_pandas() # doctest: +SKIP
           x      vector  _distance # doctest: +SKIP
        0  2  [3.0, 4.0]       85.0 # doctest: +SKIP
        """
        LOOP.run(self._table.delete(predicate))

    def update(
        self,
        where: Optional[str] = None,
        values: Optional[dict] = None,
        *,
        values_sql: Optional[Dict[str, str]] = None,
    ):
        """
        This can be used to update zero to all rows depending on how many
        rows match the where clause.

        Parameters
        ----------
        where: str, optional
            The SQL where clause to use when updating rows. For example, 'x = 2'
            or 'x IN (1, 2, 3)'. The filter must not be empty, or it will error.
        values: dict, optional
            The values to update. The keys are the column names and the values
            are the values to set.
        values_sql: dict, optional
            The values to update, expressed as SQL expression strings. These can
            reference existing columns. For example, {"x": "x + 1"} will increment
            the x column by 1.

        Examples
        --------
        >>> import lancedb
        >>> data = [
        ...    {"x": 1, "vector": [1, 2]},
        ...    {"x": 2, "vector": [3, 4]},
        ...    {"x": 3, "vector": [5, 6]}
        ... ]
        >>> db = lancedb.connect("db://...", api_key="...", # doctest: +SKIP
        ...                      region="...") # doctest: +SKIP
        >>> table = db.create_table("my_table", data) # doctest: +SKIP
        >>> table.to_pandas() # doctest: +SKIP
           x      vector # doctest: +SKIP
        0  1  [1.0, 2.0] # doctest: +SKIP
        1  2  [3.0, 4.0] # doctest: +SKIP
        2  3  [5.0, 6.0] # doctest: +SKIP
        >>> table.update(where="x = 2", values={"vector": [10, 10]}) # doctest: +SKIP
        >>> table.to_pandas() # doctest: +SKIP
           x        vector # doctest: +SKIP
        0  1    [1.0, 2.0] # doctest: +SKIP
        1  3    [5.0, 6.0] # doctest: +SKIP
        2  2  [10.0, 10.0] # doctest: +SKIP

        """
        LOOP.run(
            self._table.update(where=where, updates=values, updates_sql=values_sql)
        )

    def cleanup_old_versions(self, *_):
        """
        cleanup_old_versions() is a no-op on LanceDB Cloud.

        Tables are automatically cleaned up and optimized.
        """
        warnings.warn(
            "cleanup_old_versions() is a no-op on LanceDB Cloud. "
            "Tables are automatically cleaned up and optimized."
        )
        pass

    def compact_files(self, *_):
        """
        compact_files() is a no-op on LanceDB Cloud.

        Tables are automatically compacted and optimized.
        """
        warnings.warn(
            "compact_files() is a no-op on LanceDB Cloud. "
            "Tables are automatically compacted and optimized."
        )
        pass

    def optimize(
        self,
        *,
        cleanup_older_than: Optional[timedelta] = None,
        delete_unverified: bool = False,
    ):
        """
        optimize() is a no-op on LanceDB Cloud.

        Indices are optimized automatically.
        """
        warnings.warn(
            "optimize() is a no-op on LanceDB Cloud. "
            "Indices are optimized automatically."
        )
        pass

    def count_rows(self, filter: Optional[str] = None) -> int:
        return LOOP.run(self._table.count_rows(filter))

    def add_columns(self, transforms: Dict[str, str]):
        return LOOP.run(self._table.add_columns(transforms))

    def alter_columns(self, *alterations: Iterable[Dict[str, str]]):
        return LOOP.run(self._table.alter_columns(*alterations))

    def drop_columns(self, columns: Iterable[str]):
        return LOOP.run(self._table.drop_columns(columns))

    def uses_v2_manifest_paths(self) -> bool:
        raise NotImplementedError(
            "uses_v2_manifest_paths() is not supported on the LanceDB Cloud"
        )

    def migrate_v2_manifest_paths(self):
        raise NotImplementedError(
            "migrate_v2_manifest_paths() is not supported on the LanceDB Cloud"
        )

name property

name: str

The name of the table

schema property

schema: Schema

The Arrow Schema of this Table

version property

version: int

Get the current version of the table

embedding_functions cached property

embedding_functions: Dict[str, EmbeddingFunctionConfig]

Get the embedding functions for the table

Returns:

  • funcs ( dict ) –

    A mapping of the vector column to the embedding function or empty dict if not configured.

list_versions

list_versions()

List all versions of the table

Source code in lancedb/remote/table.py
def list_versions(self):
    """List all versions of the table"""
    return LOOP.run(self._table.list_versions())

to_arrow

to_arrow() -> Table

to_arrow() is not yet supported on LanceDB cloud.

Source code in lancedb/remote/table.py
def to_arrow(self) -> pa.Table:
    """to_arrow() is not yet supported on LanceDB cloud."""
    raise NotImplementedError("to_arrow() is not yet supported on LanceDB cloud.")

to_pandas

to_pandas()

to_pandas() is not yet supported on LanceDB cloud.

Source code in lancedb/remote/table.py
def to_pandas(self):
    """to_pandas() is not yet supported on LanceDB cloud."""
    return NotImplementedError("to_pandas() is not yet supported on LanceDB cloud.")

list_indices

list_indices() -> Iterable[IndexConfig]

List all the indices on the table

Source code in lancedb/remote/table.py
def list_indices(self) -> Iterable[IndexConfig]:
    """List all the indices on the table"""
    return LOOP.run(self._table.list_indices())

index_stats

index_stats(index_uuid: str) -> Optional[IndexStatistics]

List all the stats of a specified index

Source code in lancedb/remote/table.py
def index_stats(self, index_uuid: str) -> Optional[IndexStatistics]:
    """List all the stats of a specified index"""
    return LOOP.run(self._table.index_stats(index_uuid))

create_scalar_index

create_scalar_index(column: str, index_type: Literal['BTREE', 'BITMAP', 'LABEL_LIST', 'scalar'] = 'scalar', *, replace: bool = False)

Creates a scalar index

Parameters:

  • column (str) –

    The column to be indexed. Must be a boolean, integer, float, or string column.

  • index_type (str, default: 'scalar' ) –

    The index type of the scalar index. Must be "scalar" (BTREE), "BTREE", "BITMAP", or "LABEL_LIST",

  • replace (bool, default: False ) –

    If True, replace the existing index with the new one.

Source code in lancedb/remote/table.py
def create_scalar_index(
    self,
    column: str,
    index_type: Literal["BTREE", "BITMAP", "LABEL_LIST", "scalar"] = "scalar",
    *,
    replace: bool = False,
):
    """Creates a scalar index
    Parameters
    ----------
    column : str
        The column to be indexed.  Must be a boolean, integer, float,
        or string column.
    index_type : str
        The index type of the scalar index. Must be "scalar" (BTREE),
        "BTREE", "BITMAP", or "LABEL_LIST",
    replace : bool
        If True, replace the existing index with the new one.
    """
    if index_type == "scalar" or index_type == "BTREE":
        config = BTree()
    elif index_type == "BITMAP":
        config = Bitmap()
    elif index_type == "LABEL_LIST":
        config = LabelList()
    else:
        raise ValueError(f"Unknown index type: {index_type}")

    LOOP.run(self._table.create_index(column, config=config, replace=replace))

create_index

create_index(metric='L2', vector_column_name: str = VECTOR_COLUMN_NAME, index_cache_size: Optional[int] = None, num_partitions: Optional[int] = None, num_sub_vectors: Optional[int] = None, replace: Optional[bool] = None, accelerator: Optional[str] = None, index_type='vector')

Create an index on the table. Currently, the only parameters that matter are the metric and the vector column name.

Parameters:

  • metric (str, default: 'L2' ) –

    The metric to use for the index. Default is "L2".

  • vector_column_name (str, default: VECTOR_COLUMN_NAME ) –

    The name of the vector column. Default is "vector".

Examples:

>>> import lancedb
>>> import uuid
>>> from lancedb.schema import vector
>>> db = lancedb.connect("db://...", api_key="...",
...                      region="...")
>>> table_name = uuid.uuid4().hex
>>> schema = pa.schema(
...     [
...             pa.field("id", pa.uint32(), False),
...            pa.field("vector", vector(128), False),
...             pa.field("s", pa.string(), False),
...     ]
... )
>>> table = db.create_table(
...     table_name,
...     schema=schema,
... )
>>> table.create_index("L2", "vector")
Source code in lancedb/remote/table.py
def create_index(
    self,
    metric="L2",
    vector_column_name: str = VECTOR_COLUMN_NAME,
    index_cache_size: Optional[int] = None,
    num_partitions: Optional[int] = None,
    num_sub_vectors: Optional[int] = None,
    replace: Optional[bool] = None,
    accelerator: Optional[str] = None,
    index_type="vector",
):
    """Create an index on the table.
    Currently, the only parameters that matter are
    the metric and the vector column name.

    Parameters
    ----------
    metric : str
        The metric to use for the index. Default is "L2".
    vector_column_name : str
        The name of the vector column. Default is "vector".

    Examples
    --------
    >>> import lancedb
    >>> import uuid
    >>> from lancedb.schema import vector
    >>> db = lancedb.connect("db://...", api_key="...", # doctest: +SKIP
    ...                      region="...") # doctest: +SKIP
    >>> table_name = uuid.uuid4().hex
    >>> schema = pa.schema(
    ...     [
    ...             pa.field("id", pa.uint32(), False),
    ...            pa.field("vector", vector(128), False),
    ...             pa.field("s", pa.string(), False),
    ...     ]
    ... )
    >>> table = db.create_table( # doctest: +SKIP
    ...     table_name, # doctest: +SKIP
    ...     schema=schema, # doctest: +SKIP
    ... )
    >>> table.create_index("L2", "vector") # doctest: +SKIP
    """

    if num_partitions is not None:
        logging.warning(
            "num_partitions is not supported on LanceDB cloud."
            "This parameter will be tuned automatically."
        )
    if num_sub_vectors is not None:
        logging.warning(
            "num_sub_vectors is not supported on LanceDB cloud."
            "This parameter will be tuned automatically."
        )
    if accelerator is not None:
        logging.warning(
            "GPU accelerator is not yet supported on LanceDB cloud."
            "If you have 100M+ vectors to index,"
            "please contact us at contact@lancedb.com"
        )
    if replace is not None:
        logging.warning(
            "replace is not supported on LanceDB cloud."
            "Existing indexes will always be replaced."
        )

    index_type = index_type.upper()
    if index_type == "VECTOR" or index_type == "IVF_PQ":
        config = IvfPq(distance_type=metric)
    elif index_type == "IVF_HNSW_PQ":
        config = HnswPq(distance_type=metric)
    elif index_type == "IVF_HNSW_SQ":
        config = HnswSq(distance_type=metric)
    else:
        raise ValueError(
            f"Unknown vector index type: {index_type}. Valid options are"
            " 'IVF_PQ', 'IVF_HNSW_PQ', 'IVF_HNSW_SQ'"
        )

    LOOP.run(self._table.create_index(vector_column_name, config=config))

add

add(data: DATA, mode: str = 'append', on_bad_vectors: str = 'error', fill_value: float = 0.0) -> int

Add more data to the Table. It has the same API signature as the OSS version.

Parameters:

  • data (DATA) –

    The data to insert into the table. Acceptable types are:

    • dict or list-of-dict

    • pandas.DataFrame

    • pyarrow.Table or pyarrow.RecordBatch

  • mode (str, default: 'append' ) –

    The mode to use when writing the data. Valid values are "append" and "overwrite".

  • on_bad_vectors (str, default: 'error' ) –

    What to do if any of the vectors are not the same size or contains NaNs. One of "error", "drop", "fill".

  • fill_value (float, default: 0.0 ) –

    The value to use when filling vectors. Only used if on_bad_vectors="fill".

Source code in lancedb/remote/table.py
def add(
    self,
    data: DATA,
    mode: str = "append",
    on_bad_vectors: str = "error",
    fill_value: float = 0.0,
) -> int:
    """Add more data to the [Table](Table). It has the same API signature as
    the OSS version.

    Parameters
    ----------
    data: DATA
        The data to insert into the table. Acceptable types are:

        - dict or list-of-dict

        - pandas.DataFrame

        - pyarrow.Table or pyarrow.RecordBatch
    mode: str
        The mode to use when writing the data. Valid values are
        "append" and "overwrite".
    on_bad_vectors: str, default "error"
        What to do if any of the vectors are not the same size or contains NaNs.
        One of "error", "drop", "fill".
    fill_value: float, default 0.
        The value to use when filling vectors. Only used if on_bad_vectors="fill".

    """
    LOOP.run(
        self._table.add(
            data, mode=mode, on_bad_vectors=on_bad_vectors, fill_value=fill_value
        )
    )

search

search(query: Union[VEC, str] = None, vector_column_name: Optional[str] = None, query_type='auto', fts_columns: Optional[Union[str, List[str]]] = None, fast_search: bool = False) -> LanceVectorQueryBuilder

Create a search query to find the nearest neighbors of the given query vector. We currently support vector search

All query options are defined in Query.

Examples:

>>> import lancedb
>>> db = lancedb.connect("db://...", api_key="...",
...                      region="...")
>>> data = [
...    {"original_width": 100, "caption": "bar", "vector": [0.1, 2.3, 4.5]},
...    {"original_width": 2000, "caption": "foo",  "vector": [0.5, 3.4, 1.3]},
...    {"original_width": 3000, "caption": "test", "vector": [0.3, 6.2, 2.6]}
... ]
>>> table = db.create_table("my_table", data)
>>> query = [0.4, 1.4, 2.4]
>>> (table.search(query)
...     .where("original_width > 1000", prefilter=True)
...     .select(["caption", "original_width"])
...     .limit(2)
...     .to_pandas())
  caption  original_width           vector  _distance
0     foo            2000  [0.5, 3.4, 1.3]   5.220000
1    test            3000  [0.3, 6.2, 2.6]  23.089996

Parameters:

  • query (Union[VEC, str], default: None ) –

    The targetted vector to search for.

    • default None. Acceptable types are: list, np.ndarray, PIL.Image.Image
  • vector_column_name (Optional[str], default: None ) –

    The name of the vector column to search.

    • If not specified then the vector column is inferred from the table schema

    • If the table has multiple vector columns then the vector_column_name needs to be specified. Otherwise, an error is raised.

  • fast_search (bool, default: False ) –

    Skip a flat search of unindexed data. This may improve search performance but search results will not include unindexed data.

    • default False.

Returns:

  • LanceQueryBuilder

    A query builder object representing the query. Once executed, the query returns

    • selected columns

    • the vector

    • and also the "_distance" column which is the distance between the query vector and the returned vector.

Source code in lancedb/remote/table.py
def search(
    self,
    query: Union[VEC, str] = None,
    vector_column_name: Optional[str] = None,
    query_type="auto",
    fts_columns: Optional[Union[str, List[str]]] = None,
    fast_search: bool = False,
) -> LanceVectorQueryBuilder:
    """Create a search query to find the nearest neighbors
    of the given query vector. We currently support [vector search][search]

    All query options are defined in [Query][lancedb.query.Query].

    Examples
    --------
    >>> import lancedb
    >>> db = lancedb.connect("db://...", api_key="...", # doctest: +SKIP
    ...                      region="...") # doctest: +SKIP
    >>> data = [
    ...    {"original_width": 100, "caption": "bar", "vector": [0.1, 2.3, 4.5]},
    ...    {"original_width": 2000, "caption": "foo",  "vector": [0.5, 3.4, 1.3]},
    ...    {"original_width": 3000, "caption": "test", "vector": [0.3, 6.2, 2.6]}
    ... ]
    >>> table = db.create_table("my_table", data) # doctest: +SKIP
    >>> query = [0.4, 1.4, 2.4]
    >>> (table.search(query) # doctest: +SKIP
    ...     .where("original_width > 1000", prefilter=True) # doctest: +SKIP
    ...     .select(["caption", "original_width"]) # doctest: +SKIP
    ...     .limit(2) # doctest: +SKIP
    ...     .to_pandas()) # doctest: +SKIP
      caption  original_width           vector  _distance # doctest: +SKIP
    0     foo            2000  [0.5, 3.4, 1.3]   5.220000 # doctest: +SKIP
    1    test            3000  [0.3, 6.2, 2.6]  23.089996 # doctest: +SKIP

    Parameters
    ----------
    query: list/np.ndarray/str/PIL.Image.Image, default None
        The targetted vector to search for.

        - *default None*.
        Acceptable types are: list, np.ndarray, PIL.Image.Image

    vector_column_name: str, optional
        The name of the vector column to search.

        - If not specified then the vector column is inferred from
        the table schema

        - If the table has multiple vector columns then the *vector_column_name*
        needs to be specified. Otherwise, an error is raised.

    fast_search: bool, optional
        Skip a flat search of unindexed data. This may improve
        search performance but search results will not include unindexed data.

        - *default False*.

    Returns
    -------
    LanceQueryBuilder
        A query builder object representing the query.
        Once executed, the query returns

        - selected columns

        - the vector

        - and also the "_distance" column which is the distance between the query
        vector and the returned vector.
    """
    return LanceQueryBuilder.create(
        self,
        query,
        query_type,
        vector_column_name=vector_column_name,
        fts_columns=fts_columns,
        fast_search=fast_search,
    )

merge_insert

merge_insert(on: Union[str, Iterable[str]]) -> LanceMergeInsertBuilder

Returns a LanceMergeInsertBuilder that can be used to create a "merge insert" operation.

See Table.merge_insert for more details.

Source code in lancedb/remote/table.py
def merge_insert(self, on: Union[str, Iterable[str]]) -> LanceMergeInsertBuilder:
    """Returns a [`LanceMergeInsertBuilder`][lancedb.merge.LanceMergeInsertBuilder]
    that can be used to create a "merge insert" operation.

    See [`Table.merge_insert`][lancedb.table.Table.merge_insert] for more details.
    """
    return super().merge_insert(on)

delete

delete(predicate: str)

Delete rows from the table.

This can be used to delete a single row, many rows, all rows, or sometimes no rows (if your predicate matches nothing).

Parameters:

  • predicate (str) –

    The SQL where clause to use when deleting rows.

    • For example, 'x = 2' or 'x IN (1, 2, 3)'.

    The filter must not be empty, or it will error.

Examples:

>>> import lancedb
>>> data = [
...    {"x": 1, "vector": [1, 2]},
...    {"x": 2, "vector": [3, 4]},
...    {"x": 3, "vector": [5, 6]}
... ]
>>> db = lancedb.connect("db://...", api_key="...",
...                      region="...")
>>> table = db.create_table("my_table", data)
>>> table.search([10,10]).to_pandas()
   x      vector  _distance
0  3  [5.0, 6.0]       41.0
1  2  [3.0, 4.0]       85.0
2  1  [1.0, 2.0]      145.0
>>> table.delete("x = 2")
>>> table.search([10,10]).to_pandas()
   x      vector  _distance
0  3  [5.0, 6.0]       41.0
1  1  [1.0, 2.0]      145.0

If you have a list of values to delete, you can combine them into a stringified list and use the IN operator:

>>> to_remove = [1, 3]
>>> to_remove = ", ".join([str(v) for v in to_remove])
>>> table.delete(f"x IN ({to_remove})")
>>> table.search([10,10]).to_pandas()
   x      vector  _distance
0  2  [3.0, 4.0]       85.0
Source code in lancedb/remote/table.py
def delete(self, predicate: str):
    """Delete rows from the table.

    This can be used to delete a single row, many rows, all rows, or
    sometimes no rows (if your predicate matches nothing).

    Parameters
    ----------
    predicate: str
        The SQL where clause to use when deleting rows.

        - For example, 'x = 2' or 'x IN (1, 2, 3)'.

        The filter must not be empty, or it will error.

    Examples
    --------
    >>> import lancedb
    >>> data = [
    ...    {"x": 1, "vector": [1, 2]},
    ...    {"x": 2, "vector": [3, 4]},
    ...    {"x": 3, "vector": [5, 6]}
    ... ]
    >>> db = lancedb.connect("db://...", api_key="...", # doctest: +SKIP
    ...                      region="...") # doctest: +SKIP
    >>> table = db.create_table("my_table", data) # doctest: +SKIP
    >>> table.search([10,10]).to_pandas() # doctest: +SKIP
       x      vector  _distance # doctest: +SKIP
    0  3  [5.0, 6.0]       41.0 # doctest: +SKIP
    1  2  [3.0, 4.0]       85.0 # doctest: +SKIP
    2  1  [1.0, 2.0]      145.0 # doctest: +SKIP
    >>> table.delete("x = 2") # doctest: +SKIP
    >>> table.search([10,10]).to_pandas() # doctest: +SKIP
       x      vector  _distance # doctest: +SKIP
    0  3  [5.0, 6.0]       41.0 # doctest: +SKIP
    1  1  [1.0, 2.0]      145.0 # doctest: +SKIP

    If you have a list of values to delete, you can combine them into a
    stringified list and use the `IN` operator:

    >>> to_remove = [1, 3] # doctest: +SKIP
    >>> to_remove = ", ".join([str(v) for v in to_remove]) # doctest: +SKIP
    >>> table.delete(f"x IN ({to_remove})") # doctest: +SKIP
    >>> table.search([10,10]).to_pandas() # doctest: +SKIP
       x      vector  _distance # doctest: +SKIP
    0  2  [3.0, 4.0]       85.0 # doctest: +SKIP
    """
    LOOP.run(self._table.delete(predicate))

update

update(where: Optional[str] = None, values: Optional[dict] = None, *, values_sql: Optional[Dict[str, str]] = None)

This can be used to update zero to all rows depending on how many rows match the where clause.

Parameters:

  • where (Optional[str], default: None ) –

    The SQL where clause to use when updating rows. For example, 'x = 2' or 'x IN (1, 2, 3)'. The filter must not be empty, or it will error.

  • values (Optional[dict], default: None ) –

    The values to update. The keys are the column names and the values are the values to set.

  • values_sql (Optional[Dict[str, str]], default: None ) –

    The values to update, expressed as SQL expression strings. These can reference existing columns. For example, {"x": "x + 1"} will increment the x column by 1.

Examples:

>>> import lancedb
>>> data = [
...    {"x": 1, "vector": [1, 2]},
...    {"x": 2, "vector": [3, 4]},
...    {"x": 3, "vector": [5, 6]}
... ]
>>> db = lancedb.connect("db://...", api_key="...",
...                      region="...")
>>> table = db.create_table("my_table", data)
>>> table.to_pandas()
   x      vector
0  1  [1.0, 2.0]
1  2  [3.0, 4.0]
2  3  [5.0, 6.0]
>>> table.update(where="x = 2", values={"vector": [10, 10]})
>>> table.to_pandas()
   x        vector
0  1    [1.0, 2.0]
1  3    [5.0, 6.0]
2  2  [10.0, 10.0]
Source code in lancedb/remote/table.py
def update(
    self,
    where: Optional[str] = None,
    values: Optional[dict] = None,
    *,
    values_sql: Optional[Dict[str, str]] = None,
):
    """
    This can be used to update zero to all rows depending on how many
    rows match the where clause.

    Parameters
    ----------
    where: str, optional
        The SQL where clause to use when updating rows. For example, 'x = 2'
        or 'x IN (1, 2, 3)'. The filter must not be empty, or it will error.
    values: dict, optional
        The values to update. The keys are the column names and the values
        are the values to set.
    values_sql: dict, optional
        The values to update, expressed as SQL expression strings. These can
        reference existing columns. For example, {"x": "x + 1"} will increment
        the x column by 1.

    Examples
    --------
    >>> import lancedb
    >>> data = [
    ...    {"x": 1, "vector": [1, 2]},
    ...    {"x": 2, "vector": [3, 4]},
    ...    {"x": 3, "vector": [5, 6]}
    ... ]
    >>> db = lancedb.connect("db://...", api_key="...", # doctest: +SKIP
    ...                      region="...") # doctest: +SKIP
    >>> table = db.create_table("my_table", data) # doctest: +SKIP
    >>> table.to_pandas() # doctest: +SKIP
       x      vector # doctest: +SKIP
    0  1  [1.0, 2.0] # doctest: +SKIP
    1  2  [3.0, 4.0] # doctest: +SKIP
    2  3  [5.0, 6.0] # doctest: +SKIP
    >>> table.update(where="x = 2", values={"vector": [10, 10]}) # doctest: +SKIP
    >>> table.to_pandas() # doctest: +SKIP
       x        vector # doctest: +SKIP
    0  1    [1.0, 2.0] # doctest: +SKIP
    1  3    [5.0, 6.0] # doctest: +SKIP
    2  2  [10.0, 10.0] # doctest: +SKIP

    """
    LOOP.run(
        self._table.update(where=where, updates=values, updates_sql=values_sql)
    )