mindnet/app/core/qdrant.py

180 lines
6.5 KiB
Python
Raw Normal View History

2025-09-05 09:22:15 +02:00
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
2025-11-11 17:58:21 +01:00
app/core/qdrant.py
Version: 2.2.0 (2025-11-11)
Aufgabe
-------
- Zentraler Qdrant-Zugriff (Client, Config)
- Collection-Anlage (notes/chunks/edges)
- **Payload-Indizes sicherstellen** (idempotent)
Hinweis
-------
Diese Datei ist als Drop-in-Ersatz gedacht, falls in deinem Projekt noch keine
robuste ensure_payload_indexes()-Implementierung vorliegt. Die Signaturen
bleiben kompatibel zu scripts.import_markdown und scripts.reset_qdrant.
API-Notizen
-----------
- Payload-Indizes werden mit `create_payload_index` angelegt.
- Typen stammen aus `qdrant_client.http.models.PayloadSchemaType`:
KEYWORD | TEXT | INTEGER | FLOAT | BOOL | GEO | DATETIME
- Für häufige Filterfelder (note_id, kind, scope, type, tags, ...) legen wir
Indizes an. Das ist laut Qdrant-Doku Best Practice für performante Filter.
2025-11-08 16:27:47 +01:00
"""
from __future__ import annotations
2025-11-11 17:58:21 +01:00
2025-09-03 08:04:02 +02:00
import os
2025-09-04 08:37:10 +02:00
from dataclasses import dataclass
2025-11-11 17:58:21 +01:00
from typing import Optional, Tuple, Dict, List
2025-09-03 08:04:02 +02:00
2025-11-08 16:27:47 +01:00
from qdrant_client import QdrantClient
from qdrant_client.http import models as rest
2025-09-03 08:04:02 +02:00
2025-09-04 08:37:10 +02:00
2025-11-11 17:58:21 +01:00
# ---------------------------------------------------------------------------
# Konfiguration
# ---------------------------------------------------------------------------
2025-09-03 08:04:02 +02:00
@dataclass
class QdrantConfig:
2025-11-11 17:58:21 +01:00
host: Optional[str] = None
port: Optional[int] = None
url: Optional[str] = None
api_key: Optional[str] = None
prefix: str = "mindnet"
dim: int = 384
distance: str = "Cosine" # Cosine | Dot | Euclid
on_disk_payload: bool = True
@classmethod
def from_env(cls) -> "QdrantConfig":
# Entweder URL ODER Host/Port, API-Key optional
url = os.getenv("QDRANT_URL") or None
host = os.getenv("QDRANT_HOST") or None
port = os.getenv("QDRANT_PORT")
port = int(port) if port else None
2025-11-08 16:27:47 +01:00
api_key = os.getenv("QDRANT_API_KEY") or None
2025-11-11 17:58:21 +01:00
prefix = os.getenv("COLLECTION_PREFIX") or "mindnet"
dim = int(os.getenv("VECTOR_DIM") or 384)
distance = os.getenv("DISTANCE", "Cosine")
on_disk_payload = (os.getenv("ON_DISK_PAYLOAD", "true").lower() == "true")
return cls(
host=host, port=port, url=url, api_key=api_key,
prefix=prefix, dim=dim, distance=distance, on_disk_payload=on_disk_payload
)
2025-11-08 16:27:47 +01:00
def get_client(cfg: QdrantConfig) -> QdrantClient:
2025-11-11 17:58:21 +01:00
# QdrantClient akzeptiert entweder url=... oder host/port
if cfg.url:
return QdrantClient(url=cfg.url, api_key=cfg.api_key, timeout=60.0)
return QdrantClient(host=cfg.host or "127.0.0.1", port=cfg.port or 6333, api_key=cfg.api_key, timeout=60.0)
2025-11-08 16:27:47 +01:00
2025-11-11 17:58:21 +01:00
# ---------------------------------------------------------------------------
# Collections
# ---------------------------------------------------------------------------
2025-09-05 09:27:28 +02:00
2025-11-11 17:58:21 +01:00
def collection_names(prefix: str) -> Tuple[str, str, str]:
return f"{prefix}_notes", f"{prefix}_chunks", f"{prefix}_edges"
2025-09-05 09:27:28 +02:00
2025-11-11 17:58:21 +01:00
def _vector_params(dim: int, distance: str) -> rest.VectorParams:
# Distance: "Cosine" | "Dot" | "Euclid"
dist = getattr(rest.Distance, distance.capitalize(), rest.Distance.COSINE)
return rest.VectorParams(size=dim, distance=dist)
2025-09-05 09:27:28 +02:00
2025-11-08 16:27:47 +01:00
2025-11-11 17:58:21 +01:00
def ensure_collections(client: QdrantClient, prefix: str, dim: int) -> None:
"""Legt mindnet_notes, mindnet_chunks, mindnet_edges an (falls nicht vorhanden)."""
notes, chunks, edges = collection_names(prefix)
2025-11-08 16:27:47 +01:00
2025-11-11 17:58:21 +01:00
# notes
if not client.collection_exists(notes):
client.create_collection(
collection_name=notes,
vectors_config=_vector_params(dim, os.getenv("DISTANCE", "Cosine")),
on_disk_payload=True,
)
# chunks
if not client.collection_exists(chunks):
client.create_collection(
collection_name=chunks,
vectors_config=_vector_params(dim, os.getenv("DISTANCE", "Cosine")),
on_disk_payload=True,
)
# edges (Dummy-Vektor, Filter via Payload)
if not client.collection_exists(edges):
client.create_collection(
collection_name=edges,
vectors_config=_vector_params(1, "Dot"),
on_disk_payload=True,
)
2025-11-08 16:27:47 +01:00
2025-11-11 17:58:21 +01:00
# ---------------------------------------------------------------------------
# Payload-Indizes
# ---------------------------------------------------------------------------
2025-11-08 16:27:47 +01:00
2025-11-11 17:58:21 +01:00
def _ensure_index(client: QdrantClient, collection: str, field: str, schema: rest.PayloadSchemaType) -> None:
"""Idempotentes Anlegen eines Payload-Indexes für ein Feld."""
2025-11-08 11:45:59 +01:00
try:
2025-11-11 17:58:21 +01:00
client.create_payload_index(collection_name=collection, field_name=field, field_schema=schema, wait=True)
except Exception as e:
# Fehler ignorieren, falls Index bereits existiert oder Server "already indexed" meldet.
# Für Debugging ggf. Logging ergänzen.
_ = e
2025-11-08 16:27:47 +01:00
def ensure_payload_indexes(client: QdrantClient, prefix: str) -> None:
2025-11-11 17:58:21 +01:00
"""
Stellt sicher, dass alle benötigten Payload-Indizes existieren.
- notes: note_id(KEYWORD), type(KEYWORD), title(TEXT), updated(INTEGER), tags(KEYWORD)
- chunks: note_id(KEYWORD), chunk_id(KEYWORD), index(INTEGER), type(KEYWORD), tags(KEYWORD)
- edges: note_id(KEYWORD), kind(KEYWORD), scope(KEYWORD), source_id(KEYWORD), target_id(KEYWORD), chunk_id(KEYWORD)
"""
2025-11-08 16:27:47 +01:00
notes, chunks, edges = collection_names(prefix)
2025-11-11 17:58:21 +01:00
# NOTES
for field, schema in [
("note_id", rest.PayloadSchemaType.KEYWORD),
("type", rest.PayloadSchemaType.KEYWORD),
("title", rest.PayloadSchemaType.TEXT),
("updated", rest.PayloadSchemaType.INTEGER),
("tags", rest.PayloadSchemaType.KEYWORD),
]:
_ensure_index(client, notes, field, schema)
# CHUNKS
for field, schema in [
("note_id", rest.PayloadSchemaType.KEYWORD),
("chunk_id", rest.PayloadSchemaType.KEYWORD),
("index", rest.PayloadSchemaType.INTEGER),
("type", rest.PayloadSchemaType.KEYWORD),
("tags", rest.PayloadSchemaType.KEYWORD),
]:
_ensure_index(client, chunks, field, schema)
# EDGES
for field, schema in [
("note_id", rest.PayloadSchemaType.KEYWORD),
("kind", rest.PayloadSchemaType.KEYWORD),
("scope", rest.PayloadSchemaType.KEYWORD),
("source_id", rest.PayloadSchemaType.KEYWORD),
("target_id", rest.PayloadSchemaType.KEYWORD),
("chunk_id", rest.PayloadSchemaType.KEYWORD),
]:
_ensure_index(client, edges, field, schema)
__all__ = [
"QdrantConfig",
"get_client",
"ensure_collections",
"ensure_payload_indexes",
"collection_names",
]