Rus
Eng
Работа с поиском в Битрикс
Order site
By contacting me you will receive a reliable and knowledgeable contractor who will quickly and efficiently implement any task for you and your business.

All English-language materials have been translated fully automatically using the Google service

Навигация по разделам:

Подписываемся на событие индексации поиска

В init.php добавляем подписку на событие вызываемое перед индексацией элемента

$eventManager = \Bitrix\Main\EventManager::getInstance();

$eventManager->addEventHandler('search', 'BeforeIndex', ['Pro\Search', 'BeforeIndexHandler']);

Добавляем обработчик события:

class Search{

    /**
     * Обработчик исполняемый перед поисковой индексацией
     * @param $arFields array
     * @return array
     */
    public static function BeforeIndexHandler($arFields){
        /* ЗДЕСЬ ВАШ КОД */

        return $arFields;
    }
}

Удаляем из поискового индекса стандартные поля

В обработчик индексации добавляем:

if($arFields["MODULE_ID"] == "iblock" && substr($arFields["ITEM_ID"], 0, 1) != "S")
{
	$IBLOCK_ID = [\Pro\Data\Config::getCatalogIB()];//Здесь ID вашего каталога

	//Исключаем из индекса "Детальное описание" и "Анонс"
	$EXCLUDE_FIELDS = ["DETAIL_TEXT", "PREVIEW_TEXT"];
	if (CModule::IncludeModule('iblock') && $arFields["MODULE_ID"] == 'iblock' && in_array($arFields["PARAM2"], $IBLOCK_ID) && intval($arFields["ITEM_ID"]) > 0){
		$dbElement = CIblockElement::GetByID($arFields["ITEM_ID"]) ;
		if ($arElement = $dbElement->Fetch()){
			foreach ($EXCLUDE_FIELDS as $field){
				if (isset ($arElement[$field]) && strlen($arElement[$field]) > 0){
					$arFields["BODY"] = str_replace (CSearch::KillTags($arElement[$field]) , "", CSearch::KillTags($arFields["BODY"]) );
				}
			}
		}
	}
}

Добавляем в индекс новые поля

В обработчик индексации добавляем:

//Добавляем в индексацию поле "Текстовое поле"
if($arFields["MODULE_ID"] == "iblock" && substr($arFields["ITEM_ID"], 0, 1) != "S")
{
	$IBLOCK_ID = [\Pro\Data\Config::getCatalogIB()];//Здесь ID вашего каталога
	
	\Bitrix\Main\Loader::includeModule('iblock');

	\Bitrix\Iblock\Iblock::wakeUp($IBLOCK_ID)->getEntityDataClass();

	$elements = \Bitrix\Iblock\Elements\ElementCatalogTable::getByPrimary($arFields["ITEM_ID"], [
		'select' => ['ID', 'TEXT_FIELD'],
	])->fetchCollection();

	foreach ($elements as $element) {
		if ($element->getTextField()){
			if($element->getTextField()->getValue()){
				$arFields["PARAMS"]['TEXT_FIELD'] = $element->getTextField()->getValue();
				$arFields["BODY"] = 'Описание: ' . $element->getTextField()->getValue() . ' ' . $arFields["BODY"];
			}
		}
	}
}

Исключаем из поиска товары по условию

В обработчик индексации добавляем:

//Исключаем из индексации товары с определенным значением поля
if($arFields["MODULE_ID"] == "iblock" && substr($arFields["ITEM_ID"], 0, 1) != "S")
{
	$IBLOCK_ID = [\Pro\Data\Config::getCatalogIB()];//Здесь ID вашего каталога

	\Bitrix\Main\Loader::includeModule('iblock');

	\Bitrix\Iblock\Iblock::wakeUp($IBLOCK_ID)->getEntityDataClass();

	$elements = \Bitrix\Iblock\Elements\ElementCatalogTable::getByPrimary($arFields["ITEM_ID"], [
		'select' => ['ID', 'OTOBRAZHAT_NA_SAYTE'],
	])->fetchCollection();

	foreach ($elements as $element) {
		//Если "Отображать на сайте" = "Нет", то пропускаем
		if ($element->getOtobrazhatNaSayte()){
			if($element->getOtobrazhatNaSayte()->getValue() == 733){
				$arFields["PARAMS"]["search"] = "N";
			}else{
				$arFields["PARAMS"]["search"] = "Y";
			}
		}
	}
}

Before calling the bitrix:search.page component, we add a filter to display only those products that have the corresponding flag set

global $arSearch;
$arSearch = array(
	"PARAMS" => array(
			"search" => "Y"
	)
);

In the component itself, specify the name of the filter

<?$componentResult = $APPLICATION->IncludeComponent(
    "bitrix:search.page",
    ".default",
    array(
		...
		...
        "FILTER_NAME" => "arSearch",
		...
		...
    ),
    false
);
?>

After making changes, do not forget to reindex at /bitrix/admin/search_reindex.php?lang=ru

Comments

There are no comments yet, you can be the first to leave it

Leave a comment

The site uses a comment pre-moderation system, so your message will be published only after approval by the moderator

You are replying to a user's comment

Send

FEEDBACK

Email me

Please message me to discuss the task. I work remotely and officially (as a self-employed professional); my hourly rate is 1,800 RUB, and I can dedicate 3–4 hours a day to the project. I respond quickly, and the consultation is free.

An error occurred while sending, please try again after a while
Message sent successfully

Phones

+7(993) 007-18-96

Email

info@tichiy.ru

Address

Россия, г. Москва

By submitting the form, you automatically confirm that you have read and accept the Privacy Policy site