PHP code example of andydefer / inverted-index-search

1. Go to this page and download the library: Download andydefer/inverted-index-search library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

andydefer / inverted-index-search example snippets


use AndyDefer\AlgoKIT\Algorithms\InvertedIndex;
use AndyDefer\InvertedIndexSearch\Services\InvertedIndexSearchService;
use AndyDefer\InvertedIndexSearch\Services\InvertedIndexExpressionEvaluator;
use AndyDefer\StorageKit\Storage\MemoryStorage;

$storage = new MemoryStorage();
$index = new InvertedIndex($storage, 'documents');
$evaluator = new InvertedIndexExpressionEvaluator($index);
$search = new InvertedIndexSearchService($index, $evaluator);

// Indexation des documents
$documents = [
    ['id' => 'doc1', 'tokens' => ['php', 'laravel', 'web']],
    ['id' => 'doc2', 'tokens' => ['php', 'python', 'data']],
    ['id' => 'doc3', 'tokens' => ['php', 'laravel', 'vuejs']],
    ['id' => 'doc4', 'tokens' => ['python', 'django', 'web']],
];

foreach ($documents as $doc) {
    $index->add(InvertedIndexRecord::from([
        'document_id' => $doc['id'],
        'tokens' => $doc['tokens'],
    ]));
}

// Recherches
$results1 = $search->and(['php', 'laravel']);
// → doc1, doc3

$results2 = $search->or(['php', 'python']);
// → doc1, doc2, doc3, doc4

$results3 = $search->not('php', 'python');
// → doc1, doc3

$results4 = $search->expression('(php AND laravel) OR (python AND django)');
// → doc1, doc3, doc4

// Requête : php AND (laravel OR vuejs) AND NOT python
$results = $search->query()
    ->where('php')
    ->whereGroup(function($q) {
        $q->where('laravel')
          ->orWhere('vuejs');
    })
    ->whereNot('python')
    ->get();

// Construction dynamique
$builder = $search->query();

if ($mustHave) {
    foreach ($mustHave as $token) {
        $builder->where($token);
    }
}

if ($shouldHave) {
    $builder->whereGroup(function($q) use ($shouldHave) {
        foreach ($shouldHave as $token) {
            $q->orWhere($token);
        }
    });
}

$results = $builder->get();

// Expression simple
$results = $evaluator->evaluate('php AND laravel');

// Expression avec NOT
$results = $evaluator->evaluate('php AND (NOT python)');

// Expression complexe imbriquée
$results = $evaluator->evaluate('(php AND laravel) OR (python AND django)');

// Expression avec plusieurs niveaux
$results = $evaluator->evaluate('php AND (laravel OR vuejs) AND (NOT python)');

// Syntaxe directe
$results = $search->and(['php', 'laravel']);

// Via expression
$results = $search->expression('php AND laravel');

// Via QueryBuilder
$results = $search->query()->where('php')->where('laravel')->get();

// Syntaxe directe
$results = $search->or(['php', 'python']);

// Via expression
$results = $search->expression('php OR python');

// Via QueryBuilder
$results = $search->query()->where('php')->orWhere('python')->get();

// Syntaxe directe
$results = $search->not('php', 'python');

// Via expression
$results = $search->expression('php AND (NOT python)');

// Via QueryBuilder
$results = $search->query()->where('php')->whereNot('python')->get();

// Syntaxe directe
$results = $search->xor('php', 'python');

// Via expression
$results = $search->expression('php XOR python');

// Via QueryBuilder (via expression)
$results = $search->query()->expression('php XOR python')->get();

class BlogSearch
{
    private InvertedIndexSearchService $search;
    
