File size: 10,667 Bytes
daafb32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f780124
 
daafb32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f780124
 
daafb32
 
f780124
 
daafb32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
"""
Qdrant vector database interface for ResearchPilot.

RUNS LOCALLY - no server needed, no Docker, no cloud account.
Qdrant client in local mode stores everything in a directory
on disk, exactly like SQLite does for relational data.

Data lives in: data/qdrant_db/
"""

import json
import uuid
import numpy as np
from pathlib import Path
from typing import Optional

from qdrant_client import QdrantClient
from qdrant_client.models import (
    Distance,
    VectorParams,
    PointStruct,
    Filter,
    FieldCondition,
    MatchValue,
    Range,
    SearchRequest,
)
from tqdm import tqdm


from src.utils.logger import get_logger
from config.settings import (
    QDRANT_COLLECTION_NAME,
    QDRANT_PATH,
    EMBEDDING_DIMENSION,
    TOP_K_RETRIEVAL,
)

logger = get_logger(__name__)

# How many points to upload to Qdrant at once
# Too large = memory spike. Too small = many round trips.
UPSERT_BATCH_SIZE = 256


class QdrantStore:
    """
    Manages the Qdrant vector database for chunk storage and retrieval.

    UPSERT PATTERN:
    We use 'upsert' (update + insert) instead of 'insert'.
    If a chunk already exists, upsert updates it.
    If it doesn't exist, upsert creates it.
    This makes our indexing pipeline idempotent - safe to re-run.
    """

    def __init__(self):
        # Local mode: pass path= instead of url=
        # Qdrant creates/opens a local database at this path
        # No server process needed - runs in-process
        logger.info(f"Connecting to local Qdrant at: {QDRANT_PATH}")
        self.client = QdrantClient(path = QDRANT_PATH)
        self.collection_name = QDRANT_COLLECTION_NAME

    
    def collection_exists(self) -> bool:
        """Check if our collection already exists in Qdrant."""
        collections = self.client.get_collections().collections
        names = [c.name for c in collections]
        return self.collection_name in names


    def get_collection_size(self) -> int:
        """Return number of points currently in the collections."""
        if not self.collection_exists():
            return 0
        info = self.client.get_collection(self.collection_name)
        return info.points_count

    
    def create_collection(self, recreate: bool = False):
        """
        Create the Qdrant collection for research paper chunks.

        Args:
            recreate: If True, delete existing collection and rebuild.
                      Use this when you want a clean re-index.

        COLLECTION CONFIGURATION:
            size=768      -> matches BGE-base-en-v1.5 output dimension
            distance=COSINE -> similarity metric

        WHY COSINE DISTANCE:
            Our embeddings are L2-normalized (magnitude = 1.0).
            For normalized vectors: cosine_similarity = dot_product
            Qdrant's COSINE metric handles this correctly.
            Using DOT_PRODUCT would also work but COSINE is more explicit.
        """

        if self.collection_exists():
            if recreate:
                logger.warning(f"Deleting existing collection: {self.collection_name}")
                self.client.delete_collection(self.collection_name)
            else:
                size = self.get_collection_size()
                logger.info(
                    f"Collection: '{self.collection_name}' already exists "
                    f"with {size:,} points. Skipping creation."
                )
                return

        logger.info(f"Creating collection: {self.collection_name}")
        self.client.create_collection(
            collection_name = self.collection_name,
            vectors_config = VectorParams(
                size        = EMBEDDING_DIMENSION,
                distance    = Distance.COSINE,
            ),
        )
        logger.info(f"Collection created: {self.collection_name}")


    def index_chunks(
        self,
        embeddings: np.ndarray,
        chunk_ids:  list[str],
        metadata:   list[dict],
        texts:      list[str]
    ) -> int:
        """
        Upload embeddings + metadata into Qdrant.

        Args:
            embeddings:  numpy array (N, 768)
            chunk_ids:   list of N chunk ID strings
            metadata:    list of N metadata dicts
            texts:       list of N chunk text strings

        Returns:
            Number of points successfully indexed

        QDRANT POINT STRUCTURE:
            Each point needs:
            - id:      unique identifier (we use the chunk_id UUID)
            - vector:  the embedding as a Python list of floats
            - payload: dict of any metadata we want to store/filter

        WHY INCLUDE TEXT IN PAYLOAD:
            When we retrieve a point, we need the text to show to the
            user and to send to the LLM. Storing it in the payload
            means ONE database query returns everything we need.
            Alternative would be a separate text lookup - slower and
            more complex.
        """
        assert len(embeddings) == len(chunk_ids) == len(metadata) == len(texts), \
            "All inputs must have the same length"

        total_indexed = 0

        # Process in batches to avoid memory spikes
        for batch_start in tqdm(
            range(0, len(embeddings), UPSERT_BATCH_SIZE),
            desc = "Indexing into Qdrant"
        ):
            batch_end = min(batch_start + UPSERT_BATCH_SIZE, len(embeddings))

            # Build PointStruct objects for this batch
            points = []
            for i in range(batch_start, batch_end):
                # Qdrant requires UUID format for point IDs
                # Our chunk_ids are already UUIDs from Phase 5
                point = PointStruct(
                    id      = chunk_ids[i],
                    vector  = embeddings[i].tolist(),    # Numpy -> Python List
                    payload = {
                        # Store ALL metadata in payload for retrieval
                        **metadata[i],
                        "text": texts[i],   # Include chunk text
                        "publication_year": int(metadata[i].get("published_date", "0000")[:4]),
                    }
                )
                points.append(point)

            # Upsert this batch
            self.client.upsert(
                collection_name = self.collection_name,
                points          = points,
            )
            total_indexed += len(points)


        logger.info(
            f"Indexing complete. "
            f"Total points in collection: {self.get_collection_size():,}"
        )
        return total_indexed


    def search(
        self,
        query_vector:    np.ndarray,
        top_k:           int = TOP_K_RETRIEVAL,
        filter_category: Optional[str] = None,
        filter_year_gte: Optional[int] = None,
    ) -> list[dict]:
        """
        Search for most similar chunks to a query vector.

        Args:
            query_vector:    768-dimensional query embedding
            top_k:           How many results to return
            filter_category: Only return chunks from this ArXiv category
            filter_year_gte: Only return chunks from this year or later

        Returns:
            List of result dicts, each containing:
            {
                "chunk_id":    str,
                "score":       float (cosine similarity, 0-1),
                "text":        str,
                "paper_id":    str,
                "title":       str,
                "authors":     list,
                "published_date": str,
                ...all other payload fields
            }

        FILTERING IN QDRANT:
            Qdrant applies metadata filters DURING vector search,
            not after. This means it only scores vectors that match
            the filter - much faster than post-filtering.

            Example: filter_year_gte=2024 means:
            "Find the top-20 most similar vectors, but ONLY consider
             vectors from papers published in 2024 or later"
        """
        # Build optional filter
        qdrant_filter = self._build_filter(filter_category, filter_year_gte)


        # Execute search
        results = self.client.query_points(
            collection_name = self.collection_name,
            query           = query_vector.tolist(),
            limit           = top_k,
            query_filter    = qdrant_filter,
            with_payload    = True,      # Return metadata with results
            with_vectors    = False      # Don't return the vectors (saves bandwidth)
        ).points

        # Convert Qdrant ScoredPoint objects to plain dicts
        return [
            {
                "chunk_id": str(r.id),
                "score"   : round(r.score, 4),
                **r.payload,    # Unpack all payload fields (text, title, etc.)
            }
            for r in results
        ]


    def _build_filter(
        self,
        category:   Optional[str],
        year_gte:   Optional[int],
    ) -> Optional[Filter]:
        """
        Build a Qdrant filter from optional parameters.

        Returns None if no filters specified (search everything).

        QDRANT FILTER SYNTAX:
            Filter(must=[condition1, condition2])
            means: results must satisfy condition1 AND condition2

            MatchValue -> exact match (equality check)
            Range      -> numeric range (gte, lte, gt, lt)
        """
        conditions = []

        if category:
            conditions.append(
                FieldCondition(
                    key   = "primary_category",
                    match = MatchValue(value = category) 
                )
            )

        if year_gte:
            # publication_year is stored as an integer (e.g. 2026)
            # Range(gte=year_gte) filters to papers from that year onwards
            conditions.append(
                FieldCondition(
                    key     = "publication_year",
                    range   = Range(gte = year_gte)
                )
            )

        if not conditions:
            return None

        return Filter(must = conditions)


    def get_collection_info(self) -> dict:
        """Return summary information about the collection."""
        if not self.collection_exists():
            return {"status": "collection_not_found"}

        info = self.client.get_collection(self.collection_name)

        return {
            "collection_name": self.collection_name,
            "points_count"   : info.points_count,
            "status"         : str(info.status),
            "vector_size"    : info.config.params.vectors.size,
            "distance"       : str(info.config.params.vectors.distance),
        }