diff --git a/src/ElasticSearch/Parameters/Factory/IndexFactory.php b/src/ElasticSearch/Parameters/Factory/IndexFactory.php index 4991e4a..f3fdb28 100644 --- a/src/ElasticSearch/Parameters/Factory/IndexFactory.php +++ b/src/ElasticSearch/Parameters/Factory/IndexFactory.php @@ -4,6 +4,8 @@ namespace Drupal\elasticsearch_connector\ElasticSearch\Parameters\Factory; use Drupal\elasticsearch_connector\Event\PrepareDocumentIndexEvent; use Drupal\search_api\IndexInterface; +use Drupal\search_api\Utility\Utility; +use Drupal\Core\Field\FieldDefinitionInterface; use Drupal\elasticsearch_connector\Event\PrepareIndexEvent; use Drupal\elasticsearch_connector\Event\PrepareIndexMappingEvent; use Drupal\search_api_autocomplete\Suggester\SuggesterInterface; @@ -120,12 +122,24 @@ class IndexFactory { /** @var \Drupal\search_api\Item\FieldInterface $field */ foreach ($item as $name => $field) { $field_type = $field->getType(); - $values = []; + + // Set to list only if list. + $value = NULL; + if (self::isFieldList($index, $field)) { + $value = []; + } + if (!empty($field->getValues())) { - foreach ($field->getValues() as $value) { - $values[] = self::getFieldValue($field_type, $value); + foreach ($field->getValues() as $val) { + if (self::isFieldList($index, $field)) { + $value[] = self::getFieldValue($field_type, $val); + } + else { + $value = self::getFieldValue($field_type, $val); + } } - $data[$field->getFieldIdentifier()] = $values; + + $data[$field->getFieldIdentifier()] = $value; } } // Allow other modules to alter document before we create it. @@ -299,4 +313,35 @@ class IndexFactory { return $value; } + /** + * Helper function. Returns true if the field is a list of values. + * + * @param \Drupal\search_api\IndexInterface $index + * @param \Drupal\search_api\Item\Field $field + * + * @return bool + */ + protected static function isFieldList($index, $field) { + $is_list = FALSE; + + // Ensure we get the field definition for the root/parent field item (ie tags). + $property_definitions = $index->getPropertyDefinitions($field->getDatasourceId()); + $root_property = Utility::splitPropertyPath($field->getPropertyPath(), FALSE)[0]; + $field_definition = $property_definitions[$root_property]; + + // Using $field_definition->isList() doesn't seem to be accurate, so we + // check the fieldStorage cardinality !=1. + if ($field_definition instanceof FieldDefinitionInterface) { + $storage = $field_definition->getFieldStorageDefinition(); + if (1 != $storage->getCardinality()) { + $is_list = TRUE; + } + } + else { + $is_list = $field_definition->isList(); + } + + return $is_list; + } + }