Typesense PHP Client

repository·master·Indexed 42 days ago

https://github.com/typesense/typesense-php

The official PHP client for the Typesense API, providing a high-level interface to interact with Typesense search servers. It includes tools for managing collections, documents, aliases, and conversation models, and supports custom PSR-3 loggers and PSR-18 HTTP clients via HTTPlug.

Tokens
6.6K
Snippets
32
Records
34
Agent score
54%

What's inside Typesense

  1. Run the Typesense PHP client examples

    master

    To run the provided examples, you must first have a local Typesense server running. You can start the server using the composer script provided in the repository. Once the server is active, navigate to the examples directory and execute the desired PHP example file.

    # 1. Start the local Typesense server via docker
    composer run-script typesenseServer
    
    # 2. Run a specific example
    cd examples
    php <example_name>.php
  2. Access Typesense resources via the Client

    master

    The Typesense\Client organizes API functionality into specialized resource objects. You can access these resources using either public properties or their corresponding get{ResourceName}() methods.

    Common resources include:

    • collections: Manage collections (create, list, retrieve).
    • multiSearch: Perform federated multi-search requests.
    • keys: Manage API keys.
    • health: Check server readiness.
    • metrics: Retrieve RAM, CPU, Disk, and Network usage.
    • synonymSets: Manage synonym sets.

    Many resources support two access patterns:

    1. Method-style: For collection-level operations (e.g., $client->collections->create(...)).
    2. Array-style: For accessing a specific resource by name/ID (e.g., $client->collections['products']->retrieve()).
    // Method-style for collection operations
    $client->collections->create(['name' => 'products', 'fields' => [['name' => 'title', 'type' => 'string']]]);
    
    // Array-style for specific resource operations
    $client->collections['products']->retrieve();
    
    // Multi-search
    $client->multiSearch->perform(['searches' => [['collection' => 'products', 'q' => '*']]]);
  3. Access documents, overrides, and synonyms within a collection

    master

    A Collection object provides access to related resources via public properties. You can use these to manage the data and curation rules within that specific collection:

    • $collection->documents: Access the documents resource to index, search, import, or export documents. You can also access a single document using array syntax.
    • $collection->overrides: Access legacy curation rules (overrides) to upsert or list them.
    • $collection->synonyms: Access legacy synonyms to upsert or list them.
    // Manage documents
    $client->collections['products']->documents->create(['id' => '1', 'title' => 'Hat']);
    $client->collections['products']->documents['1']->retrieve();
    
    // Manage overrides (curation rules)
    $client->collections['products']->overrides->upsert('promote-hat', ['rule' => ['query' => 'hat', 'match' => 'exact'], 'includes' => []]);
    $client->collections['products']->overrides['promote-hat']->retrieve();
    
    // Manage synonyms
    $client->collections['products']->synonyms->upsert('syn-1', ['synonyms' => ['nyc', 'new york']]);
    $client->collections['products']->synonyms['syn-1']->retrieve();
  4. Access specific alias operations

    master

    The Aliases class implements ArrayAccess and uses a magic __get method, allowing you to access specific alias instances by name. This provides access to the Alias class for operations targeting a single named alias.

    // Accessing an alias instance by name via magic property
    $myAlias = $client->aliases->my_alias_name;
  5. Run Typesense via Docker Compose

    master

    You can use the provided docker-compose.yml to spin up a local Typesense server instance. This configuration maps the data directory to a local path and exposes the default port.

    Key Configuration Details:

    • Image: Uses typesense/typesense:27.0.rc21.
    • Environment Variables:
      • TYPESENSE_DATA_DIR: Set to /data inside the container.
      • TYPESENSE_API_KEY: Set to xyz (this should be changed to a secure key in production).
    • Ports: Maps host port 8108 to container port 8108.
    • Volumes: Maps /tmp/typesense-server-data on the host to /data in the container to persist search data.
    version: '3.5'
    
    services:
      typesense:
        image: typesense/typesense:27.0.rc21
        environment:
          TYPESENSE_DATA_DIR: /data
          TYPESENSE_API_KEY: xyz
        volumes:
          - /tmp/typesense-server-data:/data
        ports:
          - 8108:8108
        restart: 'no'
  6. Initialize the Typesense Client

    master

    To interact with the Typesense API, instantiate the Typesense\Client class by passing a configuration array. The client acts as the central entry point, providing access to various resource managers (like collections, search, and analytics) via public properties or getter methods.

    use Typesense;
    
    $client = new Typesense\Client([
        'nodes' => [
            ['host' => 'localhost', 'port' => '8108', 'protocol' => 'http']
        ],
        'api_key' => 'xyz'
    ]);
  7. Escape filter values for search queries

    master

    When using string values within a filter_by query, use Typesense\FilterBy::escapeString() to safely escape special characters and prevent query errors. This is essential for handling strings that contain quotes, logical operators, or other reserved characters.

    use Typesense\FilterBy;
    
    $filterValue = "The 17\" O'Conner && O`Series \n OR a || 1%2 book? (draft), [alpha]";
    $filterBy = 'tags:=' . FilterBy::escapeString($filterValue);
  8. Configure the Typesense PHP Client

    master

    The Typesense PHP client is initialized using a configuration array passed to the Configuration constructor. The configuration defines connection nodes, authentication, retry logic, logging, and the HTTP client.

    Required Keys

    • nodes: An array of node dictionaries. Each node must contain host, port, and protocol.
    • api_key: Your Typesense API key.

    Optional Keys

    • randomize_nodes: Boolean. If true (default), the order of nodes is shuffled to distribute load.
    • nearest_node: A dictionary defining a specific node to prioritize.
    • healthcheck_interval_seconds: Integer. Interval for health checks (default: 60).
    • num_retries: Float. Number of retries for failed requests (default: 3.0).
    • retry_interval_seconds: Float. Seconds to wait between retries (default: 1.0).
    • logger: An object implementing Psr\​Log\\​LoggerInterface. If provided, you cannot set log_level.
    • log_level: The logging level (e.g., using Monolog constants) if no custom logger is provided.
    • client: An HTTP client. Supports Psr\\Http\\Client\\ClientInterface, Http\\Client\\HttpClient, or Http\\Client\\Common\\HttpMethodsClient.
    $config = [
        'nodes' => [
            [
                'host' => 'localhost',
                'port' => 8108,
                'protocol' => 'http',
                'path' => '',
            ],
        ],
        'api_key' => 'your_api_key',
        'num_retries' => 5.0,
        'retry_interval_seconds' => 2.0,
        'randomize_nodes' => true,
    ];
    
    $configuration = new \Typesense\Lib\Configuration($config);
  9. Check Typesense Server and Client compatibility

    master

    Ensure your typesense-php client version is compatible with your running Typesense Server version. Use the following mapping as a guide:

    Typesense Servertypesense-php
    >= v30.0>= v6.0.0
    >= v28.0>= v5.0.0
    >= v26.0>= v4.9.0
    >= v0.23.0>= v4.8.0
    >= v0.21.0>= v4.7.0
    >= v0.20.0>= v4.6.0
    >= v0.19.0>= v4.5.0
    >= v0.18.0>= v4.4.0
    >= v0.17.0>= v4.2.0
    >= v0.16.0>= v4.1.0
    >= v0.15.0>= v4.0.0
  10. Migrate from legacy Synonyms to Synonym Sets

    master

    The Synonyms class and its methods (upsert, retrieve) are deprecated starting with Typesense Server v30.0.0.

    To ensure compatibility with newer Typesense Server versions, you should migrate from using collection-specific synonyms to the new Synonym Sets APIs via $client->synonymSets.

  11. Use legacy Synonyms API (Deprecated)

    master

    If you are using an older version of Typesense Server (pre-v30), you can manage synonyms for a specific collection using the synonyms property on a collection object.

    Note: This is deprecated. Use $client->synonymSets for Typesense Server v30+.

    // Upsert a synonym for a specific collection
    $client->collections['products']->synonyms->upsert('syn-1', ['synonyms' => ['nyc', 'new york']]);
    
    // Retrieve all synonyms for a specific collection
    $synonyms = $client->collections['products']->synonyms->retrieve();