SQLAlchemy Searchable

3.0.0 · active · verified Fri Apr 17

SQLAlchemy Searchable provides full-text search capabilities for declarative SQLAlchemy models, primarily leveraging PostgreSQL's `tsvector` type for robust search. The current version is 3.0.0, and the library maintains a regular release cadence, with major versions often aligning with SQLAlchemy and PostgreSQL version support changes.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to integrate `sqlalchemy-searchable` into a basic SQLAlchemy application. It sets up a simple `Document` model, makes it searchable using `make_searchable`, and then performs a basic full-text search query. Note that while this example uses SQLite for simplicity, `sqlalchemy-searchable`'s full potential, especially for advanced full-text search, is realized with PostgreSQL.

import os
from sqlalchemy import create_engine, Column, Integer, String, Text
from sqlalchemy.orm import sessionmaker, declarative_base
from sqlalchemy_searchable import make_searchable
# from sqlalchemy_utils import TSVectorType # Often used for explicit search vector column type

# Database setup (using in-memory SQLite for simplicity)
# For PostgreSQL, use 'postgresql://user:password@host:port/database'
engine = create_engine(os.environ.get('SQLALCHEMY_DATABASE_URL', 'sqlite:///:memory:'))
Session = sessionmaker(bind=engine)
session = Session()

Base = declarative_base()

# IMPORTANT: Call make_searchable BEFORE defining your models
make_searchable(Base.metadata)

class Document(Base):
    __tablename__ = 'document'
    # __searchable__ defines which columns contribute to the search vector
    __searchable__ = ['title', 'content']

    id = Column(Integer, primary_key=True)
    title = Column(String(255))
    content = Column(Text)
    # For PostgreSQL, you might define an explicit TSVectorType:
    # search_vector = Column(TSVectorType('title', 'content'))

    def __repr__(self):
        return f"<Document(id={self.id}, title='{self.title}')>"

Base.metadata.create_all(engine)

# Add some data
doc1 = Document(title="Python Programming Basics", content="Learn the fundamentals of Python, including variables, data types, and control flow.")
doc2 = Document(title="Advanced SQLAlchemy Techniques", content="Explore advanced features of SQLAlchemy like custom types, events, and performance tuning.")
doc3 = Document(title="Web Development with Flask", content="Build web applications efficiently using the Flask microframework and Jinja2 templates.")

session.add_all([doc1, doc2, doc3])
session.commit()

# Perform searches
print("Searching for 'Python':")
results_python = session.query(Document).search('Python').all()
for doc in results_python:
    print(f"- {doc.title}")

print("\nSearching for 'web applications':")
results_web = session.query(Document).search('web applications').all()
for doc in results_web:
    print(f"- {doc.title}")

session.close()

view raw JSON →