在这篇博客中,我们将学习如何向 Magento 2 elasticsearch 文档(产品)添加自定义字段。有时你需要上传一些不是产品属性的数据,或者它是一个产品属性,但在 elasticsearch 服务器上既不可搜索也不可过滤,这些数据稍后可用于在 Magento 中搜索和过滤产品。

让我们看看该怎么做:

首先,您需要创建一个类,该类将作为当 Magento 索引器运行时您想要索引的数据的提供者

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
declare(strict_types=1);

namespace Vendor\CustomModule\Model\Adapter\BatchDataMapper;

use Magento\AdvancedSearch\Model\Adapter\DataMapper\AdditionalFieldsProviderInterface;

/**
 * Provide data mapping for custom fields
 */
class CustomDataProvider implements AdditionalFieldsProviderInterface
{

    /**
     * @inheritdoc
     */
    public function getFields(array $productIds, $storeId)
    {

        $fields = [];
        
        foreach ($productIds as $productId) {
            $data = ""; //you can get you data here
            $fields[$productId] = ["custom_field" => $data];
        }

        return $fields;
    }

}

在上述类中,你可以看到我扩展了这个类Magento\AdvancedSearch\Model\Adapter\DataMapper\AdditionalFieldsProviderInterface,这是创建提供者类所必需的,同时你还需要定义getFields方法,该方法将为你提供访问所有产品和商店 ID 的权限。

现在,我们需要将这个类添加到模块的 di.xml 文件中,以便 Magento 在索引时知道要添加这个字段:

<virtualType name="additionalFieldsProviderForElasticsearch" type="Magento\AdvancedSearch\Model\Adapter\DataMapper\AdditionalFieldsProvider">
    <arguments>
        <argument name="fieldsProviders" xsi:type="array">
            <item name="custom_field" xsi:type="object">Vendor\CustomModule\Model\Adapter\BatchDataMapper\CustomDataProvider</item>
        </argument>
    </arguments>
</virtualType>

现在你已经通知 Magento 使用你的提供类将你的字段添加到弹性索引和文档中。

要检查你的代码是否正常工作,只需在浏览器中打开此 URL 以了解当前索引的名称:

http://localhost:9200/_all

在上述 URL 中,将 localhost 替换为你的Elasticsearch服务器主机,将 9200 替换为你的弹性服务器端口。在浏览器中执行该 URL,你将获得弹性索引的架构,以查找 custom_field,你将在mappings > properties keys 下找到它。

参考文档:https://webkul.com/blog/add-non-product-attribute-to-magento2-elastic-documents/