如何为中文商品名使用 IK 分词并支持拼音搜索?

解读

面试官真正想验证的是:

  1. 你是否理解 Magento 默认 Elasticsearch 分词器对中文“一字一 token”的缺陷;
  2. 能否把国内最常用的 IK Analyzer 平滑接入 Magento 索引流程,同时不破坏升级路径;
  3. 能否在 同一字段 里同时支持“汉字精确/模糊”+“拼音首字母/全拼”双重检索,且保证 索引体积、查询性能、分片平衡 在大型商城(SKU>100 万)可接受;
  4. 是否具备 DevOps 视角,即配置即代码、容器可重现、灰度验证。
    回答时要体现“国内合规数据源 + Magento 插件化 + Elasticsearch 映射模板”三位一体思路,避免直接改 vendor 目录。

知识点

  • Magento 2.4.x 强制使用 Elasticsearch 7.x/8.x 作为目录搜索引擎,所有文本字段最终落到 ES 的 mapping
  • 中文 IK 分词器(elasticsearch-analysis-ik)需安装在 所有数据节点 并重启集群;国内镜像源如清华、华为可加速
  • Magento 的 Search Request Builder 最终生成 multi_match 查询,可通过插件拦截并注入自定义 analyzer
  • 拼音检索方案主流有两种:elasticsearch-analysis-pinyin 插件 或 自维护 ngram+pinyin4j;国内大厂生产环境多用插件方式,维护成本低
  • EAV 属性 name 的 is_searchable 与 elasticsearch_field_mapping.xml 共同决定字段是否被索引
  • Index Template 优先级高于 Magento 自动生成的 mapping,需用 index_patterns : ["magento_product_*"] 锁定范围
  • 必须验证 IK 细粒度/智能分词 双模式差异,避免“手机壳”被拆成“手/机/壳”导致召回率下降
  • 拼音字段建议 edge_ngram + lowercase,长度 1-20,避免“zhang” 匹配 “张” 时评分异常
  • 国内 CDN 边缘节点 常缓存搜索建议,调试阶段需加 ?___store=cn&___cache_suffix={timestamp} 绕过
  • 最终需跑通 10w 商品压测:P99<200 ms、索引增量 <5 min、分片大小 <30 GB

答案

  1. 环境准备
    在 所有 Elasticsearch 数据节点 安装 IK 与拼音插件:
    bin/elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v7.17.0/elasticsearch-analysis-ik-7.17.0.zip
    bin/elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-pinyin/releases/download/v7.17.0/elasticsearch-analysis-pinyin-7.17.0.zip
    使用 国内华为镜像 可提速 3-5 倍;安装后滚动重启并验证 GET _cat/plugins 包含 analysis-ik 与 analysis-pinyin。

  2. 创建 Index Template 覆盖 Magento 产品索引
    在 Kibana 执行:

    PUT _index_template/magento_cn_template
    {
      "index_patterns": ["magento_product_*"],
      "priority": 300,
      "template": {
        "settings": {
          "number_of_shards": 3,
          "number_of_replicas": 1,
          "analysis": {
            "analyzer": {
              "ik_max_word_pinyin": {
                "tokenizer": "ik_max_word",
                "filter": ["pinyin_filter", "unique"]
              },
              "ik_smart_name": {
                "tokenizer": "ik_smart"
              }
            },
            "filter": {
              "pinyin_filter": {
                "type": "pinyin",
                "keep_first_letter": true,
                "keep_full_pinyin": true,
                "keep_none_chinese": true,
                "limit_first_letter_length": 20,
                "lowercase": true
              }
            }
          }
        },
        "mappings": {
          "properties": {
            "name": {
              "type": "text",
              "fields": {
                "ik_max": {
                  "type": "text",
                  "analyzer": "ik_max_word_pinyin"
                },
                "ik_smart": {
                  "type": "text",
                  "analyzer": "ik_smart_name"
                }
              }
            }
          }
        }
      }
    }
    

    该模板保证 新建 product 索引 自动携带 IK + 拼音多字段。

  3. 让 Magento 使用新字段
    在自定义模块 Vendor/CnSearch/etc/elasticsearch_field_mapping.xml 中声明:

    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Elasticsearch:etc/elasticsearch_field_mapping.xsd">
        <field name="name">
            <mapping>
                {"type":"text","fields":{"ik_max":{"type":"text","analyzer":"ik_max_word_pinyin"},"ik_smart":{"type":"text","analyzer":"ik_smart_name"}}}
            </mapping>
        </field>
    </config>
    

    执行 bin/magento indexer:reindex catalogsearch_fulltext,Magento 会按模板重建索引,无需改核心代码。

  4. 注入 Search Request 使用多字段查询
    创建插件 Vendor/CnSearch/Plugin/Search/RequestBuilder.php:

    public function aroundBuild(RequestBuilder $subject, callable $proceed, ...$args)
    {
        $request = $proceed(...$args);
        $query = $request->getQuery();
        if ($query instanceof MultiMatch && $query->getValue() === 'name') {
            $query->setFields(['name.ik_max^3', 'name.ik_smart^2', 'name^1']);
        }
        return $request;
    }
    

    在 di.xml 中声明拦截 Magento\Elasticsearch\SearchAdapter\RequestBuilder,即可让前端关键词同时命中 IK 细粒度、智能、原始 三列,拼音 已包含在 ik_max_word_pinyin 中。

  5. 验证与压测

    • 使用 POST magento_product_1/_analyze 验证“华为手机壳”拆成 华为/手机/手机壳 及 hw/sj/sjk
    • 在 CN Store 前端搜索“sj”应返回“手机壳”;搜索“huawei”应返回“华为”商品
    • 使用 JMeter 200 并发、随机 2000 关键词,P99 latency 需 <200 ms;索引增量 5 分钟内完成
    • 灰度发布:先切 10% 流量到新索引,监控 Elasticsearch 慢查询 >500 ms 的日志,确认无异常后全量
  6. 上线后运维

    • 把 Index Template 与 插件版本 写入 Ansible Playbook,保证新集群一键重建
    • 使用 Kibana Watcher 监控 search.queue 与 fielddata 内存,中文分词容易膨胀
    • 每季度用 IK 新增词典 更新热词,如“冰墩墩”,通过 POST _reload_search_analyzers 热加载,无需重启节点

拓展思考

  1. 如果商城同时面向 海外华人,需支持 繁简转换,可在 IK 词典 里加入 TW 词典,并在拼音过滤器加 keep_joined_full_pinyin: true,让“風殼”也能被“fengke”召回。
  2. 当 SKU 数量级到 千万 时,单索引分片数需调到 5-8,并启用 Elasticsearch ILM 把 30 天前只读索引 Shrink 到 1 分片,节约内存。
  3. 国内 阿里云 Elasticsearch 已内置 IK + Pinyin,但版本滞后,需确认与 Magento 2.4.6 要求的 ES 7.17 兼容;否则用 自建热数据 + 云冷数据 混合架构。
  4. 若要支持 语音搜索(微信小程序语音输入),可把 ASR 结果 直接走拼音字段,减少二次分词误差。
  5. 未来 Magento 转向 OpenSearch,需验证 analysis-ik 移植性;提前封装 Analyzer Service 接口,避免厂商锁定。