Search by

searchcraft / searchcraft-php

searchcraft

Searchcraft API PHP Client

v0.8.2 2026-10-25 18:46 UTC

This package is auto-updated.

Last update: 2026-11-22 13:02:23 UTC


README

Build faster, ship more. The next frontier in developer search tools is here. Searchcraft

Searchcraft API PHP Client

A PSR-compatible PHP client for the Searchcraft API.

Test Status

Documentation | Discord | FAQ | Issues / Requests | Searchcraft Cloud | Searchcraft Website

Installation

composer require searchcraft/searchcraft-php

You will also need to install a PSR-18 compatible HTTP client, such as Guzzle.

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

Basic Usage

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

The client uses PSR-18 HTTP Client 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 require an admin key or read key.

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']);

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

time_taken on the response is reported in seconds. limit defaults to 20 and is rejected client-side above 200.

Scoping a Search to Specific Fields

fields restricts a query to particular fields instead of the index's configured search_fields. Pass a field name, a list of names, or a map of name to boost. The engine honors it for fuzzy and term clauses.

// Single field
$results = $searchcraft->search()->query('my_index', 'search term', [
    'fields' => 'title'
]);

// Several fields, with per-field boosts
$results = $searchcraft->search()->query('my_index', 'search term', [
    'fields' => ['title' => 2.0, 'body' => 1.0]
]);

Boolean Occurrence

occur sets how the clause participates in matching. It is placed beside the mode key inside the query object for you.

$results = $searchcraft->search()->query('my_index', 'search term', [
    'mode'  => 'exact',
    'occur' => 'must',   // 'should' (default), 'must', or 'mustnot'
]);

occur and fields both describe a single clause, so they apply to string queries only. Passing either alongside an array query throws a SearchcraftException — set them inside the clause itself in that case.

Additional Search Options

$results = $searchcraft->search()->query('my_index', 'search term', [
    // Datetime field used to decay relevance for older documents,
    // overriding the index's own setting for this query.
    'time_decay_field' => 'publishedAt',

    // Relevance weight for this index within a federation search.
    'index_weighting' => 1.5,

    // Ordering by a field means hits come back with a null score.
    'order_by' => 'publishedAt',
    'sort' => 'desc',
]);

Complex Queries

Pass an array instead of a string to build a multi-clause query. It is forwarded to the engine verbatim, which is how you reach the query kinds that have no string shorthand. Each clause takes an occur of should, must, or mustnot, and a fields selector belongs inside the clause rather than in the options array.

$results = $searchcraft->search()->query('my_index', [
    ['occur' => 'must', 'fuzzy' => ['ctx' => 'breaking news']],

    // A single unparsed term against one field — useful for programmatic
    // filters.
    ['occur' => 'must', 'term' => ['ctx' => 'published', 'fields' => 'status']],

    ['occur' => 'mustnot', 'exact' => ['ctx' => 'category:opinion']],
]);

// Require at least two of the optional (`should`) clauses to match. The
// minimum cannot exceed the number of `should` clauses in the query.
// `minimum_number_should_match` was added in Searchcraft Engine 0.11.0.
$results = $searchcraft->search()->query('my_index', [
    ['occur' => 'should', 'fuzzy' => ['ctx' => 'election']],
    ['occur' => 'should', 'fuzzy' => ['ctx' => 'senate']],
    ['occur' => 'should', 'fuzzy' => ['ctx' => 'polls']],
], ['minimum_number_should_match' => 2]);

// Find documents similar to a reference document. `ctx` is the internal
// Searchcraft `document_id`, as returned on each search hit.
$results = $searchcraft->search()->query('my_index', [
    'more-like-this' => ['ctx' => '1a2b3c4d']
]);

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 administration operations require an admin key.

List Indexes

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

Get Index Details

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

Create Index

$newIndex = $searchcraft->index()->createIndex('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
        ],
        // json fields store nested objects and are queried via dotted
        // paths (e.g. metadata.author:tolkien). tokenizer and
        // expand_dots are json-specific options.
        'metadata' => [
            'type' => 'json',
            'stored' => true,
            'indexed' => true,
            'tokenizer' => 'raw',
            'expand_dots' => true
        ]
    ],
    'weight_multipliers' => [
        'title' => 2.0,
        'tags' => 1.0,
        'content' => 0.6
    ],
    // Optional: run an enrichment pipeline over documents before indexing.
    'ingestion' => [
        'enrichment_pipeline' => 'my-pipeline'
    ]
]);

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 for details on which properties are patchable.

$updatedIndex = $searchcraft->index()->updateIndex('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
    ]
]);

