2

In the website I'm making with Flask, I'm trying to "upgrade" my search bar by using the pg_trgm PostgreSQL extension to match words even after being spelled wrong. However, I'm having trouble figuring out how to use the extension's custom functions alongside SQLAlchemy.

Will I have to use raw SQL to properly perform the queries, or is there a way to do this more cleanly?

2
  • Have you tried psycopg? Commented Jan 1, 2022 at 5:59
  • That would be the raw SQL approach I could fall back on yeah. Commented Jan 1, 2022 at 6:28

1 Answer 1

3

Assuming the extension is configured correctly, these functions should be accessible like any other database function. For example, here's how the similarity function might be called using SQLAlchemy core:

import sqlalchemy as sa

engine = sa.create_engine('postgresql+psycopg2:///test', echo=True, future=True)

metadata = sa.MetaData()

tbl = sa.Table('t70546926', metadata,
               sa.Column('c1', sa.String, primary_key=True),
               sa.Column('c2', sa.String))
tbl.drop(engine, checkfirst=True)
tbl.create(engine)

ins = sa.insert(tbl).values(c1='Alice', c2='Alison')

with engine.begin() as conn:
    conn.execute(ins)

query = sa.select(sa.func.similarity(tbl.c.c1, tbl.c.c2).label('similarity_result'))
with engine.connect() as conn:
    rows = conn.execute(query)
    for row in rows:
        print(row.similarity_result)

For Flask-SQLAlchemy, you might do something like this:

result = dbsession.query(sa.func.similarity(val1, val2)).all()
Sign up to request clarification or add additional context in comments.

3 Comments

I am trying to implement this as well. How do you configure this extension @csjh?
@MarcTanne I don't think I really needed any configuration for it, I just used sa.func.SIMILARITY

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.