PHP code example of searchcraft / searchcraft-php

1. Go to this page and download the library: Download searchcraft/searchcraft-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

searchcraft / searchcraft-php example snippets


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

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

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

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


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

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

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

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

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

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

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

$newIndex = $searchcraft->index()->createIndex('blog', [
    'language' => 'en',
    'search_fields' => ['title', 'content', 'tags'],
    'fields' => [
        'id' => [
            'type' => 'text',
            't',
            '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'
    ]
]);

$updatedIndex = $searchcraft->index()->updateIndex('blog', [
    'language' => 'en',
    'search_fields' => ['title', 'content', 'tags', 'summary'],
    'fields' => [
        'id' => [
            '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
    ]
]);

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

// 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();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

use Searchcraft\Exception\SearchcraftException;

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