updateIndex is a whole-schema replacement, so anything you leave out reverts to its default. It is also the only way to change fields or to clear search_fields, weight_multipliers or language — patchIndex cannot do either.

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
]);

fields is not patchable — the engine carries the existing schema over verbatim and silently ignores a fields key here. search_fields, weight_multipliers and language cannot be cleared either, since the engine reads an empty value as "leave unchanged". Use updateIndex for both. time_decay_field can be cleared by passing an empty string.

Index Statistics

// Document count for a single index
$stats = $searchcraft->index()->getIndexStats('blog');

// Aggregate statistics for every index the key can reach. The response
// carries index_count, total_document_count, and an indices list mapping
// each index name to its own document_count.
$allStats = $searchcraft->index()->getStats();

Delete Index

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

Document Operations

Document operations require an admin key or ingest key.

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

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

Get Document

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

Delete Documents

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

Stopword Operations

Stopwords are excluded from indexing and from queries when the index has exclude_stop_words enabled.

// The index's custom stopword list
$stopwords = $searchcraft->stopwords()->getStopwords('blog');

// The engine's built-in defaults for the index's language, as distinct
// from the custom list above
$defaults = $searchcraft->stopwords()->getDefaultStopwords('blog');

$searchcraft->stopwords()->addStopwords('blog', ['whilst', 'thereof']);
$searchcraft->stopwords()->deleteStopwords('blog', ['thereof']);
$searchcraft->stopwords()->deleteAllStopwords('blog');

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 all federations
$federations = $searchcraft->federation()->listFederations();

Get Federation Details

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

Get Federations by Organization

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

List a Federation's Indexes

// The names of the indexes belonging to a federation
$indexNames = $searchcraft->federation()->listFederationIndexes('galaxy_news_federation');

Federation Statistics

// The federation's num_docs total, plus per-index num_docs and space_usage
$stats = $searchcraft->federation()->getFederationStats('galaxy_news_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 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 a federation
$result = $searchcraft->federation()->deleteFederation('old_federation');

AI Capabilities

Requires Searchcraft Engine 0.10.0 or later.

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

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

Get Keys for an Index

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

Check a Key's Permissions

The engine stores key permissions as a bitmask rather than a fixed set of levels. Combine the Searchcraft\Permissions constants with the bitwise OR operator. A key that simply lacks the permission is answered with a 403, which is reported as false rather than raised as an exception.

use Searchcraft\Permissions;

$canReadAnalytics = $searchcraft->authentication()
    ->checkKeyPermissions(Permissions::READ_ANALYTICS);

$canManageContent = $searchcraft->authentication()
    ->checkKeyPermissions(Permissions::MODIFY_DOCUMENTS | Permissions::MODIFY_INDEX);

// Presets are available for the conventional key shapes.
$isAdmin = $searchcraft->authentication()
    ->checkKeyPermissions(Permissions::PRESET_ADMIN);

// Add-ons combine with a level: a read key that can request AI summaries.
$canSummarize = $searchcraft->authentication()
    ->checkKeyPermissions(Permissions::PRESET_READ | Permissions::PRESET_AI);

Individual bits: SEARCH, MODIFY_SYNONYMS, MODIFY_STOP_WORDS, MODIFY_DOCUMENTS, MODIFY_INDEX, MODIFY_AUTH, LLM_RAG_SUMMARIES, LLM_EXPANDED_KEYWORD_SEARCH, READ_ANALYTICS.

Presets come in two kinds. Levels say what a key can change: PRESET_READ (1), PRESET_INGEST (15), PRESET_ADMIN (63), PRESET_SUPER_USER (511). Add-ons are features a key can use on top of its level: PRESET_AI (64) and PRESET_ANALYTICS (256). Combine them with |.

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

// 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

$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

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

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' => 1767225600]);
$usage      = $searchcraft->measure()->getDashboardUsage(['granularity' => 'days']);

// index_names may be given as an array; it is sent pipe-delimited.
$summary = $searchcraft->measure()->getDashboardSummary([
    'index_names' => ['products', 'articles'],
    'granularity' => 'weeks',
]);

date_start and date_end are Unix timestamps in seconds. granularity is one of minutes, hours, days, weeks, months, or years.

Compatibility

Client version Searchcraft Engine
0.8.2 0.11.x
0.8.0 - 0.8.1 0.10.x
0.7.x 0.7.9 - 0.9.x

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

For view the rest of the endpoints and operations, please refer to the full Searchcraft API documentation.

To run unit tests

./vendor/bin/pest

License

Apache 2.0 License