PHP code example of zestic / weaviate-php-client

1. Go to this page and download the library: Download zestic/weaviate-php-client 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/ */

    

zestic / weaviate-php-client example snippets




use Weaviate\WeaviateClient;
use Weaviate\Auth\ApiKey;

// Connect to local Weaviate instance (default: localhost:8080)
$client = WeaviateClient::connectToLocal();

// Connect to Docker container on custom port
$client = WeaviateClient::connectToLocal('localhost:18080');

// Connect with authentication
$client = WeaviateClient::connectToLocal('localhost:8080', new ApiKey('your-api-key'));

// Connect to Weaviate Cloud
$client = WeaviateClient::connectToWeaviateCloud(
    'my-cluster.weaviate.network',
    new ApiKey('your-wcd-api-key')
);

// Connect to custom Weaviate instance
$client = WeaviateClient::connectToCustom(
    'my-server.com',        // host
    9200,                   // port
    true,                   // use HTTPS
    new ApiKey('api-key'),  // authentication
    [                       // custom headers
        'X-OpenAI-Api-Key' => 'your-openai-key',
        'X-Custom-Header' => 'custom-value'
    ]
);



use Weaviate\WeaviateClient;

$client = WeaviateClient::connectToLocal();
$schema = $client->schema();

// Check if collection exists
if (!$schema->exists('Article')) {
    // Create collection with properties
    $schema->create([
        'class' => 'Article',
        'description' => 'A collection for storing articles',
        'properties' => [
            [
                'name' => 'title',
                'dataType' => ['text'],
                'description' => 'Article title'
            ],
            [
                'name' => 'content',
                'dataType' => ['text'],
                'description' => 'Article content'
            ],
            [
                'name' => 'publishedAt',
                'dataType' => ['date'],
                'description' => 'Publication date'
            ],
            [
                'name' => 'viewCount',
                'dataType' => ['int'],
                'description' => 'Number of views'
            ]
        ]
    ]);
}

// Get complete schema
$completeSchema = $schema->get();

// Get specific collection schema
$articleSchema = $schema->get('Article');

// Add property to existing collection
$schema->addProperty('Article', [
    'name' => 'author',
    'dataType' => ['text'],
    'description' => 'Article author'
]);

// Get specific property
$authorProperty = $schema->getProperty('Article', 'author');

// Delete collection
$schema->delete('Article');



use Weaviate\WeaviateClient;
use Weaviate\Connection\HttpConnection;
use Weaviate\Auth\ApiKey;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\HttpFactory;

// Create HTTP client and factories
$httpClient = new Client();
$httpFactory = new HttpFactory();

// Create connection
$connection = new HttpConnection(
    'http://localhost:8080',
    $httpClient,
    $httpFactory,
    $httpFactory
);

// Create client with optional authentication
$client = new WeaviateClient($connection, new ApiKey('your-api-key'));

// Check if collection exists
if (!$client->collections()->exists('Organization')) {
    // Create collection with multi-tenancy
    $client->collections()->create('Organization', [
        'properties' => [
            ['name' => 'name', 'dataType' => ['text']],
            ['name' => 'createdAt', 'dataType' => ['date']]
        ],
        'multiTenancyConfig' => ['enabled' => true]
    ]);
}

// Manage tenants
use Weaviate\Tenants\Tenant;
use Weaviate\Tenants\TenantActivityStatus;

$collection = $client->collections()->get('Organization');
$tenants = $collection->tenants();

// Create tenants (multiple ways)
$tenants->create(['tenant1', 'tenant2']);
$tenants->create(new Tenant('tenant3', TenantActivityStatus::INACTIVE));

// Retrieve tenants
$allTenants = $tenants->get();
$specificTenant = $tenants->getByName('tenant1');

// Manage tenant status
$tenants->activate('tenant3');
$tenants->deactivate('tenant1');
$tenants->offload('tenant2');

