PHP code example of ogini / oginisearch-laravel-scout

1. Go to this page and download the library: Download ogini/oginisearch-laravel-scout 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/ */

    

ogini / oginisearch-laravel-scout example snippets


return [
    'base_url' => env('OGINI_BASE_URL', 'http://localhost:3000'),
    'api_key' => env('OGINI_API_KEY'),
    
    'client' => [
        'timeout' => 30,
        'retry_attempts' => 3,
        'retry_delay' => env('OGINI_BATCH_RETRY_DELAY', 100),
    ],
    
    'engine' => [
        'max_results' => 1000,
        'default_limit' => 15,
    ],
    
    'performance' => [
        'query_optimization' => [
            'enabled' => true,
            'min_term_length' => env('OGINI_MIN_TERM_LENGTH', 3),
            'max_complexity_score' => env('OGINI_MAX_COMPLEXITY_SCORE', 15),
            'performance_check_threshold' => env('OGINI_PERFORMANCE_CHECK_THRESHOLD', 100),
            'wildcard_penalty' => env('OGINI_WILDCARD_PENALTY', 5),
            'phrase_boost' => env('OGINI_PHRASE_BOOST', 1.5),
            'exact_match_boost' => env('OGINI_EXACT_MATCH_BOOST', 2.0),
            'fuzzy_match_boost' => env('OGINI_FUZZY_MATCH_BOOST', 1.0),
        ],
        'cache' => [
            'enabled' => true,
            'driver' => 'redis',
            'query_ttl' => 300,
            'result_ttl' => 1800,
            'suggestion_ttl' => 600,
        ],
        'connection_pool' => [
            'enabled' => true,
            'pool_size' => 5,
            'connection_timeout' => 5,
            'idle_timeout' => 30,
        ],
        'batch_processing' => [
            'enabled' => true,
            'batch_size' => 100,
            'max_retry_attempts' => 3,
            'retry_delay' => env('OGINI_BATCH_RETRY_DELAY', 100),
        ],
    ],
];



namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;

class Article extends Model
{
    use Searchable;

    /**
     * Get the indexable data array for the model.
     */
    public function toSearchableArray(): array
    {
        return [
            'title' => $this->title,
            'content' => $this->content,
            'author' => $this->author->name,
            'published_at' => $this->published_at,
        ];
    }

    /**
     * Get the index name for the model.
     */
    public function searchableAs(): string
    {
        return 'articles';
    }
}

// Basic search
$articles = Article::search('laravel scout')->get();

// Search with additional options
$articles = Article::search('laravel scout')
    ->options([
        'filter' => ['published' => true],
        'sort' => ['published_at' => 'desc'],
    ])
    ->paginate(15);

// In your controller - no manual casting needed!
public function search(Request $request)
{
    $validated = $request->validate([
        'query' => 'eturn Article::search($validated['query'])
        ->paginate(
            $validated['per_page'] ?? 15,  // No need for (int) casting!
            'page',
            $validated['page'] ?? 1
        );
}

// Direct client usage also supports strings
use OginiScoutDriver\Facades\Ogini;

$results = Ogini::search('articles', 'query', [
    'size' => $request->get('per_page', '15'),    // String works!
    'from' => $request->get('offset', '0'),       // String works!
]);

// Before v1.0.7 - Required manual casting
->paginate((int) $request->validated('per_page', 15))

// After v1.0.7 - Works directly
->paginate($request->validated('per_page', 15))

// Validation rules work seamlessly
$request->validate([
    'per_page' => 'integer|between:1,100',  // Laravel returns string
    'page' => 'integer|min:1',              // Automatically handled
]);

use OginiScoutDriver\Facades\Ogini;

// Get query suggestions
$suggestions = Ogini::getQuerySuggestions('articles', 'larav', [
    'size' => 10,
    'fuzzy' => true,
    'highlight' => true,
]);

// Get autocomplete suggestions
$completions = Ogini::getAutocompleteSuggestions('articles', 'lar', [
    'size' => 5,
    'completion_field' => 'suggest',
]);

// Add synonyms
Ogini::addSynonyms('articles', [
    ['car', 'automobile', 'vehicle'],
    ['fast', 'quick', 'rapid'],
]);

// Get synonyms
$synonyms = Ogini::getSynonyms('articles');

// Update synonyms
Ogini::updateSynonyms('articles', [
    ['updated', 'modified', 'changed'],
]);

// Delete synonyms
Ogini::deleteSynonyms('articles');

// Configure stopwords
Ogini::configureStopwords('articles', ['the', 'a', 'an', 'and', 'or'], 'en');

// Get current stopwords
$stopwords = Ogini::getStopwords('articles');

// Update stopwords
Ogini::updateStopwords('articles', ['the', 'a', 'an']);

// Reset to default
Ogini::resetStopwords('articles', 'en');

use OginiScoutDriver\Facades\AsyncOgini;

// Index documents asynchronously
$promise = AsyncOgini::indexDocumentAsync('articles', [
    'title' => 'Async Article',
    'content' => 'This article was indexed asynchronously',
]);

// Bulk index with callback
AsyncOgini::bulkIndexDocumentsAsync('articles', $documents, 
    function ($result) {
        Log::info('Bulk indexing completed', $result);
    },
    function ($error) {
        Log::error('Bulk indexing failed', ['error' => $error]);
    }
);

// Search asynchronously
$searchPromise = AsyncOgini::searchAsync('articles', [
    'query' => ['match' => ['title' => 'Laravel']],
]);

// Wait for all pending operations
$results = AsyncOgini::waitForAll();

// Enable queue integration
AsyncOgini::setQueueEnabled(true);

// Now operations will be queued instead of executed immediately
$jobId = AsyncOgini::indexDocumentAsync('articles', $document);

// Execute multiple requests in parallel
$requests = [
    ['method' => 'POST', 'endpoint' => '/api/indices/articles/search', 'data' => $query1],
    ['method' => 'POST', 'endpoint' => '/api/indices/articles/search', 'data' => $query2],
    ['method' => 'POST', 'endpoint' => '/api/indices/articles/search', 'data' => $query3],
];

$results = AsyncOgini::executeParallel($requests, function ($completed, $total, $result) {
    echo "Progress: {$completed}/{$total}\n";
});

use OginiScoutDriver\Events\IndexingCompleted;
use OginiScoutDriver\Events\SearchCompleted;

// In your EventServiceProvider
protected $listen = [
    IndexingCompleted::class => [
        YourIndexingCompletedListener::class,
    ],
    SearchCompleted::class => [
        YourSearchCompletedListener::class,
    ],
];



namespace App\Listeners;

use OginiScoutDriver\Events\IndexingCompleted;

class LogIndexingSuccess
{
    public function handle(IndexingCompleted $event): void
    {
        \Log::info('Document indexed successfully', [
            'job_id' => $event->getJobId(),
            'index_name' => $event->getIndexName(),
            'document_id' => $event->getDocumentId(),
            'is_bulk' => $event->isBulk(),
        ]);
    }
}

// The package automatically optimizes queries based on configuration:
// - Removes short terms (< min_term_length)
// - Applies complexity scoring
// - Optimizes wildcard usage
// - Boosts phrase matches and exact matches

// Query results are automatically cached based on configuration
// Cache keys are generated from query parameters and settings
// TTL values are configurable for different operation types

// HTTP connections are pooled and reused for better performance
// Pool size and timeout settings are configurable

// Large operations are automatically batched
// Batch size and retry logic are configurable

try {
    $results = Article::search('query')->get();
} catch (\OginiScoutDriver\Exceptions\OginiException $e) {
    Log::error('Search failed', [
        'message' => $e->getMessage(),
        'context' => $e->getContext(),
    ]);
}

use OginiUpdateChecker;

// Check if updates are available
if (OginiUpdateChecker::hasUpdate()) {
    $updateInfo = OginiUpdateChecker::getUpdateInfo();
    
    if ($updateInfo['security_update']) {
        Log::warning('Security update available', $updateInfo);
    }
    
    if ($updateInfo['breaking_changes']) {
        Log::info('Major version update available', $updateInfo);
    }
}

// Get current and latest versions
$current = OginiUpdateChecker::getCurrentVersion();
$latest = OginiUpdateChecker::getLatestVersion();

// Clear update cache
OginiUpdateChecker::clearCache();
bash
php artisan vendor:publish --tag=ogini-config
bash
# Check for available updates
php artisan ogini:check-updates

# Clear cache and check
php artisan ogini:check-updates --clear-cache

# Security updates only
php artisan ogini:check-updates --security-only

# JSON output for automation
php artisan ogini:check-updates --json