Working with search in Bitrix
Rus
Eng
Работа с поиском в Битрикс

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

Are you developing a new service, making improvements to the existing one and want to be better than your competitors? You have come to the right place. I offer you a comprehensive studio-level website development. From me you can order design, layout, programming, development of non-traditional functionality, implementation of communication between CMS, CRM and Data Analitics, as well as everything else related to sites, except for promotion.

Contact, I will always advise on all questions and help you find the most effective solution for your business. I am engaged in the creation of sites in Novosibirsk and in other regions of Russia, I also work with the CIS countries. You will be satisfied with our cooperation

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

Contact with me
Send message
By submitting the form, you automatically confirm that you have read and accept Privacy policy of site
Sending successful!
Thank you for contacting :) I will contact you as soon as possible
Sending failed
An error occurred while sending the request. Please wait and try again after a while or call my phone number