    public function searchArticles(array $criteria): array
    {
        $builder = $this->search->query();
        
        // Tags obligatoires
        if (!empty($criteria['tags'])) {
            foreach ($criteria['tags'] as $tag) {
                $builder->where($tag);
            }
        }
        
        // Catégories (au moins une)
        if (!empty($criteria['categories'])) {
            $builder->whereGroup(function($q) use ($criteria) {
                foreach ($criteria['categories'] as $category) {
                    $q->orWhere($category);
                }
            });
        }
        
        // Exclusions
        if (!empty($criteria['exclude'])) {
            foreach ($criteria['exclude'] as $exclude) {
                $builder->whereNot($exclude);
            }
        }
        
        return $builder->get()->toArray();
    }
}

// Utilisation
$articles = $blogSearch->searchArticles([
    'tags' => ['php', 'laravel'],
    'categories' => ['web', 'api'],
    'exclude' => ['deprecated'],
]);

class ProductSearch
{
    private InvertedIndexSearchService $search;
    
    public function search(array $filters): array
    {
        $builder = $this->search->query();
        
        // Marques (AND)
        if (!empty($filters['brands'])) {
            foreach ($filters['brands'] as $brand) {
                $builder->where($brand);
            }
        }
        
        // Couleurs (OR)
        if (!empty($filters['colors'])) {
            $builder->whereGroup(function($q) use ($filters) {
                foreach ($filters['colors'] as $color) {
                    $q->orWhere($color);
                }
            });
        }
        
        // Prix (facultatif)
        if (isset($filters['price_range'])) {
            $builder->where($filters['price_range']);
        }
        
        return $builder->get()->toArray();
    }
}

// Utilisation
$products = $productSearch->search([
    'brands' => ['nike', 'adidas'],
    'colors' => ['red', 'blue', 'black'],
    'price_range' => 'premium',
]);

class LogAnalyzer
{
    private InvertedIndexSearchService $search;
    
    public function analyzeLogs(array $logs): array
    {
        $expression = 'error OR (warning AND php) NOT (debug OR trace)';
        
        $results = $this->search->expression($expression);
        
        $stats = [
            'total' => count($logs),
            'matching' => $results->count(),
            'log_ids' => $results->toArray(),
        ];
        
        return $stats;
    }
}

// Utilisation
$analyzer = new LogAnalyzer($search);
$stats = $analyzer->analyzeLogs($logs);

class SearchAPI
{
    private InvertedIndexSearchService $search;
    
    public function search(Request $request): JsonResponse
    {
        $query = $request->get('q');
        $limit = (int) $request->get('limit', 10);
        
        try {
            // L'utilisateur peut utiliser des opérateurs avancés
            $results = $this->search->expression($query);
            $limited = $results->take($limit);
            
            return response()->json([
                'success' => true,
                'results' => $limited->toArray(),
                'total' => $results->count(),
                'limit' => $limit,
            ]);
        } catch (InvalidArgumentException $e) {
            return response()->json([
                'success' => false,
                'error' => 'Invalid search expression',
                'message' => $e->getMessage(),
            ], 400);
        }
    }
}

// Requêtes API acceptées
// GET /search?q=php AND laravel
// GET /search?q=(php OR python) AND web
// GET /search?q=php AND (NOT java)
// GET /search?q=php AND (laravel OR vuejs) NOT python

class TagRecommender
{
    private InvertedIndexSearchService $search;
    
    public function recommendTags(array $existingTags, int $limit = 5): array
    {
        $builder = $this->search->query();
        
        // Tags existants
        foreach ($existingTags as $tag) {
            $builder->where($tag);
        }
        
        $results = $builder->get();
        
        // Extraire les tags associés
        $relatedTags = [];
        foreach ($results as $docId) {
            $doc = $this->getDocument($docId);
            $relatedTags = array_merge($relatedTags, $doc['tags']);
        }
        
        // Compter et trier les tags
        $counts = array_count_values($relatedTags);
        arsort($counts);
        
        // Filtrer les tags existants
        $recommended = array_diff(array_keys($counts), $existingTags);
        
        return array_slice($recommended, 0, $limit);
    }
}

// Utilisation
$recommendations = $recommender->recommendTags(['php', 'laravel']);
// → ['web', 'api', 'eloquent', 'vuejs']