php-elasticaHow can I use the PHP Elastica API to query data?
The PHP Elastica API can be used to query data in an Elasticsearch index. Queries can be constructed using the Search
object and the Query
object.
Example
<?php
// include the Elastica lib
require_once 'path/to/elastica/lib/Elastica/Autoloader.php';
Elastica\Autoloader::register();
// create an instance of the Elastica client
$client = new Elastica\Client();
// create a search object
$search = new Elastica\Search($client);
// create a query object
$query = new Elastica\Query();
// set the query string
$query->setQueryString('example');
// set the index to search
$search->addIndex('my_index');
// set the type to search
$search->addType('my_type');
// execute the query
$results = $search->search($query);
// print the results
print_r($results);
Output example
Elastica\ResultSet Object
(
[_results:protected] => Array
(
[0] => Elastica\Result Object
(
[_data:protected] => Array
(
[_index] => my_index
[_type] => my_type
[_id] => 1
[_score] => 1
[_source] => Array
(
[field1] => value1
[field2] => example
[field3] => value3
)
)
)
)
)
The code above:
- includes the Elastica library (
require_once 'path/to/elastica/lib/Elastica/Autoloader.php';
) - creates an instance of the Elastica client (
$client = new Elastica\Client();
) - creates a search object (
$search = new Elastica\Search($client);
) - creates a query object (
$query = new Elastica\Query();
) - sets the query string (
$query->setQueryString('example');
) - sets the index to search (
$search->addIndex('my_index');
) - sets the type to search (
$search->addType('my_type');
) - executes the query (
$results = $search->search($query);
) - prints the results (
print_r($results);
)
Helpful links
More of Php Elastica
- How do I configure PHP Elastica using YML?
- How can I use PHP and Elastica to parse XML data?
- How can I use Elastic Search with PHP?
- How can I use Amazon Elastic Transcoder with PHP?
- How do I use Elastic Search with PHP?
- How can I use the Elasticsearch PHP client to interact with an Elasticsearch server?
- How can I use Elastica to create a query in PHP?
- How can I use PHP to create an elastic query?
- How can I use a PHP Elastic Query Builder to create an effective search query?
- How can I use the Elastica options with PHP?
See more codes...