I am scraping a large amount of data from a website and the problem is it is taking too much time by inserting one by one into the database I am looking for a smart way to bulk insert or make a batch insert to the database so it won't take like forever to push it to the database. I am using sqlalchemy1.4
orm and scrapy framework.
models:
from sqlalchemy import Column, Date, String, Integer, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from . import settings
engine = create_engine(settings.DATABSE_URL)
Session = sessionmaker(bind=engine)
session = Session()
DeclarativeBase = declarative_base()
class Olx_Eg(DeclarativeBase):
"""
Defines the property listing model
"""
__tablename__ = "olx_egypt"
_id = Column(Integer, primary_key=True)
URL = Column("URL", String)
Breadcrumb = Column("Breadcrumb", String)
Price = Column("Price", String)
Title = Column("Title", String)
Type = Column("Type", String)
Bedrooms = Column("Bedrooms", String)
Bathrooms = Column("Bathrooms", String)
Area = Column("Area", String)
Location = Column("Location", String)
Compound = Column("Compound", String)
seller = Column("seller", String)
Seller_member_since = Column("Seller_member_since", String)
Seller_phone_number = Column("Seller_phone_number", String)
Description = Column("Description", String)
Amenities = Column("Amenities", String)
Reference = Column("Reference", String)
Listed_date = Column("Listed_date", String)
Level = Column("Level", String)
Payment_option = Column("Payment_option", String)
Delivery_term = Column("Delivery_term", String)
Furnished = Column("Furnished", String)
Delivery_date = Column("Delivery_date", String)
Down_payment = Column("Down_payment", String)
Image_url = Column("Image_url", String)
Here is my scrapy pipeline right now:
from olx_egypt.models import Olx_Eg, session
class OlxEgPipeline:
def __init__(self):
"""
Initializes database connection and sessionmaker.
Creates items table.
"""
def process_item(self, item, spider):
"""
Process the item and store to database.
"""
# session = self.Session()
instance = session.query(Olx_Eg).filter_by(Reference=item["Reference"]).first()
if instance:
return instance
else:
olx_item = Olx_Eg(**item)
session.add(olx_item)
try:
session.commit()
except:
session.rollback()
raise
finally:
session.close()
return item
I tried creating a list and appending the items to it and then on closing the spider push it to db:
from olx_egypt.models import Olx_Eg, session
class ExampleScrapyPipeline:
def __init__(self):
self.items = []
def process_item(self, item, spider):
self.items.append(item)
return item
def close_spider(self, spider):
try:
session.bulk_insert_mappings(Olx_Eg, self.items)
session.commit()
except Exception as error:
session.rollback()
raise
finally:
session.close()
but it failed on session.bulk_insert_mappings(Olx_Eg, self.items)
this line. Can anyone tell me how can I make scrapy pipeline bulk or batch insert?