Last active
December 10, 2021 19:25
-
-
Save felipeelia/f4f5dcf4684461d48efe70920cbffdfe to your computer and use it in GitHub Desktop.
ElasticPress: Make Elasticsearch search for the string in different fields
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 | |
/** | |
* Add a cross_field type clause to the ES query, so it searches for terms | |
* in different fields. | |
* | |
* @param array $query Current query | |
* @param array $args Query variables | |
* @param string $search_text Search text | |
* @param array $search_fields Search fields | |
* @return array | |
*/ | |
function ep_formatted_args_query( $query, $args, $search_text, $search_fields ) { | |
if ( ! @isset( $query['bool']['should'] ) ) { | |
return $query; | |
} | |
$query['bool']['should'][] = [ | |
'multi_match' => [ | |
'query' => $search_text, | |
'type' => 'cross_fields', | |
'fields' => $search_fields, | |
'boost' => 1, | |
'analyzer' => 'standard', | |
'tie_breaker' => 0.5, | |
'operator' => 'and', | |
], | |
]; | |
return $query; | |
} | |
add_filter( 'ep_formatted_args_query', 'ep_formatted_args_query', 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 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', '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