我正在使用 Scrapy 从网络论坛中抓取数据。我使用 SQLAlchemy 将此数据存储在 PostgreSQL 数据库中。表和列创建得很好,但是,我无法让 SQLAlchemy 在其中一个列上创建索引。我正在尝试使用 Gin 创建三元组索引 (pg_trgm)。
创建这个索引的 Postgresql 代码是:
CREATE INDEX description_idx ON table USING gin (description gin_trgm_ops);
我添加到 models.py 文件中的 SQLAlchemy 代码是:
desc_idx = Index('description_idx', text("description gin_trgm_ops"), postgresql_using='gin')
我已将此行添加到我的 models.py,但是当我 checkin postgresql 时,从未创建索引。
下面是我的完整 models.py 和 pipelines.py 文件。我这样做是不是错了??
任何帮助将不胜感激!!
模型.py:
from sqlalchemy import create_engine, Column, Integer, String, DateTime, Index, text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.engine.url import URL
import settings
DeclarativeBase = declarative_base()
def db_connect():
return create_engine(URL(**settings.DATABASE))
def create_forum_table(engine):
DeclarativeBase.metadata.create_all(engine)
class forumDB(DeclarativeBase):
__tablename__ = "table"
id = Column(Integer, primary_key=True)
title = Column('title', String)
desc = Column('description', String, nullable=True)
desc_idx = Index('description_idx', text("description gin_trgm_ops"), postgresql_using='gin')
管道.py
from scrapy.exceptions import DropItem
from sqlalchemy.orm import sessionmaker
from models import forumDB, db_connect, create_forum_table
class ScrapeforumToDB(object):
def __init__(self):
engine = db_connect()
create_forum_table(engine)
self.Session = sessionmaker(bind=engine)
def process_item(self, item, spider):
session = self.Session()
forumitem = forumDB(**item)
try:
session.add(forumitem)
session.commit()
except:
session.rollback()
raise
finally:
session.close()
return item
最佳答案
引用 Operator Class 的正确方法在SQLAlchemy中(如gin_trgm_ops
)就是使用postgresql_ops
参数。这也将允许像 alembic 这样的工具。了解在自动生成迁移时如何使用它。
Index('description_idx',
'description', postgresql_using='gin',
postgresql_ops={
'description': 'gin_trgm_ops',
})
关于python - 如何使用 Scrapy 的 SQLAlchemy 创建 pg_trgm 索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36389166/