parisholley / wordpress-fantastic-elasticsearch

Improve wordpress search performance/accuracy and enable faceted search by leveraging an ElasticSearch server.
MIT License
162 stars 63 forks source link

How to use elasticsearch_searcher_query filter #128

Closed leopuleo closed 8 years ago

leopuleo commented 9 years ago

Hi @parisholley, many thanks for this amazing plugin. I'm starting a new project is going beyond the Wordpress search and I'm stating to use the plugin filters in order to create complex queries.

How can I modify the query to elastic index before WP send it? I believe the right filter to use is elasticsearch_searcher_query, is it right? Can you provide a simple example (like how to set the limit of results to 5)?

Thank you very much in advance.

jorgelopezs commented 9 years ago

You should use the elasticsearch_searcher_query hook in order to modify the query before it's sent. The add_filter() should be used in order to add your function. This filter passes an Elastica Query object to your hooked function as the 1st parameter.

Example: Not In A Class

add_filter('elasticsearch_searcher_query', 'hello');

function hello($query){

    //This function takes in the Elastica\Query parameter

    //return the Query object
    return $query;
}

In a Class

add_filter('elasticsearch_searcher_query', array($this, 'hello'));

function hello($query){

    //This function takes in the Elastica\Query parameter
   // you can call any of Elastica\Query's methods

    //return the Query object
    return $query;
}
Changing the Results returned to 5
add_filter('elasticsearch_searcher_query', 'limitResults');

function limitResults($query){
    //The filter gives us an Elastica\Query object
   //Call the Query's setSize method to change it to value of results  you want
    $query->setSize(5);

   //return the modified Query
   return $query;
}

Let me know if it helps.