2

How do you create your own solr field using Drupal 8's search api?

6

1) Copy /modules/contrib/search_api/src/Plugin/search_api/processor/AddURL.php into your own custom module at /src/Plugin/search_api/processor

2) Rename and rework (see below)

3) Add your extra field to the index at /admin/config/search/search-api/index/myindex/fields

4) Enable the processor on your search_api index

5) Reindex content and verify in solr that your new custom field is indexed.

http://127.0.0.1:8983/solr/#/mysolrcore/schema-browser?field=sm_mymodule_content_type, click on "Load Term Info" to see data loaded in.

Here's an example:

namespace Drupal\mymodule\Plugin\search_api\processor;

use Drupal\search_api\Datasource\DatasourceInterface;
use Drupal\search_api\Item\ItemInterface;
use Drupal\search_api\Processor\ProcessorPluginBase;
use Drupal\search_api\Processor\ProcessorProperty;

/**
 * Adds a custom type filter to the indexed data.
 *
 * @SearchApiProcessor(
 *   id = "mycustom_field",
 *   label = @Translation("Custom Field"),
 *   description = @Translation("Add a custom field to search index"),
 *   stages = {
 *     "add_properties" = 0,
 *   },
 *   locked = true,
 *   hidden = false,
 * )
 */
class CustomField extends ProcessorPluginBase {

  /**
   * machine name of the processor.
   * @var string
   */
  protected $processor_id = 'mycustom_field';

  /**
   * {@inheritdoc}
   */
  public function getPropertyDefinitions(DatasourceInterface $datasource = NULL) {
    $properties = array();

    if (!$datasource) {
      $definition = array(
        'label' => $this->t('Custom Field'),
        'description' => $this->t('custom field'),
        'type' => 'string',
        'processor_id' => $this->getPluginId(),
      );
      $properties[$this->processor_id] = new ProcessorProperty($definition);
    }

    return $properties;
  }

  /**
   * {@inheritdoc}
   */
  public function addFieldValues(ItemInterface $item) {
    $entity = $item->getOriginalObject()->getValue();

    $custom_field = '';

    // Use $entity to get custom field.


    $fields = $this->getFieldsHelper()
      ->filterForPropertyPath($item->getFields(), NULL, $this->processor_id);
    foreach ($fields as $field) {
      $field->addValue($custom_field);
    }

  }
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.