Skip to content

Instantly share code, notes, and snippets.

@felipeelia
Last active April 6, 2022 19:33
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felipeelia/2b48915c9f85b8a9b3149185ed4bbd40 to your computer and use it in GitHub Desktop.
Save felipeelia/2b48915c9f85b8a9b3149185ed4bbd40 to your computer and use it in GitHub Desktop.
Remove some meta fields from the ElasticPress/Elasticsearch index
<?php
add_filter(
'ep_prepare_meta_data',
function ( $prepared_meta ) {
foreach ( $prepared_meta as $key => $meta_val ) {
// Remove empty meta fields.
if ( empty( $key ) || empty( $meta_val ) || empty( $meta_val[0] ) ) {
unset( $prepared_meta[ $key ] );
continue;
}
// Remove fields with key starting with "field_".
if ( 0 === strpos( $meta_val[0], 'field_' ) ) {
unset( $prepared_meta[ $key ] );
continue;
}
// Remove fields with just letters, numbers, hyphens and underscores.
if ( '_sku' !== $key && preg_match( '/^([a-zA-Z0-9\-\_]*)$/', $meta_val[0] ) ) {
unset( $prepared_meta[ $key ] );
continue;
}
}
return $prepared_meta;
}
);
@felipeelia
Copy link
Author

This code is useful when you notice your content is not being fully indexed on ElasticPress/Elasticsearch. If you run
wp elasticpress index --setup --show-bulk-errors
and receive the following error
[illegal_argument_exception] Limit of total fields [5000] in index [<index_name>-post-1] has been exceeded
you need to reduce your meta fields number per post.

The code of this gist will remove all empty meta fields, fields with a value starting with "field_", and fields with a value containing only letters, numbers, hyphens, and underscores (probably just a code or hash).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment