Working with Tables
Compare to "Collection" and "Points" concepts in other vector databases, TiDB uses "Table" to represent a collection of data and provides flexibility to define the table structure based on your needs.
A table can contain multiple columns with various data types, including text, numbers, vectors, binary data (BLOB), JSON, and more.
Tip
To check the complete example, please refer to the example.
Create a table
From TableModel
TiDB provides a TableModel
class that represents the schema of a table, which is compatible with [Pydantic Model] and allows you to define the table structure in a declarative way.
In the following example, we will create a table named items
with the following columns:
id
: a primary key column with an integer type.content
: a text type column.embedding
: a vector type column with 3 dimensions.meta
: a JSON type column.
from pytidb.schema import TableModel, Field, VectorField
from pytidb.datatype import TEXT, JSON
class Item(TableModel, table=True):
__tablename__ = "items"
id: int = Field(primary_key=True)
content: str = Field(sa_type=TEXT)
embedding: list[float] = VectorField(dimensions=3)
meta: dict = Field(default_factory=dict, sa_type=JSON)
table = db.create_table(schema=Item)
Once the table is created, you can use the table
object to insert, update, delete, query data.
Add data to a table
With TableModel
You can using a TableModel
instance to represent a record and insert it into the table.
Insert a single record:
Use the table.insert()
method to insert a single record into the table.
Insert multiple records:
Use the table.bulk_insert()
method to insert multiple records into the table.
Use the INSERT INTO
statement to insert multiple records into the table.
Query data from a table
Get all records from a table:
Find records based on some query conditions:
To check all the supported filters, please refer to the filtering guide.
Update data in a table
Delete from a table
Truncate table
To clean all data in the table but keep the table structure, use the table.truncate()
method.
Check the table is truncated, should be 0 rows.
Drop a table
To remove the specified table from the database permanently, use the db.drop_table()
method.
Check the table is removed from the database.