QueryBuilderTest.php 2.41 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
<?php

namespace yiiunit\extensions\elasticsearch;

use yii\elasticsearch\Query;
use yii\elasticsearch\QueryBuilder;

/**
 * @group elasticsearch
 */
class QueryBuilderTest extends ElasticSearchTestCase
{

14 15 16 17
    public function setUp()
    {
        parent::setUp();
        $command = $this->getConnection()->createCommand();
18

19 20 21 22 23
        // delete index
        if ($command->indexExists('yiitest')) {
            $command->deleteIndex('yiitest');
        }
    }
24

25 26 27 28 29 30 31
    private function prepareDbData()
    {
        $command = $this->getConnection()->createCommand();
        $command->insert('yiitest', 'article', ['title' => 'I love yii!'], 1);
        $command->insert('yiitest', 'article', ['title' => 'Symfony2 is another framework'], 2);
        $command->insert('yiitest', 'article', ['title' => 'Yii2 out now!'], 3);
        $command->insert('yiitest', 'article', ['title' => 'yii test'], 4);
32

33 34
        $command->flushIndex('yiitest');
    }
35

36 37 38 39 40 41 42 43 44 45 46 47
    public function testQueryBuilderRespectsQuery()
    {
        $queryParts = ['field' => ['title' => 'yii']];
        $queryBuilder = new QueryBuilder($this->getConnection());
        $query = new Query();
        $query->query = $queryParts;
        $build = $queryBuilder->build($query);
        $this->assertTrue(array_key_exists('queryParts', $build));
        $this->assertTrue(array_key_exists('query', $build['queryParts']));
        $this->assertFalse(array_key_exists('match_all', $build['queryParts']), 'Match all should not be set');
        $this->assertSame($queryParts, $build['queryParts']['query']);
    }
48

49 50 51
    public function testYiiCanBeFoundByQuery()
    {
        $this->prepareDbData();
52
        $queryParts = ['term' => ['title' => 'yii']];
53 54 55 56 57 58
        $query = new Query();
        $query->from('yiitest', 'article');
        $query->query = $queryParts;
        $result = $query->search($this->getConnection());
        $this->assertEquals(2, $result['hits']['total']);
    }
59

60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
    public function testFuzzySearch()
    {
        $this->prepareDbData();
        $queryParts = [
            "fuzzy_like_this" => [
                "fields" => ["title"],
                "like_text" => "Similar to YII",
                "max_query_terms" => 4
            ]
        ];
        $query = new Query();
        $query->from('yiitest', 'article');
        $query->query = $queryParts;
        $result = $query->search($this->getConnection());
        $this->assertEquals(3, $result['hits']['total']);
    }
76
}