How to request the use of Elastica

This is my first time using Elastica and requesting data from ElasticSearch

For me, as a starter, I have a question about how to request 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 a hand.

Thanks,

+4
source share
2 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 complete the request, you need to connect to 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 indicate which index and type you want to query for the query

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

Now you can run your request

 $type->search($query); 

Edit : If you use the environment with names and the current version of Elastica, change all the lines in which new objects are created accordingly

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

etc.

+8
source

You can also request the following: (Thanks to http://tech.vg.no/2012/07/03/using-elastica-to-query-elasticsearch/ for a great article)

 <?php $query = new Elastica_Query_Builder('{ "query" : { "term": { "click": "true" } }, "facets" : { "matches" : { "terms" : { "field" : "pubid", "all_terms" : true, "size": 200 } } } }'); // Create a raw query since the query above can't be passed directly to the search method used below $query = new Elastica_Query($query->toArray()); // Create the search object and inject the client $search = new Elastica_Search(new Elastica_Client()); // Configure and execute the search $resultSet = $search->addIndex('blog') ->addType('posts') ->search($query); // Loop through the results foreach ($resultSet as $hit) { // ... } 
+1
source

Source: https://habr.com/ru/post/1444749/


All Articles