File size: 12,343 Bytes
0ca462b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
#![allow(dead_code)]
//! Query expansion module for IntentForge v2
//!
//! Provides synonym, acronym, and related term expansion for search queries.
//! Uses curated term lists for technology domains.

use std::collections::HashMap;
use std::sync::LazyLock;

/// Global synonym map for tech/AI domain
static SYNONYM_MAP: LazyLock<HashMap<&'static str, Vec<&'static str>>> = LazyLock::new(|| {
    let mut map = HashMap::new();

    // Machine Learning / AI
    map.insert("ml", vec!["machine learning", "artificial intelligence"]);
    map.insert("ai", vec!["artificial intelligence", "machine learning"]);
    map.insert(
        "nlp",
        vec![
            "natural language processing",
            "text analysis",
            "language model",
        ],
    );
    map.insert(
        "llm",
        vec!["large language model", "generative ai", "chatgpt"],
    );
    map.insert(
        "deep learning",
        vec!["neural network", "deep neural network", "CNN", "RNN"],
    );
    map.insert(
        "neural network",
        vec!["deep learning", "neural net", "perceptron"],
    );
    map.insert(
        "transformer",
        vec!["attention mechanism", "BERT", "GPT", "language model"],
    );
    map.insert(
        "computer vision",
        vec!["image recognition", "object detection", "CNN"],
    );
    map.insert(
        "reinforcement learning",
        vec!["RL", "Q-learning", "policy gradient"],
    );

    // Programming Languages
    map.insert("js", vec!["javascript", "ECMAScript", "Node.js"]);
    map.insert("ts", vec!["typescript", "JavaScript superset"]);
    map.insert("py", vec!["python", "Python programming"]);
    map.insert("rs", vec!["rust", "Rust programming", "memory safe"]);
    map.insert("cpp", vec!["C++", "C plus plus"]);
    map.insert("cs", vec!["C#", "C sharp", "dotnet"]);
    map.insert("go", vec!["golang", "Go programming"]);
    map.insert("rb", vec!["ruby", "Ruby programming"]);
    map.insert("java", vec!["JVM", "Java programming"]);
    map.insert("kt", vec!["kotlin", "Kotlin programming", "Android"]);

    // Web Development
    map.insert(
        "react",
        vec!["React.js", "ReactJS", "frontend framework", "hooks"],
    );
    map.insert("vue", vec!["Vue.js", "VueJS", "frontend framework"]);
    map.insert(
        "angular",
        vec![
            "Angular.js",
            "AngularJS",
            "frontend framework",
            "TypeScript",
        ],
    );
    map.insert(
        "svelte",
        vec!["Svelte.js", "SvelteJS", "frontend framework"],
    );
    map.insert(
        "next.js",
        vec!["NextJS", "React framework", "SSR", "Vercel"],
    );
    map.insert("nuxt", vec!["NuxtJS", "Vue framework", "SSR"]);
    map.insert(
        "rest",
        vec!["REST API", "RESTful", "HTTP API", "web service"],
    );
    map.insert("graphql", vec!["GraphQL API", "query language", "Apollo"]);
    map.insert("api", vec!["API design", "web service", "endpoint", "REST"]);
    map.insert(
        "frontend",
        vec!["client-side", "UI", "user interface", "browser"],
    );
    map.insert("backend", vec!["server-side", "API", "database", "server"]);
    map.insert(
        "fullstack",
        vec!["full stack", "frontend", "backend", "web development"],
    );

    // Databases
    map.insert(
        "sql",
        vec!["SQL database", "relational database", "PostgreSQL", "MySQL"],
    );
    map.insert(
        "nosql",
        vec!["NoSQL database", "document store", "MongoDB", "Redis"],
    );
    map.insert("postgres", vec!["PostgreSQL", "SQL database", "relational"]);
    map.insert("mongo", vec!["MongoDB", "NoSQL", "document database"]);
    map.insert(
        "redis",
        vec!["Redis cache", "in-memory database", "key-value store"],
    );
    map.insert(
        "elasticsearch",
        vec!["Elasticsearch", "search engine", "full-text search"],
    );
    map.insert(
        "database",
        vec!["DB", "data store", "persistence", "SQL", "NoSQL"],
    );
    map.insert(
        "indexing",
        vec!["database index", "query optimization", "performance"],
    );

    // DevOps / Cloud
    map.insert(
        "docker",
        vec!["container", "containerization", "Docker Compose"],
    );
    map.insert(
        "kubernetes",
        vec!["k8s", "container orchestration", "K8s cluster"],
    );
    map.insert(
        "k8s",
        vec![
            "kubernetes",
            "container orchestration",
            "pods",
            "deployments",
        ],
    );
    map.insert(
        "ci/cd",
        vec![
            "continuous integration",
            "continuous deployment",
            "pipeline",
            "Jenkins",
            "GitHub Actions",
        ],
    );
    map.insert(
        "cicd",
        vec!["CI/CD", "continuous integration", "continuous deployment"],
    );
    map.insert(
        "devops",
        vec!["CI/CD", "automation", "infrastructure", "deployment"],
    );
    map.insert(
        "aws",
        vec!["Amazon Web Services", "cloud", "EC2", "S3", "Lambda"],
    );
    map.insert("azure", vec!["Microsoft Azure", "cloud", "Microsoft cloud"]);
    map.insert(
        "gcp",
        vec!["Google Cloud Platform", "cloud", "Google cloud"],
    );
    map.insert(
        "cloud",
        vec!["AWS", "Azure", "GCP", "cloud computing", "serverless"],
    );
    map.insert(
        "terraform",
        vec!["infrastructure as code", "IaC", "HashiCorp"],
    );
    map.insert(
        "ansible",
        vec!["configuration management", "automation", "DevOps"],
    );

    // General Tech
    map.insert("tutorial", vec!["guide", "how-to", "learn", "beginner"]);
    map.insert("guide", vec!["tutorial", "how-to", "documentation"]);
    map.insert("how-to", vec!["tutorial", "guide", "learn", "instructions"]);
    map.insert(
        "beginner",
        vec!["introduction", "getting started", "basics", "fundamentals"],
    );
    map.insert(
        "advanced",
        vec!["expert", "in-depth", "optimization", "best practices"],
    );
    map.insert(
        "best practices",
        vec!["patterns", "guidelines", "recommendations"],
    );
    map.insert(
        "optimization",
        vec!["performance", "speed", "efficiency", "tuning"],
    );
    map.insert(
        "performance",
        vec!["speed", "optimization", "benchmark", "latency"],
    );
    map.insert(
        "security",
        vec!["cybersecurity", "authentication", "encryption", "OAuth"],
    );
    map.insert(
        "testing",
        vec!["unit test", "integration test", "TDD", "quality assurance"],
    );
    map.insert(
        "debugging",
        vec!["troubleshooting", "bug fix", "error handling"],
    );

    // Data Science
    map.insert(
        "data science",
        vec!["data analysis", "analytics", "statistics", "ML"],
    );
    map.insert(
        "data analysis",
        vec!["data science", "statistics", "insights"],
    );
    map.insert(
        "pandas",
        vec!["Python data", "DataFrame", "data manipulation"],
    );
    map.insert(
        "numpy",
        vec!["Python numerical", "array", "scientific computing"],
    );
    map.insert(
        "scikit-learn",
        vec!["sklearn", "machine learning", "Python ML"],
    );
    map.insert("tensorflow", vec!["TF", "deep learning", "Google ML"]);
    map.insert("pytorch", vec!["PyTorch", "deep learning", "Facebook AI"]);

    map
});

