Custom entity field in Search Index
Using Search API you have lots of choices for indexing fields in a search index like Solr. However sometimes you need more than can be accomplished by using 'aggregate fields' in the Search API User Interface. Sometimes you need to create a new field (that does not actually become part of the entity and then do some processing on it to give it a value when indexed by the Search API.
First, declare the new field:
<?php
/**
* Implements hook_entity_property_info_alter().
*/
function MY_MODULE_entity_property_info_alter(&$info) {
// Create a boolean flag field for solr search index that does not exist.
if (!empty($info['ENTITY_TYPE']['bundles']['BUNDLE_NAME']['properties'])) {
$search_field = array(
// Could be any type of field you need.
'type' => 'integer',
'label' => t('Super Flag'),
'description' => t("Flag as to whether it is a Super thing."),
'sanitized' => TRUE,
);
$info['ENTITY_TYPE']['bundles']['BUNDLE_NAME']['properties']['SEARCH_FIELD'] = $search_field;
}
}
?>
Now for the special processing to determine the value indexed in that field:
<?php
/**
* Implements hook_search_api_index_items_alter().
*/
function MY_MODULE_search_api_index_items_alter(&$items, SearchApiIndex $index) {
// Assign the Super flag if the select list item is 'great'.
// This is used for sorting, to sort by super.
foreach ($items as $id => $item) {
if (($item->type === 'BUNDLE_NAME') && (!empty($item->FIELD_TO_EVALUATE))) {
$item->SEARCH_FIELD = ($item->FIELD_TO_EVALUATE[LANGUAGE_NONE][0]['value'] === 'great') ? 1 : 0;
}
}
}
?>
Will require flushing cache to register the hooks and setting the new field to be indexed in the Search API UI as well as triggering a re-indexing of the content.