#![allow(clippy::too_many_arguments)] //! Indexer module for IntentForge v2 //! //! Handles document indexing with Qdrant Cloud, including binary quantization //! and hybrid search capabilities. use anyhow::{Context, Result}; use qdrant_client::prelude::*; use qdrant_client::qdrant::{ quantization_config, vectors_config::Config as VectorConfigEnum, BinaryQuantization, Condition, CreateCollection, Distance, FieldType, Filter, PointId, PointStruct, PointsSelector, QuantizationConfig, SearchPoints, Value, VectorParams, VectorsConfig, }; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::sync::Arc; use uuid::Uuid; /// Document schema for IntentForge #[derive(Debug, Clone, Serialize, Deserialize)] pub struct IntentDocument { pub id: String, pub title: String, pub content: String, pub description: Option, pub url: String, pub source: String, pub category: String, pub tags: Vec, pub published_at: Option, // Media #[serde(default = "default_media_type")] pub media_type: String, #[serde(skip_serializing_if = "Option::is_none")] pub thumbnail_url: Option, // Image-specific fields #[serde(skip_serializing_if = "Option::is_none")] pub image_hash: Option, #[serde(skip_serializing_if = "Option::is_none")] pub image_thumbhash: Option, #[serde(skip_serializing_if = "Option::is_none")] pub image_dimensions: Option<(u32, u32)>, // Scores #[serde(rename = "intent_score")] pub intent_score: f32, #[serde(rename = "relevance_score")] pub relevance_score: f32, #[serde(rename = "commercial_score")] #[serde(default)] pub commercial_score: f32, #[serde(rename = "spam_score")] #[serde(default)] pub spam_score: f32, // Vector embeddings (Stored in Qdrant named vectors) #[serde(skip)] pub vector: Option>, } fn default_media_type() -> String { "text".to_string() } impl IntentDocument { /// Create a new document with vector pub fn new( id: String, title: String, content: String, url: String, source: String, category: String, intent_score: f32, relevance_score: f32, vector: Vec, ) -> Self { Self { id, title, content, description: None, url, source, category, tags: Vec::new(), published_at: None, media_type: default_media_type(), thumbnail_url: None, image_hash: None, image_thumbhash: None, image_dimensions: None, intent_score, relevance_score, commercial_score: 0.0, spam_score: 0.0, vector: Some(vector), } } /// Convert to Qdrant PointStruct pub fn to_point(&self, _collection_name: &str) -> Result { let mut payload_map: HashMap<&str, Value> = HashMap::new(); payload_map.insert("id", self.id.clone().into()); payload_map.insert("title", self.title.clone().into()); payload_map.insert("content", self.content.clone().into()); if let Some(desc) = &self.description { payload_map.insert("description", desc.clone().into()); } payload_map.insert("url", self.url.clone().into()); payload_map.insert("source", self.source.clone().into()); payload_map.insert("category", self.category.clone().into()); payload_map.insert("tags", self.tags.clone().into()); if let Some(pub_at) = self.published_at { payload_map.insert("published_at", pub_at.into()); } payload_map.insert("media_type", self.media_type.clone().into()); if let Some(thumb) = &self.thumbnail_url { payload_map.insert("thumbnail_url", thumb.clone().into()); } if let Some(hash) = &self.image_hash { payload_map.insert("image_hash", hash.clone().into()); } if let Some(thash) = &self.image_thumbhash { payload_map.insert("image_thumbhash", thash.clone().into()); } if let Some(dims) = self.image_dimensions { payload_map.insert("image_width", (dims.0 as i64).into()); payload_map.insert("image_height", (dims.1 as i64).into()); } payload_map.insert("intent_score", (self.intent_score as f64).into()); payload_map.insert("relevance_score", (self.relevance_score as f64).into()); payload_map.insert("commercial_score", (self.commercial_score as f64).into()); payload_map.insert("spam_score", (self.spam_score as f64).into()); let payload = Payload::from(payload_map); let point_id = Uuid::new_v5(&Uuid::NAMESPACE_URL, self.id.as_bytes()).to_string(); let vector = self.vector.clone().context("Document missing vector")?; Ok(PointStruct::new(point_id, vector, payload)) } /// Set extra scores pub fn with_extra_scores(mut self, commercial: f32, spam: f32) -> Self { self.commercial_score = commercial; self.spam_score = spam; self } /// Set description pub fn with_description(mut self, description: String) -> Self { self.description = Some(description); self } /// Set tags pub fn with_tags(mut self, tags: Vec) -> Self { self.tags = tags; self } /// Set published timestamp pub fn with_published_at(mut self, timestamp: i64) -> Self { self.published_at = Some(timestamp); self } /// Set image metadata (hash, thumbhash, dimensions) pub fn with_image_metadata( mut self, hash: Option, thumbhash: Option, dimensions: Option<(u32, u32)>, ) -> Self { self.media_type = "image".to_string(); self.image_hash = hash; self.image_thumbhash = thumbhash; self.image_dimensions = dimensions; self } /// Set media type pub fn with_media_type(mut self, media_type: String) -> Self { self.media_type = media_type; self } /// Truncate content to a snippet if not already short pub fn with_snippet(mut self, max_length: usize) -> Self { if self.content.len() > max_length { let mut snippet = self.content.chars().take(max_length).collect::(); snippet.push_str("..."); self.content = snippet; } self } } /// Indexer wrapper for Qdrant operations #[derive(Clone)] pub struct Indexer { pub client: Arc, pub collection_name: String, pub redis: Option>, } impl Indexer { /// Create a new indexer instance pub fn new(url: &str, api_key: Option<&str>, collection_name: &str) -> Result { let mut config = QdrantClientConfig::from_url(url); if let Some(key) = api_key { config.api_key = Some(key.to_string()); } let client = QdrantClient::new(Some(config))?; Ok(Self { client: Arc::new(client), collection_name: collection_name.to_string(), redis: None, }) } pub fn with_redis(mut self, redis: Arc) -> Self { self.redis = Some(redis); self } pub fn get_redis(&self) -> Arc { self.redis .as_ref() .expect("RedisStore not initialized in Indexer") .clone() } /// Ensure collection exists with correct settings pub async fn ensure_settings(&self) -> Result<()> { if self.client.collection_exists(&self.collection_name).await? { tracing::info!("Collection {} already exists", self.collection_name); return Ok(()); } tracing::info!( "Creating collection {} with Binary Quantization", self.collection_name ); self.client .create_collection(&CreateCollection { collection_name: self.collection_name.clone(), vectors_config: Some(VectorsConfig { config: Some(VectorConfigEnum::Params(VectorParams { size: 384, distance: Distance::Cosine.into(), ..Default::default() })), }), quantization_config: Some(QuantizationConfig { quantization: Some(quantization_config::Quantization::Binary( BinaryQuantization { always_ram: Some(true), }, )), }), ..Default::default() }) .await?; // Create field indexes for title and content self.client .create_field_index(&self.collection_name, "title", FieldType::Text, None, None) .await?; self.client .create_field_index( &self.collection_name, "content", FieldType::Text, None, None, ) .await?; // Create standard keyword indexes for filtering self.client .create_field_index( &self.collection_name, "category", FieldType::Keyword, None, None, ) .await?; self.client .create_field_index( &self.collection_name, "media_type", FieldType::Keyword, None, None, ) .await?; self.client .create_field_index( &self.collection_name, "source", FieldType::Keyword, None, None, ) .await?; Ok(()) } /// Index a single document pub async fn index_document(&self, doc: &IntentDocument) -> Result<()> { let point = doc.to_point(&self.collection_name)?; self.client .upsert_points(&self.collection_name, None, vec![point], None) .await?; Ok(()) } /// Index multiple documents in batch pub async fn index_documents(&self, docs: &[IntentDocument]) -> Result<()> { if docs.is_empty() { return Ok(()); } let mut points = Vec::new(); for doc in docs { points.push(doc.to_point(&self.collection_name)?); } self.client .upsert_points(&self.collection_name, None, points, None) .await?; Ok(()) } /// Delete a document by ID pub async fn delete_document(&self, id: &str) -> Result<()> { let point_id = Uuid::new_v5(&Uuid::NAMESPACE_URL, id.as_bytes()).to_string(); let selector: PointsSelector = vec![PointId::from(point_id)].into(); self.client .delete_points(&self.collection_name, None, &selector, None) .await?; Ok(()) } /// Search (Full-text fallback for legacy Rust callers) pub async fn search( &self, query_text: &str, _filter_str: Option<&str>, limit: Option, ) -> Result> { let mut filter = None; if !query_text.is_empty() { // Full-text match on title filter = Some(Filter::all(vec![Condition::matches( "title", query_text.to_string(), )])); } let result = self .client .search_points(&SearchPoints { collection_name: self.collection_name.clone(), vector: vec![0.0; 384], // Dummy vector for payload-only search filter, limit: limit.unwrap_or(30) as u64, with_payload: Some(true.into()), ..Default::default() }) .await?; let mut docs = Vec::new(); for point in result.result { let doc_json = serde_json::to_value(point.payload)?; let doc: IntentDocument = serde_json::from_value(doc_json)?; docs.push(doc); } Ok(docs) } /// Vector Search (Primary method for Python Query Layer) pub async fn search_vector( &self, query_vector: Vec, filter: Option, limit: usize, ) -> Result> { let result = self .client .search_points(&SearchPoints { collection_name: self.collection_name.clone(), vector: query_vector, filter, limit: limit as u64, with_payload: Some(true.into()), ..Default::default() }) .await?; let mut docs = Vec::new(); for point in result.result { let doc_json = serde_json::to_value(point.payload)?; let doc: IntentDocument = serde_json::from_value(doc_json)?; docs.push(doc); } Ok(docs) } /// Batch update documents pub async fn batch_update_documents(&self, docs: &[IntentDocument]) -> Result<()> { self.index_documents(docs).await } } #[cfg(test)] mod tests { use super::*; #[test] fn test_document_creation() { let vector = vec![0.1; 384]; let doc = IntentDocument::new( "test-1".to_string(), "Test Title".to_string(), "Test content".to_string(), "https://example.com".to_string(), "test-source".to_string(), "tech".to_string(), 0.8, 0.9, vector, ); assert_eq!(doc.id, "test-1"); assert!(doc.vector.is_some()); } }