在大型媒体库中,如何为 /media 端点添加 ElasticPress 集成?
解读
面试官想确认三件事:
- 你是否理解 ElasticPress 只是 Elasticsearch 的 WordPress 代理层,真正决定数据流向的是 Indexable 与 Feature 注册机制;
- 你是否能把 wp-json/wp/v2/media 这一核心 REST 端点无缝切换到 ES 查询,而不是简单“开启模块”;
- 你是否能在 十万级甚至百万级附件 的场景下,兼顾 权限、分页、排序、聚合、失效策略 与 中文分词,并给出可落地的代码与运维方案。
国内大厂(新浪、网易、36Kr)的媒体库日增上万张图片,MySQL like '%xxx%' 直接打挂是常态,所以这道题是高并发媒体站必考题。
知识点
- ElasticPress 的 Indexable 注册表:ep_indexables_array 过滤器
- Post 类型扩展:attachment 默认被索引,但 REST 控制器未走 ES,需要自定义 EP_REST_Controller
- REST 请求拦截:rest_post_query 过滤器只对 post/post_page 生效,attachment 需要 rest_attachment_query
- meta 与 tax 聚合:attachment 通常绑定 _wp_attachment_metadata、_wp_attached_file,以及中文媒体库常用的 media_category、picture_type 等自定义分类法
- 权限矩阵:attachment 的 post_status 继承自父文章,大型站会设置 upload_files 的自定义 cap,必须在 ES 查询里同步 map
- 失效策略:wp_update_attachment_metadata、delete_attachment、edit_attachment 三类钩子需要 ep_delete_index_item / ep_sync_item
- 中文 IK 分词:Elasticsearch 需安装 analysis-ik,并在 mapping 里把 post_title、post_content、post_excerpt 设为 "text_ik"
- 分页与性能:ES 的 from+size 深翻页瓶颈,需用 search_after + PIT 方案,REST 层通过 offset→search_after 的透明转换实现
- 缓存雪崩:国内 CDN 回源集中,ES 查询结果必须落到 object cache(Redis),key 带 EP_VERSION 与 site locale
- 灰度与回滚:上线前通过 ep_enable_query_integration filter 做白名单 uid 灰度,出问题一键关闭即可回退 MySQL
答案
分五步落地,全部用插件方式交付,避免改核心:
- 注册 Indexable
add_filter('ep_indexables_array', function ($indexables) {
$indexables['attachment'] = '\ElasticPress\Indexable\Post\Post';
return $indexables;
});
这一步告诉 ElasticPress 把 attachment 当成 Post 来建索引,复用现有 mapping。
- 强制索引附件
add_filter('ep_attachment_sync_kill', '__return_false');
默认 ElasticPress 会屏蔽附件同步,关掉即可。
- 拦截 /media 端点查询
add_filter('rest_attachment_query', function ($args, $request) {
// 只有前台查询才走 ES,后台媒体列表继续 MySQL,方便编辑实时上传
if (defined('REST_REQUEST') && ! is_admin()) {
$args['ep_integrate'] = true;
// 把 REST 的 search、after、order、orderby 透传
$args['s'] = $request['search'] ?? '';
$args['search_fields'] = ['post_title', 'post_content', 'post_excerpt'];
$args['orderby'] = $request['orderby'] ?? 'date';
$args['order'] = $request['order'] ?? 'desc';
// 聚合:按 media_category 分组
$args['aggs'] = [
'media_cat' => [
'terms' => ['field' => 'terms.media_category.slug'],
],
];
// 深翻页保护
if ($request['offset'] > 5000) {
$args['search_after'] = json_decode(base64_decode($request['after']), true);
unset($args['offset']);
}
}
return $args;
}, 10, 2);
- 结果序列化补充字段
add_filter('rest_prepare_attachment', function ($response, $post) {
// 把 ES 返回的高亮 title 塞回去
if (! empty($post->elasticsearch_highlight)) {
$response->data['title']['rendered'] = $post->elasticsearch_highlight['post_title'][0];
}
// 聚合数据挂到 response header,方便前端渲染筛选项
if (! empty($post->elasticsearch_aggs)) {
$response->add_link('aggregations', rest_url('wp/v2/media/aggs'));
}
return $response;
}, 10, 2);
- 失效与运维
- 监听钩子:
add_action('edit_attachment', function ($post_ID) {
if (function_exists('ep_sync_item')) {
ep_sync_item('post', $post_ID);
}
});
add_action('delete_attachment', function ($post_ID) {
if (function_exists('ep_delete_item')) {
ep_delete_item('post', $post_ID);
}
});
- 中文分词:在 wp-cli 里执行
wp elasticpress put-mapping --indexables=post --mapping-file=mapping-attachment-ik.json
mapping-attachment-ik.json 里把 title、content、excerpt 字段 analyzer 设为 ik_max_word。
- 灰度:
add_filter('ep_enable_query_integration', function ($enabled, $query) {
// 只让 10% 用户先体验
return $enabled && (abs(crc32($_SERVER['HTTP_X_UID'] ?? '')) % 10 === 0);
}, 10, 2);
- 压测:用 wrk 模拟 500 并发,观察 ES 集群 CPU < 60%、查询 P99 < 200ms;MySQL QPS 下降 80% 即达标。
拓展思考
- 如果媒体库同时用到 阿里云 OSS+CDN,可把 ES 查询结果里的 attachment_url 一键替换为 CDN 域名,并在 ep_post_sync_args 过滤器里去掉 _wp_attachment_metadata 中的 sizes,避免索引膨胀。
- 当站点开启 多区域(Beijing+Shanghai)双活 时,ES 集群用 CCR(Cross Cluster Replication),WordPress 端通过 ep_host 过滤器做 就近读、写主 的逻辑,降低跨地域延迟。
- 未来 WordPress 6.6 计划把 attachment 默认控制器拆成 WP_REST_Attachments_Controller,拦截点可能由 rest_attachment_query 变为 rest_attachment_item_query,需要持续关注 core trac#59632 的变更,提前兼容。