I have thousands of records to insert to the tables. So want to try the bulkinsert kind of featuare. #659
-
First Check
Commit to Help
Example CodeHere is the example of sqlalchamy they are providing the bulk_insert_mappings feature which helps to insert bulk records. So is there any option to do this with the SQLModel.
for item in data_bulk.data:
metadata_entry = {
"companyID": user.companyID,
"userId": user_id,
"filename": item.filename,
"CreatedDate": item.CreatedDate,
}
metadata_entries.append(metadata_entry)
db.bulk_insert_mappings(MetaData, metadata_entries)
db.commit() DescriptionLike sqlalchamy has bulk_insert_mappings option which i didn't find in the SQLModel's AsyncSession object. So want to know how to do bulk inserting using AsyncSession of SQLModel. I tried with the same bulk insert with add_all but it will take lots of time to insert 70K records to the table. But then I created a sample project with sqlalchamy bulk_insert_mapping. It will insert the same data within a few seconds only. Operating SystemWindows Operating System DetailsNo response SQLModel Versionsqlmodel Version: 0.0.8 Python VersionPython 3.10.10 Additional ContextIf anyone has any kind of solution to bulk insert efficiently then please share your suggestions. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
You should be able to use Session.bulk_insert_mappings. Just pass your model as the 'mapper'. An example using the tutorial models: session.bulk_insert_mappings(Hero, [{"name": "Deadpond", "secret_name": "Dive Wilson"}]) |
Beta Was this translation helpful? Give feedback.
-
The syntax is: session.exec(insert(MetaData), params=metadata_entries)
session.commit() Runnable code example: from typing import Optional
from sqlmodel import Field, Session, SQLModel, create_engine, insert
class Hero(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
engine = create_engine("sqlite:///", echo=True)
SQLModel.metadata.create_all(engine)
with Session(engine) as session:
heroes_data = [
{
"name": f"Hero {i}",
}
for i in range(10)
]
session.exec(insert(Hero), params=heroes_data)
session.commit() SQL
|
Beta Was this translation helpful? Give feedback.
The syntax is:
Runnable code example:
SQL