// Work with tenant-specific data
$orgId = '123e4567-e89b-12d3-a456-426614174000';
$result = $collection
    ->withTenant('tenant1')
    ->data()
    ->create([
        'id' => $orgId,
        'name' => 'ACME Corp',
        'createdAt' => '2024-01-01T00:00:00Z'
    ]);

// Retrieve object from specific tenant
$org = $collection
    ->withTenant('tenant1')
    ->data()
    ->get($orgId);

use Weaviate\WeaviateClient;
use Weaviate\Connection\HttpConnection;

$client = WeaviateClient::connectToLocal();

// Create a collection with multi-tenancy enabled
$client->collections()->create('Articles', [
    'properties' => [
        ['name' => 'title', 'dataType' => ['text']],
        ['name' => 'content', 'dataType' => ['text']],
        ['name' => 'author', 'dataType' => ['text']]
    ],
    'multiTenancyConfig' => ['enabled' => true]
]);

use Weaviate\Tenants\Tenant;
use Weaviate\Tenants\TenantActivityStatus;

$collection = $client->collections()->get('Articles');
$tenants = $collection->tenants();

// Create tenants (multiple input types supported)
$tenants->create('customer-123');                                    // String
$tenants->create(['customer-456', 'customer-789']);                 // Array of strings
$tenants->create(new Tenant('customer-abc', TenantActivityStatus::INACTIVE)); // Tenant object
$tenants->create([
    new Tenant('customer-def'),
    new Tenant('customer-ghi', TenantActivityStatus::INACTIVE)
]); // Array of Tenant objects

// Retrieve tenants
$allTenants = $tenants->get();                    // Returns array indexed by tenant name
$specificTenant = $tenants->getByName('customer-123'); // Returns Tenant object or null
$multipleTenants = $tenants->getByNames(['customer-123', 'customer-456']);

// Check tenant existence
if ($tenants->exists('customer-123')) {
    echo "Tenant exists!";
}

// Remove tenants
$tenants->remove('customer-123');                // Single tenant
$tenants->remove(['customer-456', 'customer-789']); // Multiple tenants

// Manage tenant status
$tenants->activate('customer-123');      // Set to ACTIVE
$tenants->deactivate('customer-456');    // Set to INACTIVE
$tenants->offload('customer-789');       // Set to OFFLOADED

// Update multiple tenants at once
$tenants->activate(['customer-123', 'customer-456']);

// Manual status updates
$tenants->update(new Tenant('customer-123', TenantActivityStatus::OFFLOADED));

// Get tenant-specific collection instance
$customerCollection = $collection->withTenant('customer-123');

// Create data for specific tenant
$articleId = $customerCollection->data()->create([
    'title' => 'Customer 123 Article',
    'content' => 'This article belongs to customer 123',
    'author' => 'John Doe'
]);

// Retrieve data from specific tenant
$article = $customerCollection->data()->get($articleId);

// Update data within tenant
$customerCollection->data()->update($articleId, [
    'title' => 'Updated Article Title'
]);

// Data isolation - tenant A cannot access tenant B's data
$customerACollection = $collection->withTenant('customer-a');
$customerBCollection = $collection->withTenant('customer-b');

$articleA = $customerACollection->data()->create(['title' => 'Article A']);
$articleB = $customerBCollection->data()->create(['title' => 'Article B']);

// This will return null - tenant A cannot see tenant B's data
$result = $customerACollection->data()->get($articleB); // null

// Example: Comprehensive tenant management
try {
    $tenants = $collection->tenants();

    // Check if tenant exists before creating
    if (!$tenants->exists('new-customer')) {
        $tenants->create('new-customer');
    }

    // Batch create multiple tenants
    $newTenants = ['customer-001', 'customer-002', 'customer-003'];
    $tenants->create($newTenants);

    // Get all active tenants
    $allTenants = $tenants->get();
    $activeTenants = array_filter($allTenants, function($tenant) {
        return $tenant->getActivityStatus() === TenantActivityStatus::ACTIVE;
    });

    echo "Found " . count($activeTenants) . " active tenants";

} catch (Exception $e) {
    echo "Error managing tenants: " . $e->getMessage();
}
bash
composer