Vector Database Code Search Examples

Real-world examples demonstrating the power of semantic code search with Claude Code and vector databases.

Your First Semantic Search: A Step-by-Step Guide

Before diving into advanced patterns, let’s walk through a simple, complete workflow. This will provide a foundation for the more complex use cases below.

1. Embed Your Codebase: First, you must process your code into vectors that the database can understand. This “embedding” process is typically a script you run once or whenever your code changes.

2. Write the Search Function: Next, here is a simple client-side function to query your vector database. This could be part of a CLI tool or a custom editor extension.

// src/searchClient.ts
async function semanticSearch(query: string) {
  const response = await fetch('https://your-vector-db-endpoint.com/search', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ query_text: query, top_k: 5 })
  });
  if (!response.ok) {
    throw new Error('Search request failed');
  }
  return response.json();
}

3. Perform a Search & Interpret Results: Now, you can use this function to find code related to a concept, like ‘authentication’.

// Example usage
const results = await semanticSearch("user authentication middleware");
console.log(results);
// The results will be a list of code snippets and file paths
// that are semantically similar to your query.

This simple example provides the fundamental building blocks for the more advanced patterns detailed below.

🎯 Example Searches

1. Find Similar Implementations

Query: “Functions similar to lodash debounce”

// Search for debounce-like implementations
const results = await search.findSimilar({
  referenceCode: `
    function debounce(func, wait) {
      let timeout;
      return function executedFunction(...args) {
        const later = () => {
          clearTimeout(timeout);
          func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
      };
    }
  `,
  options: {
    minSimilarity: 0.7,
    excludeLibraries: true
  }
});
 
// Results might include:
// 1. Custom throttle implementations
// 2. Rate limiting functions  
// 3. Event batching utilities
// 4. Request debouncing middleware

Query: “Repository pattern with dependency injection”

const results = await search.searchPattern({
  query: "repository pattern with dependency injection typescript",
  filters: {
    hasInterface: true,
    hasConstructor: true,
    minComplexity: 'medium'
  }
});
 
// Example result:
export interface UserRepository {
  findById(id: string): Promise<User>;
  save(user: User): Promise<void>;
}
 
@injectable()
export class MongoUserRepository implements UserRepository {
  constructor(
    @inject(TYPES.Database) private db: Database
  ) {}
 
  async findById(id: string): Promise<User> {
    return this.db.collection('users').findOne({ _id: id });
  }
}

3. Security Vulnerability Patterns

Query: “SQL injection vulnerable code”

const vulnerabilities = await search.findVulnerabilities({
  pattern: "sql injection",
  includeFixed: true // Show both vulnerable and fixed versions
});
 
// Vulnerable example found:
app.get('/user/:id', (req, res) => {
  // ❌ Vulnerable to SQL injection
  const query = `SELECT * FROM users WHERE id = ${req.params.id}`;
  db.query(query, (err, result) => {
    res.json(result);
  });
});
 
// Fixed version also found:
app.get('/user/:id', (req, res) => {
  // ✅ Safe parameterized query
  const query = 'SELECT * FROM users WHERE id = ?';
  db.query(query, [req.params.id], (err, result) => {
    res.json(result);
  });
});

4. Performance Optimization Patterns

Query: “Memoization implementations for expensive calculations”

const optimizations = await search.findOptimizations({
  type: "memoization",
  context: "expensive calculations"
});
 
// Example results:
// 1. React useMemo patterns
const ExpensiveComponent = ({ data }) => {
  const processedData = useMemo(() => {
    return data.map(item => complexTransformation(item));
  }, [data]);
};
 
// 2. Generic memoization decorator
function memoize(target: any, propertyKey: string) {
  const cache = new Map();
  const original = target[propertyKey];
  
  target[propertyKey] = function(...args: any[]) {
    const key = JSON.stringify(args);
    if (cache.has(key)) return cache.get(key);
    
    const result = original.apply(this, args);
    cache.set(key, result);
    return result;
  };
}
 
// 3. LRU cache implementation
class LRUMemoize {
  constructor(private maxSize: number) {}
  // ... implementation
}

🏗️ Use Case Implementations

Use Case 1: Code Review Assistant

class CodeReviewAssistant {
  constructor(
    private searchEngine: SemanticSearchEngine,
    private claude: ClaudeCode
  ) {}
 
  async reviewPullRequest(pr: PullRequest) {
    const issues = [];
 
    for (const file of pr.changedFiles) {
      // Find similar code in the codebase
      const similar = await this.searchEngine.findSimilar({
        code: file.content,
        threshold: 0.85
      });
 
      if (similar.length > 0) {
        issues.push({
          type: 'duplication',
          file: file.path,
          message: `Similar code found in ${similar[0].filepath}`,
          suggestion: 'Consider extracting to shared utility'
        });
      }
 
      // Check for anti-patterns
      const antipatterns = await this.searchEngine.search(
        `anti-pattern ${file.language}`,
        { 
          compareWith: file.content 
        }
      );
 
      if (antipatterns.matches.length > 0) {
        const review = await this.claude.analyze({
          code: file.content,
          antipatterns: antipatterns.matches,
          instruction: 'Identify which anti-patterns are present'
        });
 
        issues.push(...review.findings);
      }
    }
 
    return this.formatReview(issues);
  }
}

Use Case 2: Intelligent Code Completion

