public function AddHierarchyTest::testPreprocessIndexItemsTaxonomy in Search API 8
Tests taxonomy-based hierarchy indexing.
@covers ::preprocessIndexItems
File
- tests/
src/ Kernel/ Processor/ AddHierarchyTest.php, line 181
Class
- AddHierarchyTest
- Tests the "Hierarchy" processor.
Namespace
Drupal\Tests\search_api\Kernel\ProcessorCode
public function testPreprocessIndexItemsTaxonomy() {
// Add hierarchical terms to 3 nodes.
foreach ([
'vegetable.turnip',
'vegetable',
'fruit.pear',
] as $i => $term) {
$this->nodes[$i] = $this
->createNode([
'type' => 'page',
'term_field' => [
'target_id' => $this->terms[$term]
->id(),
],
]);
}
$this->index
->reindex();
$this
->indexItems();
// By default, hierarchy is not indexed, so a search for 'vegetable' should
// only return node 2.
$query = new Query($this->index);
$query
->addCondition('term_field', $this->terms['vegetable']
->id());
$result = $query
->execute();
$expected = [
'node' => [
1,
],
];
$this
->assertResults($result, $expected);
// Enable hierarchical indexing.
$processor = $this->index
->getProcessor('hierarchy');
$processor
->setConfiguration([
'fields' => [
'term_field' => 'taxonomy_term-parent',
],
]);
$this->index
->save();
$this
->indexItems();
// Query for "vegetable" should return 2 items:
// Node 1 is "vegetable.turnip" and node 2 is just "vegetable".
$query = new Query($this->index);
$query
->addCondition('term_field', $this->terms['vegetable']
->id());
$result = $query
->execute();
$expected = [
'node' => [
0,
1,
],
];
$this
->assertResults($result, $expected);
// A search for just turnips should return node 1 only.
$query = new Query($this->index);
$query
->addCondition('term_field', $this->terms['vegetable.turnip']
->id());
$result = $query
->execute();
$expected = [
'node' => [
0,
],
];
$this
->assertResults($result, $expected);
// Also add a term with multiple parents.
$this->terms['avocado'] = $this
->createTerm($this->vocabulary, [
'name' => 'Avocado',
'parent' => [
$this->terms['fruit']
->id(),
$this->terms['vegetable']
->id(),
],
]);
$this->nodes[3] = $this
->createNode([
'type' => 'page',
'term_field' => [
'target_id' => $this->terms['avocado']
->id(),
],
]);
$this->index
->reindex();
$this
->indexItems();
// Searching for 'fruit' or 'vegetable' should return this new node.
$query = new Query($this->index);
$query
->addCondition('term_field', $this->terms['fruit']
->id());
$result = $query
->execute();
$expected = [
'node' => [
2,
3,
],
];
$this
->assertResults($result, $expected);
$query = new Query($this->index);
$query
->addCondition('term_field', $this->terms['vegetable']
->id());
$result = $query
->execute();
$expected = [
'node' => [
0,
1,
3,
],
];
$this
->assertResults($result, $expected);
}