Solarium PHP Client Library

repository·master·Indexed 21 days ago

https://github.com/solariumphp/solarium

A PHP client library designed to model Apache Solr concepts, providing a high-level API to manage complex Solr query parameters. It features a two-part architecture consisting of a Client and various Adapters (Curl, Http, and PSR-18) for communication. Solarium supports a plugin system for extending behavior, custom query type registration, and provides specialized document classes for read-only select results and read-write update operations.

Tokens
98.8K
Snippets
213
Records
291
Agent score
74%

What's inside Solarium

  1. Extract from non-filesystem sources

    master

    Extract queries are not limited to local files. You can provide various types of input via $query->setFile():

    • Remote URLs: Pass a stream URL (e.g., http://example.org/resource). Note that remote streaming is disabled by default in Solr.
    • Memory Streams: Use PHP wrappers like php://memory or php://temp. This is useful for content generated in-memory.
    • Temporary Files: Use tmpfile() to create a temporary file, write content to it, and pass the file pointer.
    • Database LOBs: Pass a PDO Large Object (LOB) stream.

    Note: Using a LOB as a stream requires PHP 8.1.0 or higher due to PHP Bug #40913.

    // Example: Using a memory stream
    $contents = '...';
    $file = fopen('php://memory', 'w+');
    fwrite($file, $contents);
    $query->setFile($file);
    
    $client->extract($query);
    fclose($file);
  2. Configure update query request formats

    master
    Solr supports different request formats for update queries, such as XML, JSON, and (in Solr 9.3+) CBOR. Note that some functionalities are exclusive to specific formats (e.g., a feature might be available in XML but not in JSON). Ensure you set the appropriate request format in your Solarium client if your specific update operation requires it.
  3. Understand Plugin Execution Order

    master

    Because plugins rely on an event dispatcher, the order in which they are called for the same event depends on the dispatcher's implementation.

    If you are using the Symfony EventDispatcher, Solarium manages the priority of critical plugins automatically. However, if you require a specific execution order (e.g., Plugin A must run before Plugin B), you must consult the documentation of the specific event dispatcher you have injected into the Solarium Client.

    General requirements:

    • CustomizeRequest must execute before PostBigRequest.
    • Loadbalancer should always be the last plugin to run.
  4. Use the ReRankQuery component for query re-ranking

    master

    Query Re-Ranking allows you to run a simple query (A) to find matching documents and then re-rank the top N documents using scores from a more complex query (B). This improves performance by only applying the expensive ranking logic of query B to a subset of results.

    Note that documents scoring very low in the initial query (A) might be excluded from the re-ranking phase even if they would have scored highly in query (B).

    // get a select query instance
    $query = $client->createSelect();
    $query->setQuery('electronics');
    
    // get rerankquery component
    $rerank = $query->getReRankQuery();
    
    // Configure re-ranking
    $rerank->setQuery('popularity:10');
    $rerank->setWeight(3);
    $rerank->setOperator($rerank::OPERATOR_MULTIPLY);
    
    $resultset = $client->select($query);
  5. Use select queries to retrieve documents and facets

    master

    Select queries in Solarium allow you to retrieve specific documents and/or facet counts from your Solr index. Because Solr select queries support a wide range of parameters, you can use them to filter results, request specific fields, and perform complex faceting operations.

    For a deep understanding of the underlying Solr syntax used by these queries, refer to the official Solr documentation on Common Query Parameters, The Standard Query Parser, and Faceting.

  6. Use FacetQuery to count results with an arbitrary query

    master

    The FacetQuery component within a FacetSet allows you to supply an arbitrary query (using standard Solr query syntax) to count the number of results matching that specific query.

    Key behaviors:

    • The query is independent of the 'main' query.
    • filterQueries will affect this count unless they are explicitly excluded.
    • You can configure this using query option values or via set/get methods.
    // get the facetset component
    $facetSet = $query->getFacetSet();
    
    // create a facet query instance and set options
    $facetSet->createFacetQuery('stock')->setQuery('inStock: true');
  7. How the FacetSet component works

    master
    The FacetSet is a Solarium-specific abstraction that does not exist in Solr itself. It serves as a centralized component to manage and create various types of facets (Standard, Pivot, etc.) and to configure global facet parameters. Instead of managing individual facet parameters separately, you use the FacetSet to define both the specific facets you want to retrieve and the global settings that apply to all of them.
  8. Customize Solarium using the Plugin System

    master

    The plugin system is the recommended way to alter or add behavior to Solarium. Plugins are highly reusable, can be combined, and do not require extending the core library, making upgrades easier.

    Key features:

    • Event-driven: Plugins execute code in response to specific events.
    • Data access: Events provide access to variables that can be read or modified.
    • Client access: Plugins have access to the Solarium client instance, allowing them to modify settings or class mappings.
    • PSR-14 compatible: Solarium can use any PSR-14 compatible event dispatcher (e.g., Symfony EventDispatcher).
  9. Distinguish Solarium exceptions using ExceptionInterface

    master

    To separate errors caused by the Solarium library from general PHP errors, catch Solarium\Exception\ExceptionInterface. This is a marker interface implemented by all exceptions thrown by the library.

    try {
        $client->ping($ping);
    } catch (Solarium\Exception\ExceptionInterface $e) {
        // This block only executes for Solarium-related errors
        echo $e->getMessage();
    } catch (Exception $e) {
        // This block executes for any other PHP error
        echo $e->getMessage();
    }
  10. How the LoadBalancer plugin works

    master

    The LoadBalancer plugin provides code-based load balancing for multiple Solr servers when a dedicated hardware/software load balancer is not available.

    Key Features

    • Weighted Servers: Supports multiple servers, each with its own assigned weight.
    • Failover Mode: Can be configured to try another server if a query fails.
    • Query Blocking: By default, Update and Extract queries are blocked from load balancing and will always use the default adapter settings (pointing to the master).
    • Unblocking: You can manually unblock specific query types if you need to load balance them (e.g., extracting without indexing).
    • Server Pinning: Allows forcing a specific server for the next query.
  11. Understand the response values of an update query

    master

    When performing an update query in Solr via Solarium, the response contains two specific metrics reported by Solr. It is important to distinguish these from standard HTTP responses:

    • status: The Solr internal status code. A value of 0 indicates success. Note that this is not the HTTP status code.
    • querytime: The Solr index query time. This represents the time taken for the index operation and does not include network or HTTP response latency.

    If the update fails, Solarium will throw an exception.