PHP Classes

Simple PHP Elastic Search: Index and search documents using Elastic Search

Recommend this page to a friend!
  Info   View files Example   View files View files (17)   DownloadInstall with Composer Download .zip   Reputation   Support forum   Blog (1)    
Last Updated Ratings Unique User Downloads Download Rankings
2023-11-30 (5 months ago) RSS 2.0 feedNot enough user ratingsTotal: 61 This week: 6All time: 10,453 This week: 16Up
Version License PHP version Categories
simple-elasticsearch 7.0.0Custom (specified...7.1Searching, Web services, PHP 7
Description 

Author

This package can index and search documents using Elastic Search.

It can connect to an Elastic Search server and perform several types of operations to index and search documents.

Currently, it can:

- Put and get an index of a given name

- Put and get a mapping in an index

- Put and get a document template

- Post a document by id or template

- Get a document by id

- Delete document by id

- Search documents using the given parameters

- Listing documents with pagination

- Perform SQL queries

- Translate SQL to DSL

- Delete a template or an index

- Aggregate documents

Picture of Leonardo Di Sarli
  Performance   Level  
Name: Leonardo Di Sarli <contact>
Classes: 11 packages by
Country: Brazil Brazil
Age: ???
All time rank: 3921316 in Brazil Brazil
Week rank: 14 Up2 in Brazil Brazil Up
Innovation award
Innovation award
Nominee: 5x

Winner: 2x

Example

<?php

require_once __DIR__ . '/../vendor/autoload.php';

use
SimpleElasticsearch\SimpleElasticsearch;

$host = 'http://localhost:9200/';
$elastic = new SimpleElasticsearch($host);
$elastic->setConnectionOptions([
   
'connect_timeout' => 5,
   
'timeout' => 5,
]);

$documentName = 'document';
$indexName = 'test';
$id = '01HDRQRB0VPDDB9HWHX3MGY6XG';
$mapping = [
   
'properties' => [
       
'name' => [
           
'type' => 'keyword',
        ],
       
'email' => [
           
'type' => 'keyword',
        ],
       
'gender' => [
           
'type' => 'byte',
        ]
    ]
];
$template = [
   
'index_patterns' => [
       
'document*'
   
],
   
'mappings' => [
       
'_source' => [
           
'enabled' => true,
        ],
       
'properties' => [
           
'name' => [
               
'type' => 'keyword',
            ],
           
'created' => [
               
'type'=> 'date',
               
'format' => 'yyyy-MM-dd HH:mm:ss',
            ],
        ]
    ]
];
$data = [
   
'name' => 'user',
   
'email' => 'test@test.com',
   
'gender' => 0,
];
$dataTemplate = [
   
'name' => 'document1',
   
'created' => date('Y-m-d H:i:s'),
];
$query = "SELECT * FROM test WHERE email LIKE '%test@test.com' ORDER BY email DESC";
$dslQuery = [
   
'term' => [
       
'email' => [
           
'value' => 'test@test.com',
           
'boost' => 1,
        ],
    ],
];

$dslQueryAggregate = [
   
'wildcard' => [
       
'email' => [
           
'wildcard' => '*1-test@test.com',
           
'boost' => 1,
        ],
    ],
];

$dslAgregate = [
   
'genders' => [
       
'terms' => [
           
'field' => 'gender',
        ]
    ]
];

print_r('Is connected');
echo
PHP_EOL;
$isConnected = $elastic->isConnected();
$response = 'Elastic is connected';
if (!
$isConnected) {
   
$response = 'Elastic is NOT connected';
}
print_r($response);
echo
PHP_EOL;
print_r('===================================================');
echo
PHP_EOL;

print_r('Put index');
echo
PHP_EOL;
$index = $elastic->putIndex(
   
$indexName
);
print_r($index);
print_r('===================================================');
echo
PHP_EOL;

print_r('Put mapping');
echo
PHP_EOL;
$newMapping = $elastic->putMapping(
   
$indexName,
   
$mapping
);
print_r($newMapping);
print_r('===================================================');
echo
PHP_EOL;

print_r('Put template');
echo
PHP_EOL;
$newTemplate = $elastic->putTemplate(
   
$documentName,
   
$template
);
print_r($newTemplate);
print_r('===================================================');
echo
PHP_EOL;

print_r('Get index');
echo
PHP_EOL;
$getIndex = $elastic->getIndex(
   
$indexName
);
print_r($getIndex);
print_r('===================================================');
echo
PHP_EOL;

print_r('Get mapping');
echo
PHP_EOL;
$getMapping = $elastic->getMapping(
   
$indexName
);
print_r($getMapping);
print_r('===================================================');
echo
PHP_EOL;

print_r('Get template');
echo
PHP_EOL;
$getTemplate = $elastic->getTemplate(
   
$documentName
);
print_r($getTemplate);
print_r('===================================================');
echo
PHP_EOL;

print_r('Post documents with template');
echo
PHP_EOL;
$postDocumentTemplate = $elastic->postDocument(
   
$documentName,
   
$dataTemplate
);
print_r($postDocumentTemplate);
print_r('===================================================');
echo
PHP_EOL;

print_r('Post documents passing id');
echo
PHP_EOL;
$postDocument = $elastic->postDocument(
   
$indexName,
   
$data,
   
$id
);
print_r($postDocument);
print_r('===================================================');
echo
PHP_EOL;

print_r('get document by id');
echo
PHP_EOL;
$getDocument = $elastic->getDocument(
   
$indexName,
   
$id
);
print_r($getDocument);
print_r('===================================================');
echo
PHP_EOL;

print_r('Post documents');
echo
PHP_EOL;
for (
$i = 0; $i < 60; $i++) {
   
$data['name'] = 'user ' . $i;
   
$data['email'] = $i . '-test@test.com';
   
$data['gender'] = rand(0, 1);
   
$postDocument = $elastic->postDocument(
       
$indexName,
       
$data,
       
$i
   
);
}
print_r('60 documents added') . PHP_EOL;
print_r('===================================================');
echo
PHP_EOL;

sleep(1);

print_r('Delete document');
echo
PHP_EOL;
$deleteDocument = $elastic->deleteDocument(
   
$indexName,
   
$id
);
print_r($deleteDocument);
print_r('===================================================');
echo
PHP_EOL;

print_r('Search documents');
echo
PHP_EOL;
$searchDocuments = $elastic->searchDocuments(
   
$indexName,
   
$dslQuery
);
print_r($searchDocuments);
print_r('===================================================');
echo
PHP_EOL;

print_r('Aggregate documents');
echo
PHP_EOL;
$searchDocuments = $elastic->aggregateDocuments(
   
$indexName,
   
$dslAgregate,
   
$dslQueryAggregate
);
print_r($searchDocuments);
print_r('===================================================');
echo
PHP_EOL;

print_r('Lits documents');
echo
PHP_EOL;
$listDocuments = $elastic->listDocuments(
   
$indexName
);
print_r($listDocuments);
print_r('===================================================');
echo
PHP_EOL;

print_r('Lits documents paginated');
echo
PHP_EOL;
for (
$page = 2; $page <= 3; $page++) {
   
$listDocumentsPaginated = $elastic->listDocuments(
       
$indexName,
       
$page
   
);
   
print_r($listDocumentsPaginated);
}
print_r('===================================================');
echo
PHP_EOL;

print_r('sql');
echo
PHP_EOL;
$sql = $elastic->sql(
   
$query,
   
'JSON'
);
print_r($sql);
print_r('===================================================');
echo
PHP_EOL;

print_r('sql cursor');
echo
PHP_EOL;
for (
$i = 0; $i < 3; $i++) {
    if (isset(
$sql['cursor']) && !empty($sql['cursor'])) {
       
$sql = $elastic->sqlCursor(
           
$sql['cursor']
        );
       
print_r($sql);
    }
}
print_r('===================================================');
echo
PHP_EOL;

print_r('translate');
echo
PHP_EOL;
$translate = $elastic->translate(
   
$query
);
print_r($translate);
print_r('===================================================');
echo
PHP_EOL;

print_r('Delete template');
echo
PHP_EOL;
$deleteTemplate = $elastic->deleteTemplate(
   
$documentName
);
print_r($deleteTemplate);
print_r('===================================================');
echo
PHP_EOL;

print_r('Delete index');
echo
PHP_EOL;
$deleteIndex = $elastic->deleteIndex(
   
$indexName
);
print_r($deleteIndex);
print_r('===================================================');
echo
PHP_EOL;


Details

Simple Elasticsearch PHP

Latest Version codecov CI Build Downloads Old Downloads PRs Welcome Packagist License (custom server)

PHP library to connect to and use Elasticsearch in a simple way.

Installation

Release 7.0.0 Requires PHP 8.3

Release 6.0.0 Requires PHP 8.2

Release 5.0.0 Requires PHP 8.1

Release 4.0.0 Requires PHP 7.4

Release 3.0.0 Requires PHP 7.3

Release 2.0.0 Requires PHP 7.2

Release 1.0.0 Requires PHP 7.1

The recommended way to install is through Composer.

composer require not-empty/simple-elasticsearch-php-lib

Usage

Setting up connection

use SimpleElasticsearch\SimpleElasticsearch;
$host = 'http://localhost:9200/';
$elastic = new SimpleElasticsearch($host);
$elastic->setConnectionOptions([
    'connect_timeout' => 5,
    'timeout' => 5,
]);

Checking if connection is available

...
$isConnected = $elastic->isConnected();
var_dump($isConnected);

Putting an index

...
$indexName = 'test';
$index = $elastic->putIndex(
    $indexName
);
var_dump($index);

Putting a mapping

...
$indexName = 'test';
$mapping = [
    'properties' => [
        'name' => [
            'type' => 'keyword',
        ],
        'email' => [
            'type' => 'keyword',
        ],
        'gender' => [
            'type' => 'byte',
        ]
    ]
];
$newMapping = $elastic->putMapping(
    $indexName,
    $mapping
);
var_dump($newMapping);

Putting a template

...
$documentName = 'document';
$template = [
    'index_patterns' => [
        'document*'
    ],
    'mappings' => [
        '_source' => [
            'enabled' => true,
        ],
        'properties' => [
            'name' => [
                'type' => 'keyword',
            ],
            'created' => [
                'type'=> 'date',
                'format' => 'yyyy-MM-dd HH:mm:ss',
            ],
        ]
    ]
];
$newTemplate = $elastic->putTemplate(
    $documentName,
    $template
);
var_dump($newTemplate);

Getting an index

...
$indexName = 'test';
$getIndex = $elastic->getIndex(
    $indexName
);
var_dump($getIndex);

Getting a mapping

...
$indexName = 'test';
$getMapping = $elastic->getMapping(
    $indexName
);
var_dump($getMapping);

Getting a template

...
$documentName = 'document';
$getTemplate = $elastic->getTemplate(
    $documentName
);
var_dump($getTemplate);

Posting a document with template

...
$documentName = 'document';
$dataTemplate = [
    'name' => 'document1',
    'created' => date('Y-m-d H:i:s'),
];
$postDocumentTemplate = $elastic->postDocument(
    $documentName,
    $dataTemplate
);
var_dump($postDocumentTemplate);

Posting a document passing the id

...
$documentName = 'document';
$indexName = 'test';
$data = [
    'name' => 'user',
    'email' => 'test@test.com',
    'gender' => 0,
];
$id = '01HDRQRB0VPDDB9HWHX3MGY6XG';
$postDocument = $elastic->postDocument(
    $indexName,
    $data,
    $id
);
var_dump($postDocument);

Getting a document by his id

...
$indexName = 'test';
$id = '01HDRQRB0VPDDB9HWHX3MGY6XG';
$getDocument = $elastic->getDocument(
    $indexName,
    $id
);
var_dump($getDocument);

Deleting a document by his id

...
$indexName = 'test';
$id = '01HDRQRB0VPDDB9HWHX3MGY6XG';
$deleteDocument = $elastic->deleteDocument(
    $indexName,
    $id
);
var_dump($deleteDocument);

Searching documents

...
$indexName = 'test';
$dslQuery =  [
    'term' => [
        'email' => [
            'value' => 'test@test.com',
            'boost' => 1,
        ],
    ],
];
$searchDocuments = $elastic->searchDocuments(
    $indexName,
    $dslQuery
);
var_dump($searchDocuments);

Listing documents

...
$indexName = 'test';
$listDocuments = $elastic->listDocuments(
    $indexName
);
var_dump($listDocuments);

Listing documents paginated

...
$indexName = 'test';
$page = 2;
$listDocumentsPaginated = $elastic->listDocuments(
    $indexName,
    $page
);
var_dump($listDocumentsPaginated);

Executing 'SQL' querys

...
$query = "SELECT * FROM test WHERE email LIKE '%test@test.com' ORDER BY email DESC";
$sqlResponse = $elastic->sql(
    $query
);
var_dump($sqlResponse);

Executing 'SQL' querys with cursor to paginate

...
// var $sql has data returned from previous query with the cursor
$sqlCursorResponse = $elastic->sqlCursor(
    $sql['cursor']
);
var_dump($sqlCursorResponse);

Translating 'SQL' query to 'DSL' query

...
$query = "SELECT * FROM test WHERE email LIKE '%test@test.com' ORDER BY email DESC";
$translate = $elastic->translate(
    $query
);
var_dump($translate);

Deleting template

...
$documentName = 'document';
$deleteTemplate = $elastic->deleteTemplate(
    $documentName
);
var_dump($deleteTemplate);

Deleting index

...
$indexName = 'test';
$deleteIndex = $elastic->deleteIndex(
    $indexName
);
var_dump($deleteIndex);

Aggregating documents

...
$indexName = 'test';
$dslAgregate = [
    'genders' => [
        'terms' => [
            'field' => 'gender',
        ]
    ]
];
$dslQueryAggregate =  [
    'wildcard' => [
        'email' => [
            'wildcard' => '*1-test@test.com',
            'boost' => 1,
        ],
    ],
];
$aggregateDocuments = $elastic->aggregateDocuments(
    $indexName,
    $dslAgregate,
    $dslQueryAggregate
);
var_dump($aggregateDocuments);

if you want an environment to run or test it, you can build and install dependences like this

docker build --build-arg PHP_VERSION=8.3-rc-cli -t not-empty/simple-elasticsearch-php-lib:php83 -f contrib/Dockerfile .

Access the container

docker run -v ${PWD}/:/var/www/html -it not-empty/simple-elasticsearch-php-lib:php83 bash

Verify if all dependencies is installed

composer install --no-dev --prefer-dist

and run

php sample/elastic-sample.php

Development

Want to contribute? Great!

The project using a simple code. Make a change in your file and be careful with your updates! Any new code will only be accepted with all validations.

To ensure that the entire project is fine:

First you need to building a correct environment to install all dependences

docker build --build-arg PHP_VERSION=8.3-rc-cli -t not-empty/simple-elasticsearch-php-lib:php83 -f contrib/Dockerfile .

Access the container

docker run -v ${PWD}/:/var/www/html -it not-empty/simple-elasticsearch-php-lib:php83 bash

Install all dependences

composer install --dev --prefer-dist

Run all validations

composer check

Not Empty Foundation - Free codes, full minds


  Files folder image Files  
File Role Description
Files folder image.github (1 directory)
Files folder imagecontrib (4 files)
Files folder imagesample (1 file)
Files folder imagesrc (2 files)
Files folder imagetests (2 files)
Accessible without login Plain text file composer.json Data Auxiliary data
Accessible without login Plain text file composer.lock Data Auxiliary data
Accessible without login Plain text file LICENSE Lic. License text
Accessible without login Plain text file phpcs.xml Data Auxiliary data
Accessible without login Plain text file phpmd.xml Data Auxiliary data
Accessible without login Plain text file phpunit.xml Data Auxiliary data
Accessible without login Plain text file README.md Doc. Documentation

  Files folder image Files  /  .github  
File Role Description
Files folder imageworkflows (1 file)

  Files folder image Files  /  .github  /  workflows  
File Role Description
  Accessible without login Plain text file php.yml Data Auxiliary data

  Files folder image Files  /  contrib  
File Role Description
  Accessible without login Plain text file coverage-checker.php Example Example script
  Accessible without login Plain text file Dockerfile Data Auxiliary data
  Accessible without login Plain text file pre-commit Data Auxiliary data
  Accessible without login Plain text file setup.sh Data Auxiliary data

  Files folder image Files  /  sample  
File Role Description
  Accessible without login Plain text file elastic-sample.php Example Example script

  Files folder image Files  /  src  
File Role Description
  Plain text file BaseElasticsearch.php Class Class source
  Plain text file SimpleElasticsearch.php Class Class source

  Files folder image Files  /  tests  
File Role Description
  Plain text file BaseElasticsearchTest.php Class Class source
  Plain text file SimpleElasticsearchTest.php Class Class source

 Version Control Unique User Downloads Download Rankings  
 100%
Total:61
This week:6
All time:10,453
This week:16Up