Weave Code
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 Php Laravel Package

opensearch-project/opensearch-php

Official PHP client for OpenSearch. Provides a convenient, low-level API for indexing and searching documents, managing clusters and indices, and calling OpenSearch endpoints from Laravel or any PHP app. Supports modern PHP versions and common auth options.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**
   ```bash
   composer require opensearch-project/opensearch-php
  1. Basic Client Initialization

    use OpenSearch\Client;
    
    $client = Client::create([
        'hosts' => ['https://localhost:9200'],
        'auth' => ['username' => 'admin', 'password' => 'admin']
    ]);
    
  2. First Use Case: Indexing a Document

    $params = [
        'index' => 'products',
        'id'    => '1',
        'body'  => ['name' => 'Laptop', 'price' => 999.99]
    ];
    $response = $client->index($params);
    
  3. Where to Look First

    • Official Docs: OpenSearch PHP Client (if available)
    • Source Code: Focus on src/OpenSearch/Client.php for core functionality and src/OpenSearch/Transport/ for transport-layer details.
    • Examples: Check tests/ for real-world usage patterns.

Implementation Patterns

Core Workflows

1. Document CRUD Operations

  • Indexing:
    $client->index([
        'index' => 'users',
        'body'  => ['name' => 'John', 'email' => 'john@example.com']
    ]);
    
  • Updating:
    $client->update([
        'index' => 'users',
        'id'    => '1',
        'body'  => ['doc' => ['email' => 'new@example.com']]
    ]);
    
  • Bulk Operations:
    $params = [
        'body' => [
            ['index' => ['_index' => 'users', '_id' => '1']],
            ['create' => ['name' => 'Alice']],
            ['index' => ['_index' => 'users', '_id' => '2']],
            ['create' => ['name' => 'Bob']]
        ]
    ];
    $client->bulk($params);
    

2. Searching with Query DSL

  • Basic Search:
    $response = $client->search([
        'index' => 'products',
        'body'  => [
            'query' => [
                'match' => ['name' => 'laptop']
            ]
        ]
    ]);
    
  • Aggregations:
    $response = $client->search([
        'index' => 'products',
        'body'  => [
            'aggs' => [
                'avg_price' => ['avg' => ['field' => 'price']]
            ]
        ]
    ]);
    

3. Index Management

  • Create Index:
    $client->indices()->create([
        'index' => 'logs',
        'body'  => ['settings' => ['number_of_shards' => 3]]
    ]);
    
  • Delete Index:
    $client->indices()->delete(['index' => 'logs']);
    

4. Cluster Operations

  • Health Check:
    $client->cluster()->health();
    
  • Pending Tasks:
    $client->cluster()->pendingTasks();
    

Integration Tips

Laravel Integration

  1. Service Provider Setup

    // config/services.php
    'opensearch' => [
        'hosts' => env('OPENSEARCH_HOSTS', 'http://localhost:9200'),
        'auth'  => [
            'username' => env('OPENSEARCH_USER'),
            'password' => env('OPENSEARCH_PASS'),
        ],
    ],
    
  2. Binding the Client

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton(Client::class, function ($app) {
            return Client::create($app['config']['services.opensearch']);
        });
    }
    
  3. Usage in Controllers

    use OpenSearch\Client;
    
    public function search(Client $client)
    {
        $results = $client->search(['index' => 'products', 'body' => ['query' => ['match_all' => new \stdClass()]]]);
        return response()->json($results);
    }
    

Query Builder Pattern

Leverage the client’s query DSL support to build reusable search logic:

class ProductSearchQueryBuilder
{
    public function buildMatchQuery(string $field, string $value): array
    {
        return ['query' => ['match' => [$field => $value]]];
    }

    public function buildBoolQuery(array $must, array $filter = []): array
    {
        return [
            'query' => [
                'bool' => [
                    'must'  => $must,
                    'filter' => $filter
                ]
            ]
        ];
    }
}

Gotchas and Tips

Pitfalls

  1. Authentication Issues

    • Ensure auth is configured correctly for secure clusters. Basic auth:
      'auth' => ['username' => 'user', 'password' => 'pass']
      
    • For AWS SigV4 auth, use the OpenSearch\Transport\TransportBuilder with a custom Transport class.
  2. SSL/TLS Configuration

    • If using self-signed certificates, disable SSL verification (not recommended for production):
      $client = Client::create([
          'hosts' => ['https://localhost:9200'],
          'ssl'   => ['verify_peer' => false]
      ]);
      
    • For production, provide a CA bundle path:
      'ssl' => ['cafile' => '/path/to/ca.pem']
      
  3. Bulk Operation Errors

    • Bulk operations return a items array with success/failure status. Always check for errors:
      $response = $client->bulk($params);
      foreach ($response['items'] as $item) {
          if (isset($item['index']['error'])) {
              // Handle error
          }
      }
      
  4. Rate Limiting

    • OpenSearch may throttle requests. Configure retries in the client:
      $client = Client::create([
          'hosts' => ['https://localhost:9200'],
          'retries' => 3,
          'retry_on_status' => [502, 503, 504, 429]
      ]);
      
  5. Index/Field Mapping Conflicts

    • Ensure your document structure matches the index mapping. Use indices()->getMapping() to inspect:
      $mapping = $client->indices()->getMapping(['index' => 'products']);
      

Debugging Tips

  1. Enable Debug Logging Use the OpenSearch\Transport\TransportBuilder to enable debug output:

    $client = Client::create([
        'hosts' => ['https://localhost:9200'],
        'transport' => function () {
            return new \OpenSearch\Transport\TransportBuilder()
                ->setHosts(['https://localhost:9200'])
                ->setLogger(new \Monolog\Logger('opensearch', [
                    new \Monolog\Handler\StreamHandler('php://stderr', \Monolog\Logger::DEBUG)
                ]))
                ->build();
        }
    ]);
    
  2. Raw HTTP Responses Access raw responses for debugging:

    $response = $client->search(['index' => 'products', 'body' => ['query' => ['match_all' => new \stdClass()]]]);
    $rawResponse = $response->getRawResponse(); // For advanced debugging
    
  3. Common HTTP Errors

    • 404 Not Found: Verify index/document IDs and permissions.
    • 403 Forbidden: Check cluster/user permissions.
    • 400 Bad Request: Validate query DSL syntax (use OpenSearch Query DSL Analyzer).

Extension Points

  1. Custom Transport Layer Extend OpenSearch\Transport\Transport to integrate with custom HTTP clients (e.g., Guzzle middleware):

    class CustomTransport extends \OpenSearch\Transport\Transport
    {
        public function __construct($hosts, array $options = [])
        {
            parent::__construct($hosts, $options);
            $this->setClient(new \GuzzleHttp\Client([
                'middleware' => [new \GuzzleHttp\Middleware::tap(function ($request) {
                    // Modify request
                })]
            ]));
        }
    }
    
  2. Query DSL Helpers Create helper classes to abstract complex queries:

    class SearchHelper
    {
        public static function paginatedQuery(int $page = 1, int $perPage = 10): array
        {
            return [
                'from' =>
    
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle