PHPackages                             searchcraft/searchcraft-php - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. searchcraft/searchcraft-php

ActiveLibrary[Database &amp; ORM](/categories/database)

searchcraft/searchcraft-php
===========================

Searchcraft API PHP Client

v0.8.1(1mo ago)1572Apache-2.0PHPPHP ^7.4 || ^8.0CI passing

Since Jun 3Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/searchcraft-inc/searchcraft-client-php)[ Packagist](https://packagist.org/packages/searchcraft/searchcraft-php)[ RSS](/packages/searchcraft-searchcraft-php/feed)WikiDiscussions main Synced today

READMEChangelog (4)Dependencies (14)Versions (9)Used By (0)

[![Build faster, ship more. The next frontier in developer search tools is here. Searchcraft](./header.png)](./header.png)

Searchcraft API PHP Client
==========================

[](#searchcraft-api-php-client)

A [PSR-compatible](https://www.php-fig.org/psr/) PHP client for the Searchcraft API.

[![Test Status](https://github.com/searchcraft-inc/searchcraft-client-php/actions/workflows/tests.yml/badge.svg)](https://github.com/searchcraft-inc/searchcraft-client-php/actions/workflows/tests.yml)

#### [Documentation](https://docs.searchcraft.io?utm_campaign=oss&utm_source=github&utm_medium=searchcraft-php-client) | [Discord](https://discord.com/invite/y3zUHkBk6e) | [FAQ](https://www.searchcraft.io/frequently-asked-questions?utm_campaign=oss&utm_source=github&utm_medium=searchcraft-php-client) | [Issues / Requests](https://github.com/searchcraft-inc/searchcraft-issues) | [Searchcraft Cloud](https://vektron.searchcraft.io?utm_campaign=oss&utm_source=github&utm_medium=searchcraft-php-client) | [Searchcraft Website](https://searchcraft.io?utm_campaign=oss&utm_source=github&utm_medium=searchcraft-php-client)

[](#documentation--discord--faq--issues--requests--searchcraft-cloud--searchcraft-website)

Installation
------------

[](#installation)

```
composer require searchcraft/searchcraft-php
```

You will also need to install a PSR-18 compatible HTTP client, such as [Guzzle](https://github.com/guzzle/guzzle).

```
composer require guzzlehttp/guzzle http-interop/http-factory-guzzle:^1.0
```

Basic Usage
-----------

[](#basic-usage)

### Initialize the client

[](#initialize-the-client)

The client can be initialized with different types of API keys, depending on your access requirements:

```
use Searchcraft\Searchcraft;

// Using an admin key (full access)
$searchcraft_full = new Searchcraft('your-admin-key');

// Using a read-only key (search and read operations only)
$searchcraft_reader = new Searchcraft('your-read-key', Searchcraft::KEY_TYPE_READ);

// Using an ingest key (document operations only)
$searchcraft_ingestion = new Searchcraft('your-ingest-key', Searchcraft::KEY_TYPE_INGEST);
```

By default, the client connects to `http://localhost:8000`. To use a different endpoint such as a Searchcraft Cloud cluster:

```
// Replace with your cluster endpoint
$searchcraft = new Searchcraft(
    'your-api-key',
    Searchcraft::KEY_TYPE_ADMIN,
    'https://yourcluster.io'
);
```

### Using PSR-18 HTTP Client

[](#using-psr-18-http-client)

The client uses [PSR-18 HTTP Client discovery](https://github.com/php-http/discovery) to find an available HTTP client. You can also provide your own:

```
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\HttpFactory;

$httpClient = new Client();
$requestFactory = new HttpFactory();
$streamFactory = new HttpFactory();

$searchcraft = new Searchcraft(
    'your-api-key',
    Searchcraft::KEY_TYPE_ADMIN,
    'https://api.searchcraft.io/v1',
    $httpClient,
    $requestFactory,
    $streamFactory
);
```

Searchcraft PHP Client does not include a specific HTTP client in its `require` dependencies but Guzzle is recommended. You will need to install one in order to use the Searchcraft client.

Search Operations
-----------------

[](#search-operations)

Search operations require an admin key or read key.

### Basic Search

[](#basic-search)

```
// Simple search query
$results = $searchcraft->search()->query('my_index', 'search term');

// Search with additional parameters
$results = $searchcraft->search()->query('my_index', 'search term', [
    'limit' => 20,
    'offset' => 0,
    'sort' => 'price:asc',
    'mode' => 'fuzzy'
]);

// Fuzzy search (default)
$results = $searchcraft->search()->query('my_index', 'search term');

// Explicit fuzzy search
$results = $searchcraft->search()->query('my_index', 'search term', ['mode' => 'fuzzy']);

// Exact search
$results = $searchcraft->search()->query('my_index', 'search term', ['mode' => 'exact']);
```

### Federation Search

[](#federation-search)

```
// Search across all indexes in a federation using federatedQuery
$searchResults = $searchcraft->search()->federatedQuery('my_federation', 'breaking news', [
    'limit' => 20,
    'offset' => 0,
    'mode' => 'fuzzy'
]);

// Federation search with additional options
$searchResults = $searchcraft->search()->federatedQuery('my_federation', 'search term', [
    'limit' => 50,
    'offset' => 10,
    'order_by' => 'publishedAt',
    'sort' => 'desc',
    'occur' => 'should',
    'mode' => 'exact'
]);
```

Index Operations
----------------

[](#index-operations)

Index administration operations require an admin key.

### List Indexes

[](#list-indexes)

```
$indexes = $searchcraft->index()->listIndexes();
```

### Get Index Details

[](#get-index-details)

```
$indexDetails = $searchcraft->index()->getIndex('products');
```

### Create Index

[](#create-index)

```
$newIndex = $searchcraft->index()->createIndex('blog', [
    'index' => [
        'name' => 'blog',
        'language' => 'en',
        'search_fields' => ['title', 'content', 'tags'],
        'fields' => [
            'id' => [
                'type' => 'text',
                'required' => true,
                'stored' => true,
                'indexed' => false
            ],
            'title' => [
                'type' => 'text',
                'stored' => true
            ],
            'content' => [
                'type' => 'text',
                'stored' => true
            ],
            'tags' => [
                'type' => 'text',
                'stored' => true,
                'multi' => true
            ],
            'category' => [
                'type' => 'facet',
                'stored' => true
            ],
            'publishedAt' => [
                'type' => 'datetime',
                'fast' => true,
                'stored' => true,
                'indexed' => true
            ]
        ],
        'weight_multipliers' => [
            'title' => 2.0,
            'tags' => 1.0,
            'content' => 0.6
        ]
    ]
]);
```

### Update Index

[](#update-index)

Note if you are not adding, removing or changing properties of schema fields will likely want to use the `PATCH` operation instead. An update request will remove existing documents but for patchable updates your index is not emptied. See the [docs](https://docs.searchcraft.io/api/schema/?utm_campaign=oss&utm_source=github&utm_medium=searchcraft-php-client) for details on which properties are patchable.

```
$updatedIndex = $searchcraft->index()->updateIndex('blog', [
    'index' => [
        'name' => 'blog',
        'language' => 'en',
        'search_fields' => ['title', 'content', 'tags', 'summary'],
        'fields' => [
            'id' => [
                'type' => 'text',
                'required' => true,
                'stored' => true,
                'indexed' => false
            ],
            'title' => [
                'type' => 'text',
                'stored' => true
            ],
            'content' => [
                'type' => 'text',
                'stored' => true
            ],
            'summary' => [
                'type' => 'text',
                'stored' => true
            ],
            'tags' => [
                'type' => 'text',
                'stored' => true,
                'multi' => true
            ],
            'category' => [
                'type' => 'facet',
                'stored' => true
            ],
            'publishedAt' => [
                'type' => 'datetime',
                'fast' => true,
                'stored' => true,
                'indexed' => true
            ]
        ],
        'weight_multipliers' => [
            'title' => 2.0,
            'content' => 1.0,
            'summary' => 1.5
        ]
    ]
]);
```

### Patch Index

[](#patch-index)

```
$patchedIndex = $searchcraft->index()->patchIndex('blog', [
    'search_fields' => ['title', 'content', 'tags', 'summary'],
    'weight_multipliers' => [
        'title' => 3.0,
        'content' => 1.0,
        'summary' => 1.5,
        'tags' => 0.8
    ],
    'language' => 'en',
    'time_decay_field' => 'publishedAt',
    'auto_commit_delay' => 2,
    'exclude_stop_words' => true
]);
```

### Delete Index

[](#delete-index)

```
$result = $searchcraft->index()->deleteIndex('my-index');
```

Document Operations
-------------------

[](#document-operations)

Document operations require an admin key or ingest key.

### Add Documents

[](#add-documents)

```
$result = $searchcraft->index()->addDocuments('products', [
    [
        'id' => '1',
        'name' => 'Smartphone X',
        'price' => 699.99,
        'category' => 'Electronics',
        'brand' => 'BrandName'
    ],
    [
        'id' => '2',
        'name' => 'Laptop Pro',
        'price' => 1299.99,
        'category' => 'Electronics',
        'brand' => 'BrandName'
    ]
]);
```

### Update Documents

[](#update-documents)

```
$result = $searchcraft->index()->updateDocuments('products', [
    [
        'id' => '1',
        'price' => 649.99,
        'in_stock' => true
    ]
]);
```

### Get Document

[](#get-document)

```
$document = $searchcraft->index()->getDocument('products', '1');
```

### Delete Documents

[](#delete-documents)

```
$result = $searchcraft->index()->deleteDocuments('products', ['1', '2']);
```

Federation Operations
---------------------

[](#federation-operations)

Federation operations allow you to manage federations that combine multiple indexes for cross-index search. Federation administration operations require an admin key, while federation search requires a read key.

### List Federations

[](#list-federations)

```
// List all federations
$federations = $searchcraft->federation()->listFederations();
```

### Get Federation Details

[](#get-federation-details)

```
// Get details of a specific federation
$federation = $searchcraft->federation()->getFederation('galaxy_news_federation');
```

### Get Federations by Organization

[](#get-federations-by-organization)

```
// Get all federations for a specific organization
$organizationFederations = $searchcraft->federation()->getFederationsByOrganization('4');
```

### Create Federation

[](#create-federation)

```
// Create a new federation with weighted index configurations
$newFederation = $searchcraft->federation()->createFederation([
    'name' => '4_galaxy_news_test',
    'friendly_name' => 'Galaxy News Test Federation',
    'created_by' => '1',
    'last_modified_by' => '1',
    'organization_id' => '4',
    'index_configurations' => [
        [
            'name' => 'news_articles',
            'weight_multiplier' => 1.0
        ],
        [
            'name' => 'blog_posts',
            'weight_multiplier' => 0.8
        ],
        [
            'name' => 'press_releases',
            'weight_multiplier' => 1.5
        ]
    ]
]);
```

### Update Federation

[](#update-federation)

```
// Update an existing federation
$updatedFederation = $searchcraft->federation()->updateFederation('galaxy_news_federation', [
    'friendly_name' => 'Updated Galaxy News Federation',
    'last_modified_by' => '1',
    'organization_id' => '4',
    'index_configurations' => [
        [
            'name' => 'news_articles',
            'weight_multiplier' => 1.2
        ],
        [
            'name' => 'blog_posts',
            'weight_multiplier' => 0.9
        ],
        [
            'name' => 'press_releases',
            'weight_multiplier' => 1.8
        ],
        [
            'name' => 'social_media',
            'weight_multiplier' => 0.6
        ]
    ]
]);
```

### Delete Federation

[](#delete-federation)

```
// Delete a federation
$result = $searchcraft->federation()->deleteFederation('old_federation');
```

AI Capabilities
---------------

[](#ai-capabilities)

Requires Searchcraft Engine 0.10.0 or later.

### Check AI Capabilities for an Index

[](#check-ai-capabilities-for-an-index)

```
// Returns whether AI features are enabled and which pieces
// (LLM provider, model, and search summary config) are configured.
$capabilities = $searchcraft->index()->getCapabilities('blog');
```

### Streaming AI Search Summaries

[](#streaming-ai-search-summaries)

The index must have `ai_enabled: true` and a valid `ai.search_summary`configuration. The engine streams Server-Sent Events: one `metadata`event, any number of `delta` events with `content` chunks, and a final `done` event. `searchSummary()` returns every parsed event, and you may optionally pass a callback to react to events as they arrive.

```
// Collect all events at once
$events = $searchcraft->search()->searchSummary('blog', 'search term', [
    'limit' => 5,
    'mode'  => 'fuzzy',
]);

// Or stream them via a callback
$summaryText = '';
$searchcraft->search()->searchSummary(
    'blog',
    'search term',
    ['limit' => 5],
    function (string $event, $data) use (&$summaryText) {
        if ($event === 'delta' && isset($data['content'])) {
            $summaryText .= $data['content'];
        }
    }
);
```

Authentication Operations
-------------------------

[](#authentication-operations)

### Get Keys for an Index

[](#get-keys-for-an-index)

```
// Returns all authentication keys scoped to the given index.
$keys = $searchcraft->authentication()->getIndexKeys('blog');
```

Measure Operations
------------------

[](#measure-operations)

The Measure API is primarily used by SDKs and CMS integrations to capture search usage metrics and retrieve dashboard aggregates.

### Check Whether Analytics Are Enabled

[](#check-whether-analytics-are-enabled)

```
// Unauthenticated — works with or without an API key. Returns
// ['enabled' => bool]; when false, the other measure() endpoints are
// no-ops on the server.
$status = $searchcraft->measure()->getStatus();
if ($status['enabled']) {
    // ... track events / query dashboards
}
```

### Track a Single Event

[](#track-a-single-event)

```
$searchcraft->measure()->trackEvent([
    'event_name' => 'document_clicked',
    'properties' => [
        'searchcraft_index_names' => ['products'],
        'external_document_id' => 'sku-42',
        'document_position' => 2,
    ],
    'user' => [
        'user_id'   => 'user-123',
        'user_type' => 'authenticated',
    ],
]);
```

### Track a Batch of Events

[](#track-a-batch-of-events)

```
$searchcraft->measure()->trackBatch([
    [
        'event_name' => 'search_completed',
        'properties' => ['searchcraft_index_names' => ['products']],
        'user'       => ['user_id' => 'user-123'],
    ],
    // ...
]);
```

### Dashboard Metrics

[](#dashboard-metrics)

```
// All three accept the same optional filter set: organization_id,
// application_id, index_names, user_id, user_type, session_id,
// event_name, date_start, date_end, granularity, rpp, page.
$summary    = $searchcraft->measure()->getDashboardSummary(['organization_id' => '4']);
$conversion = $searchcraft->measure()->getDashboardConversion(['date_start' => '2026-01-01']);
$usage      = $searchcraft->measure()->getDashboardUsage(['granularity' => 'day']);
```

Compatibility
-------------

[](#compatibility)

Client versionSearchcraft Engine0.8.x0.10.x0.7.x0.7.9 - 0.9.xError Handling
--------------

[](#error-handling)

All operations should be wrapped in a try/catch block to handle errors:

```
use Searchcraft\Exception\SearchcraftException;

try {
    $results = $searchcraft->search()->query('products', 'smartphone');
} catch (SearchcraftException $e) {
    echo 'Error: ' . $e->getMessage();
}
```

Documentation
-------------

[](#documentation)

For view the rest of the endpoints and operations, please refer to the full [Searchcraft API documentation](https://docs.searchcraft.io?utm_campaign=oss&utm_source=github&utm_medium=searchcraft-php-client).

To run unit tests
-----------------

[](#to-run-unit-tests)

`./vendor/bin/pest`

License
-------

[](#license)

[Apache 2.0 License](LICENSE)

###  Health Score

40

—

FairBetter than 86% of packages

Maintenance90

Actively maintained with recent releases

Popularity19

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity37

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~114 days

Total

4

Last Release

51d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/47cd2c589a1565e403beca8f9c5941a58ed9b9ec5eb79f318e8f8dca5d23d6f6?d=identicon)[searchcraft](/maintainers/searchcraft)

---

Top Contributors

[![dmackinn](https://avatars.githubusercontent.com/u/903385?v=4)](https://github.com/dmackinn "dmackinn (24 commits)")

---

Tags

clientdatabaseenterprise-searchfuzzy-searchphp8psr-18sdksearch-as-you-typesearch-enginesearchcraftsite-searchtypo-toleranceapisearchsearchcraft

###  Code Quality

TestsPest

### Embed Badge

![Health badge](/badges/searchcraft-searchcraft-php/health.svg)

```
[![Health](https://phpackages.com/badges/searchcraft-searchcraft-php/health.svg)](https://phpackages.com/packages/searchcraft-searchcraft-php)
```

###  Alternatives

[telnyx/telnyx-php

Official Telnyx PHP SDK — APIs for Voice, SMS, MMS, WhatsApp, Fax, SIP Trunking, Wireless IoT, Call Control, and more. Build global communications on Telnyx's private carrier-grade network.

35789.4k2](/packages/telnyx-telnyx-php)[openai-php/client

OpenAI PHP is a supercharged PHP API client that allows you to interact with the Open AI API

5.8k28.0M318](/packages/openai-php-client)[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.5k5.9M736](/packages/sylius-sylius)[flow-php/flow

PHP ETL - Extract Transform Load - Data processing framework

85036.3k](/packages/flow-php-flow)[gotenberg/gotenberg-php

A PHP client for interacting with Gotenberg, a developer-friendly API for converting numerous document formats into PDF files, and more!

3856.2M31](/packages/gotenberg-gotenberg-php)[mailgun/mailgun-php

The Mailgun SDK provides methods for all API functions.

1.1k30.8M182](/packages/mailgun-mailgun-php)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
