Reuse the same expensive calculations in select and filter statement in sqlalchemy

61 Views Asked by At

Is there a way to reuse calculations in sqlalchemy such as SUM if I want to get the SUM and filter by it, or do I not need to worry of such things?

In my case I'm using pgvector to get the id of previous transactions which has a cosine-similarity above 0.8 e.g:


session.execute(
        select(model.identifier, 1 - model.embedding.cosine_distance(source_embedding)).
              filter(1 - model.embedding.cosine_distance(source_embedding) >= 0.8).
              order_by(model.embedding.cosine_distance(source_embedding)).asc()
              ).limit(5)).all()

As you can see the model.embedding.cosine_distance is invoked multiple times; in select, in filter and in order_by and can be a rather costly operation. Is there a way to do that smarter or is that handled automatically?

0

There are 0 best solutions below