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

Sphinxql Query Builder Laravel Package

foolz/sphinxql-query-builder

View on GitHub
Deep Wiki
Context7
## Getting Started

### First Steps
1. **Installation**: Add the package via Composer:
   ```bash
   composer require foolz/sphinxql-query-builder

Ensure your PHP environment meets requirements (PHP 8.2+, mysqli or pdo_mysql).

  1. Basic Connection Setup: Choose either Mysqli or PDO driver:

    // PDO Example
    use Foolz\SphinxQL\Drivers\Pdo\Connection;
    $conn = new Connection();
    $conn->setParams([
        'host' => '127.0.0.1',
        'port' => 9306,
        'charset' => 'utf8',
    ]);
    
  2. First Query: Use the fluent builder for a simple search:

    use Foolz\SphinxQL\SphinxQL;
    $rows = (new SphinxQL($conn))
        ->select('id', 'title')
        ->from('articles')
        ->match('title', 'laravel')
        ->limit(10)
        ->execute()
        ->getStored();
    

Where to Look First

  • Documentation: Start with the Builder Guide for core usage.
  • Examples: Review the Query Builder Examples in the README for common patterns.
  • Helper API: Explore the Helper Guide for maintenance tasks (e.g., SHOW TABLES, CALL commands).

Implementation Patterns

Core Workflows

  1. Fluent Query Building: Chain methods for readability and maintainability:

    $query = (new SphinxQL($conn))
        ->select('user_id', 'score')
        ->from('search_results')
        ->where('status', '=', 'active')
        ->orderBy('score', 'DESC')
        ->limit(20);
    
  2. Match Clauses with Callbacks: Use MatchBuilder for complex full-text queries:

    $query->match(function ($m) {
        $m->field('title')->match('laravel')
          ->orMatch('php')
          ->withWeights([10, 5]);
    });
    
  3. Batch Processing: Execute multiple queries in a single round-trip:

    $batch = (new SphinxQL($conn))
        ->select()->from('articles')->where('id', 1)->enqueue()
        ->select()->from('comments')->where('article_id', 1)->enqueue()
        ->executeBatch();
    
  4. Faceted Search: Group results by attributes (e.g., categories):

    $facet = (new Facet($conn))->facet(['category_id'])->orderBy('category_id', 'ASC');
    $query->facet($facet);
    

Integration Tips

  • Laravel Integration: Create a facade or service provider to wrap the builder:

    // app/Providers/SphinxServiceProvider.php
    public function register() {
        $this->app->singleton('sphinx', function () {
            $conn = new \Foolz\SphinxQL\Drivers\Pdo\Connection();
            $conn->setParams(config('sphinx.connection'));
            return new \Foolz\SphinxQL\SphinxQL($conn);
        });
    }
    

    Use dependency injection in controllers:

    public function search(Request $request, SphinxQL $sphinx) {
        $results = $sphinx->select()->from('articles')
            ->match($request->query('q'))
            ->limit(10)
            ->execute()
            ->getStored();
    }
    
  • Result Handling: Normalize results for API responses:

    $results = $query->execute()->fetchAllAssoc();
    return response()->json([
        'data' => array_map(fn($row) => [
            'id' => $row['id'],
            'title' => $row['title'],
            'score' => (float) $row['@weight'],
        ], $results),
    ]);
    
  • Error Handling: Wrap queries in try-catch blocks:

    try {
        $results = $query->execute()->getStored();
    } catch (\Foolz\SphinxQL\Exception\QueryException $e) {
        Log::error('SphinxQL Error: ' . $e->getMessage());
        return response()->json(['error' => 'Search failed'], 500);
    }
    
  • Connection Management: Use Laravel's DatabaseManager pattern for connection pooling:

    $conn = app('sphinx.connections')->connection('default');
    

Gotchas and Tips

Common Pitfalls

  1. Driver-Specific Quirks:

    • PDO: Ensure charset is set to avoid encoding issues (e.g., utf8mb4 for emoji support).
    • Mysqli: Configure MYSQLI_OPT_CONNECT_TIMEOUT to avoid hangs during connection drops.
    • Manticore vs. SphinxQL: Some commands (e.g., CALL PERCOLATE) are Manticore-specific. Check Helper::getCapabilities() before using.
  2. Result Format Inconsistencies:

    • @weight Field: SphinxQL returns scores in the @weight field by default. Explicitly select it if needed:
      ->select('id', '@weight as score')
      
    • Multi-Query Results: executeBatch() returns an array where the first element is the primary query result, and subsequent elements are subqueries. Verify the order:
      $batch = $query->executeBatch();
      $mainResults = $batch->getStored()[0]; // Primary query
      
  3. Facet Aggregation:

    • Facet results are returned after the main query in the batch. Access them via:
      $facets = $batch->getStored()[1]; // Facet data
      
    • Ensure your SphinxQL/Manticore version supports FACET syntax (v2.3+).
  4. Percolate Queries:

    • Document Format: Manticore's CALL PERCOLATE expects JSON strings for documents:
      ->documents(['{"subject":"test"}'])
      
    • Tag Filtering: Use tags() to filter percolate expressions:
      ->tags(['newsletter'])
      
  5. Multi-Valued Attributes (MVA):

    • Update MVAs with arrays:
      ->value('tags', [1, 2, 3]) // Correct
      ->value('tags', '1,2,3')    // Incorrect (string)
      
    • Query MVAs with IN or ANY:
      ->where('tags', 'IN', [1, 2])
      

Debugging Tips

  1. Compile Before Execute: Use compile()->getCompiled() to inspect raw SQL:

    $sql = $query->compile()->getCompiled();
    Log::debug('Generated SQL:', ['sql' => $sql]);
    
  2. Connection Issues:

    • Verify SphinxQL/Manticore is running (netstat -tulnp | grep 9306).
    • Check firewall rules (port 9306 by default).
  3. Performance:

    • Indexing: Use EXPLAIN via the Helper to analyze query plans:
      $helper->explain('SELECT * FROM rt WHERE MATCH(...)')->execute();
      
    • Batch Limits: SphinxQL has a default batch size (e.g., 1000 rows). Adjust with limit() or offset().
  4. Driver-Specific Logs:

    • PDO: Enable logging in the connection:
      $conn->setParams([
          'pdo' => [
              PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
              PDO::ATTR_EMULATE_PREPARES => false,
          ],
      ]);
      
    • Mysqli: Use mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT) for detailed errors.

Extension Points

  1. Custom Query Builders: Extend the base SphinxQL class to add domain-specific methods:
    class CustomSphinxQL extends \Foolz\SphinxQL\SphinxQL {
        public function searchArticles(string $query, int $limit = 10) {
            return $this->select('id', 'title', '@weight')
                ->from('articles')
                ->match(function ($m) use ($query) {
                    $m->field('title')->match($query)
                      ->field('
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity