Skip to content

Python API Reference (SaaS)

This section contains the API reference for the SaaS Python API.

Installation

pip install lancedb

Connection

lancedb.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, **kwargs) -> DBConnection

Connect to a LanceDB database.

Parameters:

Name Type Description Default
uri URI

The uri of the database.

required
api_key Optional[str]

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.

None
region str

The region to use for LanceDB Cloud.

'us-east-1'
host_override Optional[str]

The override url for LanceDB Cloud.

None
read_consistency_interval Optional[timedelta]

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

None
request_thread_pool Optional[Union[int, ThreadPoolExecutor]]

The thread pool to use for making batch requests to the LanceDB Cloud API. If an integer, then a ThreadPoolExecutor will be created with that number of threads. If None, then a ThreadPoolExecutor will be created with the default number of threads. If a ThreadPoolExecutor, then that executor will be used for making requests. This is for LanceDB Cloud only and is only used when making batch requests (i.e., passing in multiple queries to the search method at once).

None

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")

Connect to LanceDB cloud:

>>> db = lancedb.connect("db://my_database", api_key="ldb_...")

Returns:

Name Type Description
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,
    **kwargs,
) -> 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.
    request_thread_pool: int or ThreadPoolExecutor, optional
        The thread pool to use for making batch requests to the LanceDB Cloud API.
        If an integer, then a ThreadPoolExecutor will be created with that
        number of threads. If None, then a ThreadPoolExecutor will be created
        with the default number of threads. If a ThreadPoolExecutor, then that
        executor will be used for making requests. This is for LanceDB Cloud
        only and is only used when making batch requests (i.e., passing in
        multiple queries to the search method at once).

    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")

    Connect to LanceDB cloud:

    >>> db = lancedb.connect("db://my_database", api_key="ldb_...")

    Returns
    -------
    conn : DBConnection
        A connection to a LanceDB database.
    """
    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,
            request_thread_pool=request_thread_pool,
            **kwargs,
        )

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

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,
        connection_timeout: float = 120.0,
        read_timeout: float = 300.0,
    ):
        """Connect to a remote LanceDB database."""
        parsed = urlparse(db_url)
        if parsed.scheme != "db":
            raise ValueError(f"Invalid scheme: {parsed.scheme}, only accepts db://")
        self.db_name = parsed.netloc
        self.api_key = api_key
        self._client = RestfulLanceDBClient(
            self.db_name,
            region,
            api_key,
            host_override,
            connection_timeout=connection_timeout,
            read_timeout=read_timeout,
        )
        self._request_thread_pool = request_thread_pool
        self._table_cache = TTLCache(maxsize=10000, ttl=300)

    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.
        """
        while True:
            result = self._client.list_tables(limit, page_token)

            if len(result) > 0:
                page_token = result[len(result) - 1]
            else:
                break
            for item in result:
                self._table_cache[item] = True
                yield item

    @override
    def open_table(self, name: str, *, 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

        self._client.mount_retry_adapter_for_table(name)

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

        # check if table exists
        if self._table_cache.get(name) is None:
            self._client.post(f"/v1/table/{name}/describe/")
            self._table_cache[name] = True

        return RemoteTable(self, 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 data is None and schema is None:
            raise ValueError("Either data or schema must be provided.")
        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."
            )
        if mode is not None:
            logging.warning("mode is not yet supported on LanceDB Cloud.")

        if inspect.isclass(schema) and issubclass(schema, LanceModel):
            # convert LanceModel to pyarrow schema
            # note that it's possible this contains
            # embedding function metadata already
            schema = schema.to_arrow_schema()

        if data is not None:
            data = _sanitize_data(
                data,
                schema,
                metadata=None,
                on_bad_vectors=on_bad_vectors,
                fill_value=fill_value,
            )
        else:
            if schema is None:
                raise ValueError("Either data or schema must be provided")
            data = pa.Table.from_pylist([], schema=schema)

        from .table import RemoteTable

        data = to_ipc_binary(data)
        request_id = uuid.uuid4().hex

        self._client.post(
            f"/v1/table/{name}/create/",
            data=data,
            request_id=request_id,
            content_type=ARROW_STREAM_CONTENT_TYPE,
        )

        self._table_cache[name] = True
        return RemoteTable(self, name)

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

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

        self._client.post(
            f"/v1/table/{name}/drop/",
        )
        self._table_cache.pop(name, default=None)

    @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.
        """
        self._client.post(
            f"/v1/table/{cur_name}/rename/",
            data={"new_table_name": new_name},
        )
        self._table_cache.pop(cur_name, default=None)
        self._table_cache[new_name] = True

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

__init__(db_url: str, api_key: str, region: str, host_override: Optional[str] = None, request_thread_pool: Optional[ThreadPoolExecutor] = None, connection_timeout: float = 120.0, read_timeout: float = 300.0)

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,
    connection_timeout: float = 120.0,
    read_timeout: float = 300.0,
):
    """Connect to a remote LanceDB database."""
    parsed = urlparse(db_url)
    if parsed.scheme != "db":
        raise ValueError(f"Invalid scheme: {parsed.scheme}, only accepts db://")
    self.db_name = parsed.netloc
    self.api_key = api_key
    self._client = RestfulLanceDBClient(
        self.db_name,
        region,
        api_key,
        host_override,
        connection_timeout=connection_timeout,
        read_timeout=read_timeout,
    )
    self._request_thread_pool = request_thread_pool
    self._table_cache = TTLCache(maxsize=10000, ttl=300)

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

List the names of all tables in the database.

Parameters:

Name Type Description Default
page_token Optional[str]

The last token to start the new page.

None
limit int

The maximum number of tables to return for each page.

10

Returns:

Type Description
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.
    """
    while True:
        result = self._client.list_tables(limit, page_token)

        if len(result) > 0:
            page_token = result[len(result) - 1]
        else:
            break
        for item in result:
            self._table_cache[item] = True
            yield item

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

Open a Lance Table in the database.

Parameters:

Name Type Description Default
name str

The name of the table.

required

Returns:

Type Description
A LanceTable object representing the table.
Source code in lancedb/remote/db.py
@override
def open_table(self, name: str, *, 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

    self._client.mount_retry_adapter_for_table(name)

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

    # check if table exists
    if self._table_cache.get(name) is None:
        self._client.post(f"/v1/table/{name}/describe/")
        self._table_cache[name] = True

    return RemoteTable(self, name)

create_table(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 in the database.

Parameters:

Name Type Description Default
name str

The name of the table.

required
data DATA

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

None
schema Optional[Union[Schema, LanceModel]]

Acceptable types are:

None
on_bad_vectors str

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

'error'
fill_value float

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

0.0

Returns:

Type Description
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 data is None and schema is None:
        raise ValueError("Either data or schema must be provided.")
    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."
        )
    if mode is not None:
        logging.warning("mode is not yet supported on LanceDB Cloud.")

    if inspect.isclass(schema) and issubclass(schema, LanceModel):
        # convert LanceModel to pyarrow schema
        # note that it's possible this contains
        # embedding function metadata already
        schema = schema.to_arrow_schema()

    if data is not None:
        data = _sanitize_data(
            data,
            schema,
            metadata=None,
            on_bad_vectors=on_bad_vectors,
            fill_value=fill_value,
        )
    else:
        if schema is None:
            raise ValueError("Either data or schema must be provided")
        data = pa.Table.from_pylist([], schema=schema)

    from .table import RemoteTable

    data = to_ipc_binary(data)
    request_id = uuid.uuid4().hex

    self._client.post(
        f"/v1/table/{name}/create/",
        data=data,
        request_id=request_id,
        content_type=ARROW_STREAM_CONTENT_TYPE,
    )

    self._table_cache[name] = True
    return RemoteTable(self, name)

drop_table(name: str)

Drop a table from the database.

Parameters:

Name Type Description Default
name str

The name of the table.

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

    self._client.post(
        f"/v1/table/{name}/drop/",
    )
    self._table_cache.pop(name, default=None)

rename_table(cur_name: str, new_name: str)

Rename a table in the database.

Parameters:

Name Type Description Default
cur_name str

The current name of the table.

required
new_name str

The new name of the table.

required
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.
    """
    self._client.post(
        f"/v1/table/{cur_name}/rename/",
        data={"new_table_name": new_name},
    )
    self._table_cache.pop(cur_name, default=None)
    self._table_cache[new_name] = True

close() async

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
class RemoteTable(Table):
    def __init__(self, conn: RemoteDBConnection, name: str):
        self._conn = conn
        self._name = name

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

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

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

        """
        resp = self._conn._client.post(f"/v1/table/{self._name}/describe/")
        schema = json_to_schema(resp["schema"])
        return schema

    @property
    def version(self) -> int:
        """Get the current version of the table"""
        resp = self._conn._client.post(f"/v1/table/{self._name}/describe/")
        return resp["version"]

    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 list_indices(self):
        """List all the indices on the table"""
        resp = self._conn._client.post(f"/v1/table/{self._name}/index/list/")
        return resp

    def index_stats(self, index_uuid: str):
        """List all the stats of a specified index"""
        resp = self._conn._client.post(
            f"/v1/table/{self._name}/index/{index_uuid}/stats/"
        )
        return resp

    def create_scalar_index(
        self,
        column: str,
    ):
        """Creates a scalar index
        Parameters
        ----------
        column : str
            The column to be indexed.  Must be a boolean, integer, float,
            or string column.
        """
        index_type = "scalar"

        data = {
            "column": column,
            "index_type": index_type,
            "replace": True,
        }
        resp = self._conn._client.post(
            f"/v1/table/{self._name}/create_scalar_index/", data=data
        )

        return resp

    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,
    ):
        """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 = "vector"

        data = {
            "column": vector_column_name,
            "index_type": index_type,
            "metric_type": metric,
            "index_cache_size": index_cache_size,
        }
        resp = self._conn._client.post(
            f"/v1/table/{self._name}/create_index/", data=data
        )

        return resp

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

        """
        data = _sanitize_data(
            data,
            self.schema,
            metadata=None,
            on_bad_vectors=on_bad_vectors,
            fill_value=fill_value,
        )
        payload = to_ipc_binary(data)

        request_id = uuid.uuid4().hex

        self._conn._client.post(
            f"/v1/table/{self._name}/insert/",
            data=payload,
            params={"request_id": request_id, "mode": mode},
            content_type=ARROW_STREAM_CONTENT_TYPE,
        )

    def search(
        self,
        query: Union[VEC, str],
        vector_column_name: Optional[str] = None,
    ) -> 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

            - If None then the select/where/limit clauses are applied to filter
            the table
        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.

        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.
        """
        if vector_column_name is None:
            vector_column_name = inf_vector_column_query(self.schema)
        return LanceVectorQueryBuilder(self, query, vector_column_name)

    def _execute_query(
        self, query: Query, batch_size: Optional[int] = None
    ) -> pa.RecordBatchReader:
        if (
            query.vector is not None
            and len(query.vector) > 0
            and not isinstance(query.vector[0], float)
        ):
            if self._conn._request_thread_pool is None:

                def submit(name, q):
                    f = Future()
                    f.set_result(self._conn._client.query(name, q))
                    return f

            else:

                def submit(name, q):
                    return self._conn._request_thread_pool.submit(
                        self._conn._client.query, name, q
                    )

            results = []
            for v in query.vector:
                v = list(v)
                q = query.copy()
                q.vector = v
                results.append(submit(self._name, q))
            return pa.concat_tables(
                [add_index(r.result().to_arrow(), i) for i, r in enumerate(results)]
            ).to_reader()
        else:
            result = self._conn._client.query(self._name, query)
            return result.to_arrow().to_reader()

    def _do_merge(
        self,
        merge: LanceMergeInsertBuilder,
        new_data: DATA,
        on_bad_vectors: str,
        fill_value: float,
    ):
        data = _sanitize_data(
            new_data,
            self.schema,
            metadata=None,
            on_bad_vectors=on_bad_vectors,
            fill_value=fill_value,
        )
        payload = to_ipc_binary(data)

        params = {}
        if len(merge._on) != 1:
            raise ValueError(
                "RemoteTable only supports a single on key in merge_insert"
            )
        params["on"] = merge._on[0]
        params["when_matched_update_all"] = str(merge._when_matched_update_all).lower()
        if merge._when_matched_update_all_condition is not None:
            params[
                "when_matched_update_all_filt"
            ] = merge._when_matched_update_all_condition
        params["when_not_matched_insert_all"] = str(
            merge._when_not_matched_insert_all
        ).lower()
        params["when_not_matched_by_source_delete"] = str(
            merge._when_not_matched_by_source_delete
        ).lower()
        if merge._when_not_matched_by_source_condition is not None:
            params[
                "when_not_matched_by_source_delete_filt"
            ] = merge._when_not_matched_by_source_condition

        self._conn._client.post(
            f"/v1/table/{self._name}/merge_insert/",
            data=payload,
            params=params,
            content_type=ARROW_STREAM_CONTENT_TYPE,
        )

    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
        """
        payload = {"predicate": predicate}
        self._conn._client.post(f"/v1/table/{self._name}/delete/", data=payload)

    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

        """
        if values is not None and values_sql is not None:
            raise ValueError("Only one of values or values_sql can be provided")
        if values is None and values_sql is None:
            raise ValueError("Either values or values_sql must be provided")

        if values is not None:
            updates = [[k, value_to_sql(v)] for k, v in values.items()]
        else:
            updates = [[k, v] for k, v in values_sql.items()]

        payload = {"predicate": where, "updates": updates}
        self._conn._client.post(f"/v1/table/{self._name}/update/", data=payload)

    def cleanup_old_versions(self, *_):
        """cleanup_old_versions() is not supported on the LanceDB cloud"""
        raise NotImplementedError(
            "cleanup_old_versions() is not supported on the LanceDB cloud"
        )

    def compact_files(self, *_):
        """compact_files() is not supported on the LanceDB cloud"""
        raise NotImplementedError(
            "compact_files() is not supported on the LanceDB cloud"
        )

    def count_rows(self, filter: Optional[str] = None) -> int:
        payload = {"predicate": filter}
        resp = self._conn._client.post(
            f"/v1/table/{self._name}/count_rows/", data=payload
        )
        return resp

    def add_columns(self, transforms: Dict[str, str]):
        raise NotImplementedError(
            "add_columns() is not yet supported on the LanceDB cloud"
        )

    def alter_columns(self, alterations: Iterable[Dict[str, str]]):
        raise NotImplementedError(
            "alter_columns() is not yet supported on the LanceDB cloud"
        )

    def drop_columns(self, columns: Iterable[str]):
        raise NotImplementedError(
            "drop_columns() is not yet supported on the LanceDB cloud"
        )

schema: pa.Schema cached property

The Arrow Schema of this Table

version: int property

Get the current version of the table

to_arrow() -> pa.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() 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 all the indices on the table

Source code in lancedb/remote/table.py
def list_indices(self):
    """List all the indices on the table"""
    resp = self._conn._client.post(f"/v1/table/{self._name}/index/list/")
    return resp

index_stats(index_uuid: str)

List all the stats of a specified index

Source code in lancedb/remote/table.py
def index_stats(self, index_uuid: str):
    """List all the stats of a specified index"""
    resp = self._conn._client.post(
        f"/v1/table/{self._name}/index/{index_uuid}/stats/"
    )
    return resp

create_scalar_index(column: str)

Creates a scalar index

Parameters:

Name Type Description Default
column str

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

required
Source code in lancedb/remote/table.py
def create_scalar_index(
    self,
    column: str,
):
    """Creates a scalar index
    Parameters
    ----------
    column : str
        The column to be indexed.  Must be a boolean, integer, float,
        or string column.
    """
    index_type = "scalar"

    data = {
        "column": column,
        "index_type": index_type,
        "replace": True,
    }
    resp = self._conn._client.post(
        f"/v1/table/{self._name}/create_scalar_index/", data=data
    )

    return resp

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)

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

Parameters:

Name Type Description Default
metric str

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

'L2'
vector_column_name str

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

VECTOR_COLUMN_NAME

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,
):
    """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 = "vector"

    data = {
        "column": vector_column_name,
        "index_type": index_type,
        "metric_type": metric,
        "index_cache_size": index_cache_size,
    }
    resp = self._conn._client.post(
        f"/v1/table/{self._name}/create_index/", data=data
    )

    return resp

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:

Name Type Description Default
data DATA

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

  • dict or list-of-dict

  • pandas.DataFrame

  • pyarrow.Table or pyarrow.RecordBatch

required
mode str

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

'append'
on_bad_vectors str

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

'error'
fill_value float

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

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

    """
    data = _sanitize_data(
        data,
        self.schema,
        metadata=None,
        on_bad_vectors=on_bad_vectors,
        fill_value=fill_value,
    )
    payload = to_ipc_binary(data)

    request_id = uuid.uuid4().hex

    self._conn._client.post(
        f"/v1/table/{self._name}/insert/",
        data=payload,
        params={"request_id": request_id, "mode": mode},
        content_type=ARROW_STREAM_CONTENT_TYPE,
    )

search(query: Union[VEC, str], vector_column_name: Optional[str] = None) -> 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:

Name Type Description Default
query Union[VEC, str]

The targetted vector to search for.

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

  • If None then the select/where/limit clauses are applied to filter the table

required
vector_column_name Optional[str]

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.

None

Returns:

Type Description
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],
    vector_column_name: Optional[str] = None,
) -> 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

        - If None then the select/where/limit clauses are applied to filter
        the table
    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.

    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.
    """
    if vector_column_name is None:
        vector_column_name = inf_vector_column_query(self.schema)
    return LanceVectorQueryBuilder(self, query, vector_column_name)

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:

Name Type Description Default
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.

required

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
    """
    payload = {"predicate": predicate}
    self._conn._client.post(f"/v1/table/{self._name}/delete/", data=payload)

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:

Name Type Description Default
where Optional[str]

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.

None
values Optional[dict]

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

None
values_sql Optional[Dict[str, str]]

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.

None

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

    """
    if values is not None and values_sql is not None:
        raise ValueError("Only one of values or values_sql can be provided")
    if values is None and values_sql is None:
        raise ValueError("Either values or values_sql must be provided")

    if values is not None:
        updates = [[k, value_to_sql(v)] for k, v in values.items()]
    else:
        updates = [[k, v] for k, v in values_sql.items()]

    payload = {"predicate": where, "updates": updates}
    self._conn._client.post(f"/v1/table/{self._name}/update/", data=payload)

cleanup_old_versions(*_)

cleanup_old_versions() is not supported on the LanceDB cloud

Source code in lancedb/remote/table.py
def cleanup_old_versions(self, *_):
    """cleanup_old_versions() is not supported on the LanceDB cloud"""
    raise NotImplementedError(
        "cleanup_old_versions() is not supported on the LanceDB cloud"
    )

compact_files(*_)

compact_files() is not supported on the LanceDB cloud

Source code in lancedb/remote/table.py
def compact_files(self, *_):
    """compact_files() is not supported on the LanceDB cloud"""
    raise NotImplementedError(
        "compact_files() is not supported on the LanceDB cloud"
    )