/// Configuration for query expansion
#[derive(Debug, Clone)]
pub struct QueryExpansionConfig {
    /// Maximum number of synonyms to add per term
    pub max_synonyms_per_term: usize,
    /// Minimum query length to trigger expansion
    pub min_query_length: usize,
    /// Maximum expanded query length (words)
    pub max_expanded_length: usize,
    /// Enable acronym expansion
    pub enable_acronyms: bool,
    /// Enable related terms
    pub enable_related: bool,
}

impl Default for QueryExpansionConfig {
    fn default() -> Self {
        Self {
            max_synonyms_per_term: 2,
            min_query_length: 1,
            max_expanded_length: 20,
            enable_acronyms: true,
            enable_related: true,
        }
    }
}

/// Result of query expansion
#[derive(Debug, Clone)]
pub struct ExpandedQuery {
    pub original: String,
    pub expanded: String,
    pub added_terms: Vec<String>,
}

/// Expand query with synonyms and related terms
pub fn expand_query(query: &str, config: &QueryExpansionConfig) -> ExpandedQuery {
    let lower = query.to_lowercase();
    let words: Vec<&str> = lower.split_whitespace().collect();
    let mut added_terms = Vec::new();
    let mut expanded_parts = Vec::new();

    for word in &words {
        // Clean word (remove punctuation)
        let clean = word.trim_matches(|c: char| !c.is_alphanumeric());
        if clean.is_empty() {
            continue;
        }

        // Check for exact match in synonym map
        if let Some(synonyms) = SYNONYM_MAP.get(clean) {
            // Add original term
            expanded_parts.push(clean.to_string());

            // Add synonyms (limited)
            for synonym in synonyms.iter().take(config.max_synonyms_per_term) {
                if !query.to_lowercase().contains(synonym) {
                    added_terms.push(synonym.to_string());
                    expanded_parts.push(synonym.to_string());
                }
            }
        } else {
            // Check for multi-word term matches (e.g. "deep learning")
            let mut matched = false;
            for (term, synonyms) in SYNONYM_MAP.iter() {
                // Only match multi-word terms if the query contains the full term
                if term.contains(' ') && lower.contains(term) {
                    if !added_terms.iter().any(|t| t == term) {
                        for synonym in synonyms.iter().take(config.max_synonyms_per_term) {
                            if !query.to_lowercase().contains(synonym) {
                                added_terms.push(synonym.to_string());
                                expanded_parts.push(synonym.to_string());
                            }
                        }
                    }
                    matched = true;
                    break;
                }
            }

            // No multi-word match, keep original word
            if !matched && !expanded_parts.iter().any(|s| s == clean) {
                expanded_parts.push(clean.to_string());
            }
        }
    }

    // Limit expanded query length
    expanded_parts.truncate(config.max_expanded_length);

    ExpandedQuery {
        original: query.to_string(),
        expanded: expanded_parts.join(" "),
        added_terms,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_expand_ml_query() {
        let result = expand_query("nlp tutorial", &QueryExpansionConfig::default());
        assert!(result.expanded.contains("natural language processing"));
        assert!(result.expanded.contains("tutorial"));
        assert!(!result.added_terms.is_empty());
    }

    #[test]
    fn test_expand_acronym() {
        let result = expand_query("kubernetes deployment", &QueryExpansionConfig::default());
        assert!(result.expanded.contains("k8s"));
        assert!(result.expanded.contains("container orchestration"));
    }

    #[test]
    fn test_expand_javascript() {
        let result = expand_query("react hooks", &QueryExpansionConfig::default());
        assert!(result.expanded.contains("react"));
        // max_synonyms_per_term=2, so only first 2 synonyms are added
        assert!(result.added_terms.iter().any(|t| t == "React.js"));
        assert!(result.added_terms.iter().any(|t| t == "ReactJS"));
    }

    #[test]
    fn test_no_expansion_needed() {
        let result = expand_query(
            "machine learning tutorial",
            &QueryExpansionConfig::default(),
        );
        // Original terms should be preserved in expanded query
        assert!(result.expanded.contains("machine"));
        assert!(result.expanded.contains("learning"));
        assert!(result.expanded.contains("tutorial"));
    }

    #[test]
    fn test_short_query() {
        let result = expand_query("nlp", &QueryExpansionConfig::default());
        assert!(result.expanded.contains("natural language processing"));
    }
}