pgvector / pgvector-python

pgvector support for Python
MIT License
951 stars 63 forks source link

How to get distance by Psycopg 2 #19

Closed pasa13142 closed 1 year ago

pasa13142 commented 1 year ago

Hey, Thanks for this amazing project.

There is an example about how to get distance by django and SQLAlchemy but Psycopg2. Could you help about how to get the distance by Psycopg 2? Thanks in advance

ankane commented 1 year ago

Hi @pasa13142, you can use:

cur.execute('SELECT embedding <-> %s AS distance FROM item', (embedding,))
cur.fetchall()

More info: https://github.com/pgvector/pgvector#distances

pasa13142 commented 1 year ago

Hey, Thanks for the answer! Also, Can I search multi embeddings in one query? I tried like

cursor.execute('SELECT image_id, embedding <-> (%s, %s) AS distance FROM images ORDER BY distance LIMIT 20', (encodes[0],encodes[1]))
cursor.fetchall() 

but didnt work. Have any idea?

ankane commented 1 year ago

Check out https://github.com/pgvector/pgvector/issues/59#issuecomment-1436346940

pasa13142 commented 1 year ago

Hey, thanks !

I've seen it but using 'union all' on the same table didn't make much sense to me. Is there a more effective method that we can do in a single query?