Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query using Elastica

This is my first time using Elastica and querying data from the ElasticSearch

For me, as starter I have a question on how to query the code below using Elastica?:

curl 'http://localhost:9200/myindex/_search?pretty=true' -d '{     
  "query" : {
    "term": {
      "click": "true"
    }   },   "facets" : {
    "matches" : {
      "terms" : {
          "field" : "pubid",
          "all_terms" : true,
          "size": 200 
      }
    }   
  } 
}'

Hope someone can lend me an arm here.

Thanks,

like image 443
Wondering Coder Avatar asked Jan 15 '23 02:01

Wondering Coder


1 Answers

This should do:

// Create a "global" query
$query = new Elastica_Query;

// Create the term query
$term = new Elastica_Query_Term;
$term->setTerm('click', 'true');

// Add term query to "global" query
$query->setQuery($term);

// Create the facet
$facet = new Elastica_Facet_Terms('matches');
$facet->setField('pubid')
      ->setAllTerms(true)
      ->setSize(200);

// Add facet to "global" query
$query->addFacet($facet);

// Output query
echo json_encode($query->toArray());

To run the query, you need to conntect to your ES servers

// Connect to your ES servers
$client = new Elastica_Client(array(
    'servers' => array(
        array('host' => 'localhost', 'port' => 9200),
        array('host' => 'localhost', 'port' => 9201),
        array('host' => 'localhost', 'port' => 9202),
        array('host' => 'localhost', 'port' => 9203),
        array('host' => 'localhost', 'port' => 9204),
    ),
));

And specify which index and type you want to run your query against

// Get index
$index = $client->getIndex('myindex');
$type = $index->getType('typename');

Now you can run your query

$type->search($query);

Edit: If you are using a namespaced enviroment and a current version of Elastica, change all the lines where new objects are created accordingly to

$query = new \Elastica\Query;
$facet = new \Elastica\Facet\Terms

and so on

like image 168
Thorsten Avatar answered Jan 17 '23 18:01

Thorsten