Skip to content

Searching similar vectors in SQLModel #57

@AniLeo-01

Description

@AniLeo-01

I want to build a function for fetching similar vectors with the distance metrics. I have used the exact command written in the README.md but looks like it's not working for me.

Here's the code:

async def get_similar_vectors(session: AsyncSession, query_vector, k=10, distance = "cosine_distance"):
    if distance == "cosine_distance":
        query = select(db_models.Vector).order_by(
            db_models.Vector.embedding.cosine_distance(query_vector)).limit(k)
    elif distance == "l2_distance":
        query = select(db_models.Vector).order_by(
            db_models.Vector.embedding.l2_distance(query_vector)).limit(k)
    else:
        query = select(db_models.Vector).order_by(
            db_models.Vector.embedding.max_inner_product(query_vector)).limit(k)
    
    execute_query = await session.execute(query)
    similar_vectors = execute_query.all()
    results = [
            {"id": vector.id, "embedding": vector.embedding}
            for vector in similar_vectors
        ]
    return results

Here's the issue:

select(db_models.Vector).order_by(
            db_models.Vector.embedding.cosine_distance(query_vector)).limit(k)

Cannot access member "cosine_distance" for type "List[float]"
Member "cosine_distance" is unknown

This goes same for all the other distance metrics.

To give more clarity on the Vector model:

class Vector(SQLModel, table=True):
    id: Optional[UUID] = Field(default=None, primary_key=True)
    embedding: List[float] = Field(sa_column=Column(Vector(embedding_dim)))

query_vector type is List[float]

How to fix this issue? Or more specifically how to search for similar embeddings using SQLModel?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions