Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Opensearch Client Laravel Package

directorytree/opensearch-client

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require directorytree/opensearch-client
    

    Publish the config file (if needed):

    php artisan vendor:publish --provider="DirectoryTree\OpenSearchClient\OpenSearchServiceProvider"
    
  2. Configuration Edit .env with your OpenSearch cluster details:

    OPENSEARCH_HOST=http://localhost:9200
    OPENSEARCH_USERNAME=admin
    OPENSEARCH_PASSWORD=admin
    
  3. First Use Case Inject the client into a controller or service:

    use DirectoryTree\OpenSearchClient\Facades\OpenSearch;
    
    public function index()
    {
        $response = OpenSearch::get('products/_search', [
            'query' => ['match_all' => new \stdClass()]
        ]);
        return $response->getBody();
    }
    
  4. Key Files to Review

    • config/opensearch.php (default settings)
    • vendor/directorytree/opensearch-client/src/Facades/OpenSearch.php (facade usage)
    • vendor/directorytree/opensearch-client/src/OpenSearchManager.php (core logic)

Implementation Patterns

Common Workflows

  1. Search Operations

    // Basic search
    $result = OpenSearch::search('products', [
        'query' => ['match' => ['name' => 'laptop']]
    ]);
    
    // Paginated results
    $result = OpenSearch::search('products', [
        'from' => 0,
        'size' => 10,
        'query' => ['match_all' => new \stdClass()]
    ]);
    
  2. Index Management

    // Create index
    OpenSearch::indices()->create(['index' => 'products']);
    
    // Update mappings
    OpenSearch::indices()->putMapping([
        'index' => 'products',
        'body' => ['properties' => ['name' => ['type' => 'text']]]
    ]);
    
  3. Document CRUD

    // Index a document
    OpenSearch::index('products', '1', ['name' => 'Laptop', 'price' => 999]);
    
    // Update a document
    OpenSearch::update('products', '1', ['doc' => ['price' => 899]]);
    
    // Delete a document
    OpenSearch::delete('products', '1');
    
  4. Bulk Operations

    $operations = [
        ['index' => ['_index' => 'products', '_id' => '1']],
        ['name' => 'Laptop'],
        ['index' => ['_index' => 'products', '_id' => '2']],
        ['name' => 'Phone']
    ];
    OpenSearch::bulk($operations);
    

Integration Tips

  • Laravel Eloquent: Use the client alongside scout for search-as-you-type:
    use DirectoryTree\OpenSearchClient\Facades\OpenSearch;
    use Laravel\Scout\Builder;
    
    Builder::macro('opensearch', function ($query) {
        return OpenSearch::search('products', [
            'query' => ['match' => ['name' => $query]]
        ]);
    });
    
  • Queue Jobs: Offload heavy operations to queues:
    use DirectoryTree\OpenSearchClient\Facades\OpenSearch;
    use Illuminate\Support\Facades\Queue;
    
    Queue::push(function () {
        OpenSearch::bulk($largeDatasetOperations);
    });
    
  • Middleware: Validate OpenSearch responses:
    OpenSearch::middleware(function ($response) {
        if ($response->getStatusCode() >= 400) {
            throw new \Exception('OpenSearch error: ' . $response->getBody());
        }
        return $response;
    });
    

Gotchas and Tips

Pitfalls

  1. Authentication Issues

    • Ensure OPENSEARCH_USERNAME/OPENSEARCH_PASSWORD are set if using security.
    • For AWS OpenSearch, use OPENSEARCH_HOST with the full endpoint (e.g., https://search-domain.us-east-1.es.amazonaws.com).
  2. SSL/TLS Errors

    • If using HTTPS, configure CA certificates in config/opensearch.php:
      'ssl' => [
          'ca' => storage_path('certs/root-ca.pem'),
          'verify_peer' => true,
      ],
      
  3. Rate Limiting

    • OpenSearch may throttle requests. Implement retries:
      use DirectoryTree\OpenSearchClient\Facades\OpenSearch;
      
      $maxRetries = 3;
      for ($i = 0; $i < $maxRetries; $i++) {
          try {
              $response = OpenSearch::get('products/_search');
              break;
          } catch (\Exception $e) {
              if ($i === $maxRetries - 1) throw $e;
              sleep(1);
          }
      }
      
  4. Index Not Found

    • Always check if an index exists before operations:
      if (!OpenSearch::indices()->exists(['index' => 'products'])) {
          OpenSearch::indices()->create(['index' => 'products']);
      }
      

Debugging

  • Enable Logging Add to config/opensearch.php:

    'logger' => [
        'enabled' => true,
        'channel' => 'single',
    ],
    

    Then configure channels in config/logging.php to log to a file or monitor.

  • Raw Responses Inspect raw responses for debugging:

    $response = OpenSearch::get('products/_search');
    \Log::debug($response->getBody());
    

Extension Points

  1. Custom Clients Bind additional clients in AppServiceProvider:

    public function register()
    {
        $this->app->singleton('opensearch.secondary', function () {
            return OpenSearch::createClient([
                'hosts' => ['https://secondary-cluster:9200'],
                'auth' => ['admin', 'password']
            ]);
        });
    }
    
  2. Query Builders Create reusable query builders:

    class ProductSearchBuilder
    {
        public static function build($query)
        {
            return [
                'query' => [
                    'bool' => [
                        'must' => [
                            ['match' => ['name' => $query]],
                            ['range' => ['price' => ['gte' => 100]]]
                        ]
                    ]
                ]
            ];
        }
    }
    
  3. Event Listeners Listen for OpenSearch events (e.g., index creation):

    OpenSearch::listen('index.created', function ($index) {
        \Log::info("Index {$index} created.");
    });
    

Configuration Quirks

  • Default Index: The package does not set a default index. Always specify the index in operations.
  • Timeouts: Adjust timeouts in config/opensearch.php:
    'timeout' => 30, // seconds
    'connect_timeout' => 5,
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
ippanelcom/laravel-sdk
adachsoft/changelog-linter
adachsoft/collection
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel
draftsmaninc/draftsman
square-bit/laravel-volition
himito/laravel-mailman
htinlynn/genius-helper
maco-studios/hephaestus