Created
December 10, 2021 19:28
-
-
Save felipeelia/7a71aaa41e9c681e27c25dad794a392e to your computer and use it in GitHub Desktop.
ElasticPress 4.0.0 Search Algorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* These functions can be used by ElasticPress 3.5.5+ users wanting to | |
* use the search algorithm introduced as default in EP 4.0 | |
*/ | |
/** | |
* Change the search algorithm to the one introduced in ElasticPress 4.0. | |
* | |
* @param array $query Current query | |
* @param array $query_vars Query variables | |
* @param string $search_text Search text | |
* @param array $search_fields Search fields | |
* @return array New query | |
*/ | |
function ep_custom_change_search_algorithm( $query, $args, $search_text, $search_fields ) { | |
return [ | |
'bool' => [ | |
'should' => [ | |
[ | |
'multi_match' => [ | |
'query' => $search_text, | |
'type' => 'phrase', | |
'fields' => $search_fields, | |
'boost' => apply_filters( 'ep_match_phrase_boost', 3, $search_fields, $args ), | |
], | |
], | |
[ | |
'multi_match' => [ | |
'query' => $search_text, | |
'fields' => $search_fields, | |
'boost' => apply_filters( 'ep_match_boost', 1, $search_fields, $args ), | |
'fuzziness' => apply_filters( 'ep_match_fuzziness', 'auto', $search_fields, $args ), | |
'operator' => 'and', | |
], | |
], | |
[ | |
'multi_match' => [ | |
'query' => $search_text, | |
'type' => 'cross_fields', | |
'fields' => $search_fields, | |
'boost' => apply_filters( 'ep_match_cross_fields_boost', 1, $search_fields, $args ), | |
'analyzer' => 'standard', | |
'tie_breaker' => 0.5, | |
'operator' => 'and', | |
], | |
], | |
], | |
], | |
]; | |
} | |
add_filter( 'ep_formatted_args_query', 'ep_custom_change_search_algorithm', 10, 4 ); | |
/** | |
* Apply `1` as the weight for the cross_field clause. | |
* | |
* @param string $weighted_field The field and its weight as used in the ES query. | |
* @param string $field Field name | |
* @param string $weight Weight value | |
* @param array $fieldset Current subset of formatted ES args | |
* @return array New weighted field string | |
*/ | |
function ep_custom_adjust_weight_for_cross_fields( $weighted_field, $field, $weight, $fieldset ) { | |
if ( 'cross_fields' === $fieldset['type'] ) { | |
$weighted_field = "{$field}^1"; | |
} | |
return $weighted_field; | |
} | |
add_filter( 'ep_query_weighting_fields', 'ep_custom_adjust_weight_for_cross_fields', 10, 5 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment