I need to create a PostgreSQL Full Text Search index in Python with SQLAlchemy. Here’s what I want in SQL:
JavaScript
x
3
1
CREATE TABLE person ( id INTEGER PRIMARY KEY, name TEXT );
2
CREATE INDEX person_idx ON person USING GIN (to_tsvector('simple', name));
3
Now how do I do the second part with SQLAlchemy when using the ORM:
JavaScript
1
4
1
class Person(db.Model):
2
id = db.Column(db.Integer, primary_key=True)
3
name = db.Column(db.String)
4
Advertisement
Answer
You could create index using Index
in __table_args__
. Also I use a function to create ts_vector
to make it more tidy and reusable if more than one field is required. Something like below:
JavaScript
1
24
24
1
from sqlalchemy.dialects import postgresql
2
3
def create_tsvector(*args):
4
exp = args[0]
5
for e in args[1:]:
6
exp += ' ' + e
7
return func.to_tsvector('english', exp)
8
9
class Person(db.Model):
10
id = db.Column(db.Integer, primary_key=True)
11
name = db.Column(db.String)
12
13
__ts_vector__ = create_tsvector(
14
cast(func.coalesce(name, ''), postgresql.TEXT)
15
)
16
17
__table_args__ = (
18
Index(
19
'idx_person_fts',
20
__ts_vector__,
21
postgresql_using='gin'
22
)
23
)
24
Update: A sample query using index (corrected based on comments):
JavaScript
1
2
1
people = Person.query.filter(Person.__ts_vector__.match(expressions, postgresql_regconfig='english')).all()
2