9951 explained code solutions for 126 technologies


php-elasticaHow do I use Elastic Search with PHP?


To use Elastic Search with PHP, you must first install the Elasticsearch PHP client library. You can do this by running the following command:

composer require elasticsearch/elasticsearch

Once the library is installed, you can use it to interact with your Elasticsearch cluster. For example, the following code will create an index called "my_index" in your cluster:

<?php

require 'vendor/autoload.php';

$client = Elasticsearch\ClientBuilder::create()->build();

$params = [
    'index' => 'my_index'
];

$response = $client->indices()->create($params);

print_r($response);

The output of this code will be:

Array
(
    [acknowledged] => 1
)

The code consists of the following parts:

  1. require 'vendor/autoload.php';: This line is used to load the autoloader file, which is generated by Composer and is used to autoload the Elasticsearch library.

  2. $client = Elasticsearch\ClientBuilder::create()->build();: This line creates an instance of the Elasticsearch client, which is used to interact with the Elasticsearch cluster.

  3. $params = [ 'index' => 'my_index' ];: This line sets up the parameters for the index creation operation.

  4. $response = $client->indices()->create($params);: This line sends a request to the Elasticsearch cluster to create the index specified in the $params array.

  5. print_r($response);: This line prints the response from the Elasticsearch cluster, which will be an array containing the acknowledged key set to 1 if the index was created successfully.

For more information on using Elasticsearch with PHP, please see the official documentation.

Edit this code on GitHub