---
title: Send Records for Indexing
slug: php-sdk/send-records-indexing
docTags: 
createdAt: 2024-05-13T16:20:20.940Z
---

:::hint{type="info"}
*This guide assumes you have installed the latest version of&#x20;*`klevu/php-sdk`*&#x20;, either via composer or from source, and autoloading is functioning as expected.*
:::

:::hint{type="info"}
Examples in this guide are for vanilla PHP and, as such, will use `new` to instantiate objects. If you are using a modern framework such as Magento or Symfony, you should utilise your object manager for dependency injection and preferencing of interfaces where possible.
:::

## Indexing Record Batches

To send batches of records to Klevu's indexer, first locate your Klevu API and REST AUTH keys and create an `AccountCredentials` object (see Quickstart for steps).

Next, extract the catalog information (eg, products; categories; custom entities) to be sent from your application, including all applicable variants if you are using complex products. As each system differs in storage and retrieval of data, the examples below simply contain hardcoded data.

:::hint{type="warning"}
As records of all types (KLEVU\_PRODUCT, KLEVU\_CATEGORY, etc) share an ID pool, you should implement a naming convention to differentiate records whose IDs would otherwise clash (for example, sending a product and a category, both with ID 1)
:::

Instantiate a new `RecordIterator` object and populate with `RecordInterface` items. Note, while you can create these using `new Record`, it is recommended to use the `RecordFactory` class for ease of development and future compatibility.

Finally, create a new `Indexing\BatchService` object and call the `send` method with the Record collection, catching and handling any exception thrown during execution.

At this point, you will have an `ApiResponseInterface` which can be checked for success status, as well as any errors returned by the Klevu API.

```php
<?php

declare(strict_types=1);

use Klevu\PhpSDK\Exception\Api\BadRequestException;
use Klevu\PhpSDK\Exception\Api\BadResponseException;
use Klevu\PhpSDK\Exception\ValidationException;
use Klevu\PhpSDK\Model\AccountCredentials;
use Klevu\PhpSDK\Model\Indexing\RecordFactory;
use Klevu\PhpSDK\Model\Indexing\RecordIterator;
use Klevu\PhpSDK\Service\Indexing\BatchService;

$accountCredentials = new AccountCredentials(
    jsApiKey: "klevu-123456780",
    restAuthKey: "ABCDE1234567890",
);

$recordFactory = new RecordFactory();
$records = new RecordIterator(
    data: [
        $recordFactory->create(
            data: [
                'id' => '1',
                'type' => 'KLEVU_PRODUCT',
                'relations' => [
                    'categories' => [
                        'values' => [
                            'category_1',
                        ],
                    ],
                ],
                'attributes' => [
                    'name' => [
                        'default' => 'Parent Product',
                    ],
                    'sku' => 'PARENT_PRODUCT',
                    'images' => [
                        [
                            'url' => 'https://www.klevu.com/parent-product.jpg',
                            'type' => 'default',
                        ],
                    ],
                    'prices' => [
                        [
                            'amount' => 42.0,
                            'currency' => 'GBP',
                            'type' => 'defaultPrice',
                        ],
                        [
                            'amount' => 10.0,
                            'currency' => 'GBP',
                            'type' => 'salePrice',
                        ],
                        [
                            'amount' => 3.14,
                            'currency' => 'GBP',
                            'type' => 'startPrice',
                        ],
                        [
                            'amount' => 50.0,
                            'currency' => 'GBP',
                            'type' => 'endPrice',
                        ],
                    ],
                    'url' => 'https://www.klevu.com/parent-product',
                    'inStock' => true,
                    'shortDescription' => [
                        'default' => 'Comfortable Chair',
                    ],
                    'description' => [
                        'default' => 'This is a very very comfortable chair',
                    ],
                ],
            ],
        ),      
        $recordFactory->create(
            data: [
                'id' => '2',
                'type' => 'KLEVU_PRODUCT',
                'relations' => [
                    'parentProduct' => [
                        'values' => [
                            '1',
                        ],
                    ],
                ],
                'attributes' => [
                    'name' => [
                        'default' => 'Variant Product',
                    ],
                    'sku' => 'VARIANT_PRODUCT',
                    'images' => [
                        [
                            'url' => 'https://www.klevu.com/variant-product.jpg',
                            'type' => 'default',
                        ],
                    ],
                    'prices' => [
                        [
                            'amount' => 42.0,
                            'currency' => 'GBP',
                            'type' => 'defaultPrice',
                        ],
                        [
                            'amount' => 3.14,
                            'currency' => 'GBP',
                            'type' => 'salePrice',
                        ],
                    ],
                    'url' => 'https://www.klevu.com/variant-product',
                    'inStock' => true,
                ],
            ],
        ),
    ],
);
$records->addItem(
    item: $recordFactory->create(
        data: [
            'id' => 'category_1',
            'type' => 'KLEVU_CATEGORY',
            'attributes' => [
                'name' => [
                    'default' => 'Example Category',
                ],
                'url' => 'https://www.klevu.com/simple-product',
                'categoryPath' => 'Foo/Bar',
            ],
        ],
    ),
);

$batchService = new BatchService(
    // Inject any relevant dependencies, such as HTTP Client; Logger; or User Agent provider
    //  as well as behaviour config, such as invalidRecordMode
);

$response = null;
try {
    $response = $batchService->send(
        accountCredentials: $accountCredentials,
        records: $records,
    );
} catch (ValidationException $exception) {
    // One or more passed arguments are invalid
} catch (BadRequestException $exception) {
    // Klevu API rejected the request as invalid
} catch (BadResponseException $exception) {
    // Klevu API responded in an unexpected manner
}

$sentSuccessfully = $response?->isSuccess() ?: false;
$messages = $response?->getMessages() ?: [];
```

