Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for filtered search in pgvector #362

Merged
merged 1 commit into from
Aug 27, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 20 additions & 5 deletions vectordb_bench/backend/clients/pgvector/pgvector.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class PgVector(VectorDB):
conn: psycopg.Connection[Any] | None = None
cursor: psycopg.Cursor[Any] | None = None

# TODO add filters support
_filtered_search: sql.Composed
_unfiltered_search: sql.Composed

def __init__(
Expand Down Expand Up @@ -112,6 +112,16 @@ def init(self) -> Generator[None, None, None]:
self.cursor.execute(command)
self.conn.commit()

self._filtered_search = sql.Composed(
[
sql.SQL(
"SELECT id FROM public.{table_name} WHERE id >= %s ORDER BY embedding "
).format(table_name=sql.Identifier(self.table_name)),
sql.SQL(self.case_config.search_param()["metric_fun_op"]),
sql.SQL(" %s::vector LIMIT %s::int"),
]
)

self._unfiltered_search = sql.Composed(
[
sql.SQL("SELECT id FROM public.{} ORDER BY embedding ").format(
Expand Down Expand Up @@ -342,9 +352,14 @@ def search_embedding(
assert self.cursor is not None, "Cursor is not initialized"

q = np.asarray(query)
# TODO add filters support
result = self.cursor.execute(
self._unfiltered_search, (q, k), prepare=True, binary=True
)
if filters:
gt = filters.get("id")
result = self.cursor.execute(
self._filtered_search, (gt, q, k), prepare=True, binary=True
)
else:
result = self.cursor.execute(
self._unfiltered_search, (q, k), prepare=True, binary=True
)

return [int(i[0]) for i in result.fetchall()]