快速入门#
安装#
SQLAlchemy-Searchable 可在 PyPI 上获取。可以使用 pip 安装它
pip install SQLAlchemy-Searchable
SQLAlchemy-Searchable 需要 Python 3.8 或更高版本,无论是 cPython 还是 PyPy 实现。
配置#
在你的应用程序中启用全文搜索功能的第一步是使用 make_searchable()
函数并传入你的声明性基类来配置 SQLAlchemy-Searchable
from sqlalchemy.orm import declarative_base
from sqlalchemy_searchable import make_searchable
Base = declarative_base()
make_searchable(Base.metadata)
定义模型#
然后,向你的模型添加一个搜索向量列,并指定你希望包含在全文搜索中的列。这里有一个使用 Article
模型的示例
from sqlalchemy import Column, Integer, String, Text
from sqlalchemy_utils.types import TSVectorType
class Article(Base):
__tablename__ = "article"
id = Column(Integer, primary_key=True)
name = Column(String(255))
content = Column(Text)
search_vector = Column(TSVectorType("name", "content"))
搜索向量是 TSVectorType
数据类型的特殊列,针对文本搜索进行了优化。这里,我们希望 name
和 content
列为全文索引,我们通过将它们作为 TSVectorType
构造函数的参数来表明这一点。
创建并填充表格#
现在,让我们创建表格并添加一些示例数据。在创建表格之前,确保调用 sqlalchemy.orm.configure_mappers()
以确保已为模型配置了映射程序
from sqlalchemy import create_engine
from sqlalchemy.orm import configure_mappers, Session
engine = create_engine("postgresql://127.0.0.1/sqlalchemy_searchable_test")
configure_mappers() # IMPORTANT!
Base.metadata.create_all(engine)
session = Session(engine)
article1 = Article(name="First article", content="This is the first article")
article2 = Article(name="Second article", content="This is the second article")
session.add(article1)
session.add(article2)
session.commit()
执行搜索#
在创建好文章并填充数据库后,我们现在可以使用 search()
函数对它们进行全文搜索
from sqlalchemy import select
from sqlalchemy_searchable import search
query = search(select(Article), "first")
article = session.scalars(query).first()
print(article.name)
# Output: First article