### Handling Invalid Records

Prior to send, the PHP-SDK will validate each record in the provided batch. If any record fails this initial validation check, it will be removed from the batch to be sent. If removing invalid records leads to an empty batch, a `ValidationException` will be thrown and no API call will be attempted.

:::hint{type="warning"}
Note, the API may still reject an entire batch based upon the validity of a single record. In this instance, the operation will throw a `BadRequestException` . This behaviour cannot be changed via the SDK.
:::

To change the default behaviour and cause the internal validation to fail if *any* record is invalid, you can pass a flag to the BatchService during instantiation.

```php
<?php

declare(strict_types=1);

use Klevu\PhpSDK\Service\Indexing\InvalidRecordMode
use Klevu\PhpSDK\Service\Indexing\BatchService;

// Invalid records will be removed from a batch. 
//   Processing will continue for any valid records remaining.
// Default behaviour
$batchService = new BatchService(
    invalidRecordMode: InvalidRecordMode::SKIP,
);

// Presence of an invalid record will cause the entire batch
//   to be rejected prior to processing.
$batchService = new BatchService(
    invalidRecordMode: InvalidRecordMode::FAIL,
);
```

***

## Source Code Reference

- Api\Model\\[Indexing\RecordInterface](https://github.com/klevu/php-sdk/blob/master/src/Api/Model/Indexing/RecordInterface.php)
- Exception\Api\\[BadRequestException](https://github.com/klevu/php-sdk/blob/master/src/Exception/Api/BadRequestException.php)
- Exception\Api\\[BadResponseException](https://github.com/klevu/php-sdk/blob/master/src/Exception/Api/BadResponseException.php)
- Exception\\[ValidationException](https://github.com/klevu/php-sdk/blob/master/src/Exception/ValidationException.php)
- Model\\[AccountCredentials](https://github.com/klevu/php-sdk/blob/master/src/Model/AccountCredentials.php)
- Model\\[Indexing\Record](https://github.com/klevu/php-sdk/blob/master/src/Model/Indexing/Record.php)
- Model\\[Indexing\RecordFactory](https://github.com/klevu/php-sdk/blob/master/src/Model/Indexing/RecordFactory.php)
- Model\\[Indexing\RecordIterator](https://github.com/klevu/php-sdk/blob/master/src/Model/Indexing/RecordIterator.php)
- Service\\[Indexing\BatchService](https://github.com/klevu/php-sdk/blob/master/src/Service/Indexing/BatchService.php)



