magento 2.4 使用 SKU 搜索产品,返回一堆无关的产品

文章目录

    问题现象

    Magento 2.4 中,使用类似 “ab-cd-e-9”这样的 SKU 去搜索时,会发现返回了几千个产品。
    而排在前面的并不是我想要搜索的 SKU 完全匹配的产品,而是一些无关的产品。

    “ab-cd-e-9”两侧加上双引号能解决,但是用户不会这样干。

    之前处理过一例 magento 1.7 的远古版本的 SKU 搜索问题, 参考
    Magento 网站中无法通过 SKU 搜索到产品的问题排查
    解决方案是,改成 LIKE 的方式。但是 magento 2 之后没有了这个配置,直接使用了 Elasticsearch。在后台没法切换 MySQL 的搜索方案。

    github issue

    一个官方的讨论

    https://github.com/magento/magento2/issues/38125

    Product with sku that contains the complete search should be printed first and not last as the weight for the sku is superior to the name

    说是在 2.4 - dev 最新版本中修复了,今年6月份,修复了两年。。。

    思路

    如果 sku 完全匹配,则把这个产品排在第一位。

    google 搜索词

    magento search sku Hyphen split word issue

    hyphen 是横杠的意思

    问题的根源

    Elasticsearch 把横杠作为了一个分词符合,所以拆分成了 4 组,每组都很短,没有实际意义的英文短词,甚至字母,数字。

    https://magento.stackexchange.com/questions/358143/search-by-sku-in-magento-not-working-properly

    It seems that Elasticsearch treats the “-” character as word delimiter. You could tell Elasticsearch to ignore (strip) the “-” when indexing the SKU. The user can still enter the character, but Elasticsearch will treat it as being left out during the search process.

    使用 Elasticsearch 多字段 (multi-field) 特性

    如果你既需要精确匹配(如”aaa-bbb”整体),又希望支持全文检索(如单独搜索”aaa”或”bbb”),可以为字段设置多字段特性。这样,Elasticsearch 会为同一个字段值索引两种不同的方式。

    json
    PUT /your_index
    {
      "mappings": {
        "properties": {
          "your_field": {
            "type": "text",          // 主字段用于全文检索(会分词)
            "fields": {
              "raw": {               // 子字段,通过 your_field.raw 访问
                "type": "keyword"    // 子字段类型为 keyword,用于精确匹配、聚合
              }
            }
          }
        }
      }
    }
    

    另一个方案

    https://mirasvit.com/blog/how-to-enhance-the-search-by-sku-in-magento-2-with-long-tail-search.html#:~:text=By%20default%2C%20Magento%202%20search,search%20will%20return%20zero%20results.

    reddit 的一个讨论

    https://www.reddit.com/r/Magento/comments/1iimuyv/help_with_search_issues/

    If you’re using Elasticsearch 7+, tweaking the ngram or edge_ngram filters in catalogsearch_fulltext index settings might also help. Let me know if you need more details!

    关于作者 🌱

    我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊,或者关注我的个人公众号“大象工具”, 查看更多联系方式