Files
qdrant-client/qdrant_client/local/persistence.py
George a8beff7c96 Drop python3.9 (#1110)
* new: remove vectors_count, update http and grpc models

* fix: update inspection cache

* new: add conversions and update interface

* fix: fix some conversions

* fix: fix typo

* fix: fix isinstance

* fix: regen async

* fix: fix update_filter usage, fix isinstance

* tests: collection metadata test

* fix: address backward compatibility in test

* new: update models, add max payload index count and copy vectors

* fix; update _inspection_cache

* new: add read consistency to count points

* Allow uuids in interface (#1085)

* new: direct uuid support

* tests: add uuid tests

* fix: update inspection cache

* new: add collection metadata and tests to local mode (#1089)

* new: add collection metadata and tests to local mode

* fix: regen async client

* new: implement parametrized rrf in local mode (#1087)

* new: implement parametrized rrf in local mode

* refactoring: use a variable for a magic value

* fix: adjust conversion according to AI

* Update filter (#1090)

* new: add missing update_filter, implement it in local mode

* fix: fix type hint, fix update operation, fix rest uploader, add tests

* fix: fix update filter is None case

* fix: mypy was not a good boy

* Text any filter (#1091)

* new: add match text any local mode

* tests: add match text any tests

* new: update models, remove init_from and locks (#1100)

* new: update models, remove init_from and locks

* deprecate: remove init from tests

* deprecate: remove lock tests

* new: convert ascii_folding

* fix: fix type stub

* new: convert acorn

* new: convert shard key with fallback

* new: update grpcio and grpcio tools in generator (#1106)

* new: update grpcio and grpcio tools in generator

* fix: bind grpcio and tools versions to 1.62.0 in generator

* Remove deprecated methods (#1103)

* deprecate: remove old api methods

* deprecate: remove type stub for removed methods

* deprecate: remove old api methods from test_qdrant_client

* deprecate: replace search with query points in test_in_memory

* deprecate: replace search methods in fastembed mixin with query points

* deprecate: replace old api methods in test async qdrant client

* deprecate: replace search with query points in test delete points

* deprecate: replace discover and context with query points in test_discovery

* deprecate: replace recommend_groups with query_points_groups in test_group_recommend

* deprecate: replace search_groups in test_group_search

* deprecate: replace recommend with query points in test_recommendation

* deprecate: replace search with query points in test search

* deprecate: replace context and discover with query points in test sparse discovery

* deprecate: replace search with query points in test sparse idf search

* deprecate: replace recommend with query points in test sparse recommend

* deprecate: replace search with query points in test sparse search

* deprecate: replace missing search request with query request in qdrant_fastembed

* deprecate: replace search with query points in test multivector search queries

* deprecate: replace upload records with upload points in test_updates

* deprecate: remove redundant structs (#1104)

* deprecate: remove redundant structs

* fix: do not use removed conversions in local mode

* fix: remove redundant conversions, simplify types.QueryRequest

* deprecate: replace old style grpc vector conversion to a new one (#1105)

* deprecate: replace old style grpc vector conversion to a new one

* fix: ignore union attr in conversion

* review fixes

---------

Co-authored-by: generall <andrey@vasnetsov.com>

---------

Co-authored-by: generall <andrey@vasnetsov.com>

---------

Co-authored-by: generall <andrey@vasnetsov.com>

* new: deprecate add, query, query_batch in fastembed mixin (#1102)

* new: deprecate add, query, query_batch in fastembed mixin

* 1.16 -> 1.17

---------

Co-authored-by: generall <andrey@vasnetsov.com>

---------

Co-authored-by: generall <andrey@vasnetsov.com>

* new: yet another update

* new: add initial_state to create shard key (#1109)

* new: drop python3.9, replace union and optional with | where possible

* fix: fix missing type hints, regen async

* fix: remove redundant optional

* fix: fix ai comments

* fix: update type hints from merge

* new: update pyproject and lock

* new: replace optional and union with |

* new: remove optional and union from qdrant local

* new: replace union with | in client classes

* fix: replace remaining union, optional, etc, address review comments

* new: adjust numpy versioning

---------

Co-authored-by: generall <andrey@vasnetsov.com>
2025-12-05 16:32:24 +07:00

177 lines
5.5 KiB
Python

import base64
import dbm
import logging
import pickle
import sqlite3
from pathlib import Path
from typing import Iterable
from qdrant_client.http import models
STORAGE_FILE_NAME_OLD = "storage.dbm"
STORAGE_FILE_NAME = "storage.sqlite"
def try_migrate_to_sqlite(location: str) -> None:
dbm_path = Path(location) / STORAGE_FILE_NAME_OLD
sql_path = Path(location) / STORAGE_FILE_NAME
if sql_path.exists():
return
if not dbm_path.exists():
return
try:
dbm_storage = dbm.open(str(dbm_path), "c")
con = sqlite3.connect(str(sql_path))
cur = con.cursor()
# Create table
cur.execute("CREATE TABLE IF NOT EXISTS points (id TEXT PRIMARY KEY, point BLOB)")
for key in dbm_storage.keys():
value = dbm_storage[key]
if isinstance(key, str):
key = key.encode("utf-8")
key = pickle.loads(key)
sqlite_key = CollectionPersistence.encode_key(key)
# Insert a row of data
cur.execute(
"INSERT INTO points VALUES (?, ?)",
(
sqlite_key,
sqlite3.Binary(value),
),
)
con.commit()
con.close()
dbm_storage.close()
dbm_path.unlink()
except Exception as e:
logging.error("Failed to migrate dbm to sqlite:", e)
logging.error(
"Please try to use previous version of qdrant-client or re-create collection"
)
raise e
class CollectionPersistence:
CHECK_SAME_THREAD: bool | None = None
@classmethod
def encode_key(cls, key: models.ExtendedPointId) -> str:
return base64.b64encode(pickle.dumps(key)).decode("utf-8")
def __init__(self, location: str, force_disable_check_same_thread: bool = False):
"""
Create or load a collection from the local storage.
Args:
location: path to the collection directory.
"""
try_migrate_to_sqlite(location)
self.location = Path(location) / STORAGE_FILE_NAME
self.location.parent.mkdir(exist_ok=True, parents=True)
if self.CHECK_SAME_THREAD is None and force_disable_check_same_thread is False:
with sqlite3.connect(":memory:") as tmp_conn:
# it is unsafe to use `sqlite3.threadsafety` until python3.11 since it was hardcoded to 1, thus we
# need to fetch threadsafe with a query
# THREADSAFE = 0: Threads may not share the module
# THREADSAFE = 1: Threads may share the module, connections and cursors. Default for Linux.
# THREADSAFE = 2: Threads may share the module, but not connections. Default for macOS.
threadsafe = tmp_conn.execute(
"select * from pragma_compile_options where compile_options like 'THREADSAFE=%'"
).fetchone()[0]
self.__class__.CHECK_SAME_THREAD = threadsafe != "THREADSAFE=1"
if force_disable_check_same_thread:
self.__class__.CHECK_SAME_THREAD = False
self.storage = sqlite3.connect(
str(self.location),
check_same_thread=self.CHECK_SAME_THREAD, # type: ignore
)
self._ensure_table()
def close(self) -> None:
self.storage.close()
def _ensure_table(self) -> None:
cursor = self.storage.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS points (id TEXT PRIMARY KEY, point BLOB)")
self.storage.commit()
def persist(self, point: models.PointStruct) -> None:
"""
Persist a point in the local storage.
Args:
point: point to persist
"""
key = self.encode_key(point.id)
value = pickle.dumps(point)
cursor = self.storage.cursor()
# Insert or update by key
cursor.execute(
"INSERT OR REPLACE INTO points VALUES (?, ?)",
(
key,
sqlite3.Binary(value),
),
)
self.storage.commit()
def delete(self, point_id: models.ExtendedPointId) -> None:
"""
Delete a point from the local storage.
Args:
point_id: id of the point to delete
"""
key = self.encode_key(point_id)
cursor = self.storage.cursor()
cursor.execute(
"DELETE FROM points WHERE id = ?",
(key,),
)
self.storage.commit()
def load(self) -> Iterable[models.PointStruct]:
"""
Load a point from the local storage.
Returns:
point: loaded point
"""
cursor = self.storage.cursor()
cursor.execute("SELECT point FROM points")
for row in cursor.fetchall():
yield pickle.loads(row[0])
def test_persistence() -> None:
import tempfile
with tempfile.TemporaryDirectory() as tmpdir:
persistence = CollectionPersistence(tmpdir)
point = models.PointStruct(id=1, vector=[1.0, 2.0, 3.0], payload={"a": 1})
persistence.persist(point)
for loaded_point in persistence.load():
assert loaded_point == point
break
del persistence
persistence = CollectionPersistence(tmpdir)
for loaded_point in persistence.load():
assert loaded_point == point
break
persistence.delete(point.id)
persistence.delete(point.id)
for _ in persistence.load():
assert False, "Should not load anything"