class SmartCodeCompletion {
  async getSuggestions(context: CodeContext) {
    // Extract current function signature
    const signature = this.extractSignature(context);
    
    // Search for similar function implementations
    const query = `function ${signature.name} ${signature.params.join(' ')}`;
    const similar = await this.search.findSimilarFunctions(query);
 
    // Use Claude to generate contextual suggestions
    const suggestions = await this.claude.complete({
      prompt: `Given these similar implementations:
        ${similar.map(s => s.content).join('\n\n')}
        
        Generate completion for:
        ${context.currentCode}
        
        Suggestions:`,
      max_tokens: 200
    });
 
    return this.rankSuggestions(suggestions, context);
  }
}

Use Case 3: Documentation Generator

class DocumentationGenerator {
  async generateDocs(filepath: string) {
    const code = await this.loadFile(filepath);
    
    // Find similar documented code
    const documented = await this.search.search({
      query: `well documented ${this.detectLanguage(filepath)} similar to`,
      referenceCode: code,
      filters: {
        hasComments: true,
        hasJSDoc: true
      }
    });
 
    // Learn documentation patterns
    const patterns = this.extractDocPatterns(documented);
    
    // Generate documentation
    const docs = await this.claude.generate({
      task: 'document',
      code: code,
      examples: patterns,
      style: 'JSDoc'
    });
 
    return this.formatDocumentation(docs);
  }
}

Use Case 4: Refactoring Suggestions

class RefactoringSuggester {
  async suggestRefactoring(code: string, goal: string) {
    // Find examples of the desired pattern
    const examples = await this.search.search({
      query: goal,
      filters: {
        quality: 'high',
        tested: true
      }
    });
 
    // Analyze current code
    const analysis = await this.analyzeCode(code);
    
    // Generate refactoring plan
    const plan = await this.claude.complete({
      prompt: `Refactor this code to achieve: ${goal}
        
        Current code:
        ${code}
        
        Good examples found:
        ${examples.slice(0, 3).map(e => e.preview).join('\n')}
        
        Provide step-by-step refactoring:`,
      max_tokens: 500
    });
 
    return this.createRefactoringSteps(plan, code, examples);
  }
}
 
// Usage
const suggestions = await refactorer.suggestRefactoring(
  legacyCode,
  "modern async/await pattern with proper error handling"
);

📊 Query Examples by Category

Design Patterns

const patterns = {
  creational: [
    "singleton pattern thread safe",
    "factory pattern with dependency injection",
    "builder pattern for complex objects"
  ],
  structural: [
    "adapter pattern for third party APIs",
    "decorator pattern for middleware",
    "proxy pattern for caching"
  ],
  behavioral: [
    "observer pattern event emitter",
    "strategy pattern for payment processing",
    "command pattern for undo functionality"
  ]
};

Algorithm Searches

const algorithms = {
  sorting: [
    "quicksort with custom comparator",
    "merge sort for large datasets",
    "sorting algorithm stable in-place"
  ],
  searching: [
    "binary search in rotated array",
    "depth first search graph traversal",
    "A* pathfinding implementation"
  ],
  optimization: [
    "dynamic programming memoization",
    "greedy algorithm for scheduling",
    "backtracking for constraint satisfaction"
  ]
};

Framework-Specific

const frameworkQueries = {
  react: [
    "custom hooks for form validation",
    "React context for global state",
    "performance optimization with memo"
  ],
  vue: [
    "Vue 3 composition API store",
    "reactive computed properties",
    "custom directives for DOM manipulation"
  ],
  angular: [
    "dependency injection service pattern",
    "RxJS observable error handling",
    "Angular guards for route protection"
  ]
};

🔍 Advanced Search Techniques

// Search using code + comments + documentation
const results = await search.multiModal({
  code: functionImplementation,
  comments: "Handles user authentication",
  documentation: "JWT-based auth middleware",
  weights: {
    code: 0.5,
    comments: 0.3,
    documentation: 0.2
  }
});
// Find code evolution over time
const evolution = await search.temporal({
  query: "authentication implementation",
  timeRange: {
    from: "2023-01-01",
    to: "2025-01-01"
  },
  showEvolution: true
});
 
// Results show how patterns evolved
evolution.forEach(version => {
  console.log(`${version.date}: ${version.approach}`);
  // 2023: Cookie-based sessions
  // 2024: JWT tokens
  // 2025: Passkeys integration
});
// Find equivalent implementations across languages
const crossLang = await search.crossLanguage({
  referenceCode: pythonFunction,
  targetLanguages: ['typescript', 'go', 'rust'],
  preserveBehavior: true
});
 
// Returns functionally equivalent code in each language

🚀 Integration Examples

VS Code Extension

// vscode-extension/src/search.ts
export function activate(context: vscode.ExtensionContext) {
  const searchCommand = vscode.commands.registerCommand(
    'claude-code-search.search',
    async () => {
      const query = await vscode.window.showInputBox({
        prompt: 'Enter semantic search query'
      });
 
      const results = await searchEngine.search(query);
      
      const quickPick = vscode.window.createQuickPick();
      quickPick.items = results.map(r => ({
        label: path.basename(r.filepath),
        description: r.preview,
        detail: `Score: ${r.score.toFixed(2)}`,
        filepath: r.filepath
      }));
 
      quickPick.onDidSelectItem(item => {
        vscode.workspace.openTextDocument(item.filepath)
          .then(doc => vscode.window.showTextDocument(doc));
      });
 
      quickPick.show();
    }
  );
}

CLI Tool

# Search for patterns
code-search "repository pattern with caching"
 
# Find similar code
code-search --similar ./src/auth.ts --threshold 0.8
 
# Search with filters
code-search "error handling" --lang typescript --after 2024-01-01
 
# Export results
code-search "optimization patterns" --export results.json

🔗 Resources

🗺️ Navigation

← Implementation | Vector Databases | Optimization →