PHP code example of b0rner / yii2-solr

1. Go to this page and download the library: Download b0rner/yii2-solr library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

b0rner / yii2-solr example snippets


        'solr' => [
            'class' => 'b0rner\solr\Connection',
            'options' => [
                'endpoint' => [
                    'solr1' => [
                        'host' => 'solr',
                        'port' => '8983',
                        'path' => '/',
                        'collection' => 'my_collection'
                    ]
                ]
            ]
        ],



use b0rner\solr\Query;

$query = new Query;
$query->select('text, title, tags');
$query->q('foo OR bar')->offset(101);
$query->orderBy(['date' => 'desc']);
$query->where([
	'tag' => ['nature'],
	'author' => ['John Doe']
	], 'and');
$query->limit(10);

$result = $query->all();


$connection = new \b0rner\solr\Connection([
	'options' => [
		'endpoint' => [
			'solr1' => [
				'host' => 'solr',
				'port' => '8983',
				'path' => '/',
				'collection' => 'news'
			]
		]
	]
]);

$results = $connection->createCommand('foo AND bar')->queryAll();

foreach ($results as $result) {
	var_dump($result->title);
}




namespace app\models;

use b0rner\solr\ActiveRecord;

class News extends ActiveRecord
{
	// ...
}


public function attributes() {
	return ['title', 'text', 'tags', 'date', 'author']
}

    /**
     * This method defines the attribute that uniquely identifies a record.
     * This method has to be overwritten in the child class.
     * It has to be set corresponding to the SOLR configuration parameter <uniqueKey>
     *
     * @return array array of primary key attributes. Only the first element of the array will be used.
     * @throws \yii\base\InvalidConfigException if not overridden in a child class.
     */
    public static function primaryKey()
    {
        return ['id'];
    }



// giving a string assumes that a uniqueKey is provided. It will search for that id, not more.
$news = News::findOne('d4cfb176f7f9d3f7bf3523ec9832f812');

// giving an associative array will search like `fieldname:value`, multiple key-value pairs will be combined with AND
$news = News::findAll(['title' => 'foo', 'author' => 'John Doe']);

// giving an indexed array assumes, that multiple uniqueKeys are provided. They will be searched with OR
$news = News::findAll(['123', '456', '789']);


// searching just for a single term and just return one document
$result = News::find()
    ->q('berlin')
    ->one();

// search for "berlin" but add a filter query for the author.
$result = News::find()
    ->q('berlin')
    ->where(['author' => 'John Doe'])
    ->one();

// search for "berlin" and find news whether John Doe OR Jane Doe are author.
$result = News::find()
    ->q('berlin')
    ->where(['author' => ['John Doe', 'Jane Doe']])
    ->one();

// same, but return 5 documents instead of just one.
$result = News::find()
    ->q('berlin')
    ->where(['author' => ['John Doe', 'Jane Doe']])
    ->limit(5)
    ->all();

// this does exactly the same but just uses SOLR wording
$result = News::find()
    ->q('berlin')
    ->fq(['author' => ['John Doe', 'Jane Doe']])
    ->rows(5)
    ->all();

// skip the first 20 documents
$result = News::find()
    ->q('berlin')
    ->where(['author' => ['John Doe', 'Jane Doe']])
    ->limit(5)
    ->offset(20)
    ->all();

// order by date field in ascending order.
$result = News::find()
    ->q('berlin')
    ->where(['author' => ['John Doe', 'Jane Doe']])
    ->limit(5)
    ->offset(20)
    ->orderBy('date, desc')
    ->all();

// same - notice the array as orderBy parameter
$result = News::find()
    ->q('berlin')
    ->where(['author' => ['John Doe', 'Jane Doe']])
    ->limit(5)
    ->offset(20)
    ->orderBy(['date' => 'desc'])
    ->all();


// deleting one specific document
$db = News::getDb()->createCommand();
$db->delete('id', 'af90a227-e677-4899-8362-ac7443969329');

// deleting ALL (!) documents authored by John Doe
$db = News::getDb()->createCommand();
$db->delete('author', 'John Doe');

// Doing the same thing just with the `solr` component:
$result = \Yii::$app->solr->createCommand()->delete('author', 'John Doe');


$news = News::findOne('8e100f8c-6ff1-4312-a84f-2f07a8eb7364');
$news->delete();


// Because no uniqueKey is given, a new document will be added, with a SOLR generated value
$news = new News;
$news->title = "foo";
$news->text = "my text";
$news->author = "Jane Doe";
$result = $news->insert();

var_dump($result);

// Assuming that the given `id` property is unkown to the SOLR index, this creates a new document
// as well
$news = new News;
$news->title = "foo";
$news->text = "my text";
$news->author = "Jane Doe";
$news->id = "12345678";
$result = $news->insert();

var_dump($result);

// And now we are updating the formerly inserted document, because the `id`
// already exists in the index.
// Note that we are using `insert()` for updating.
$news = new News;
$news->title = "foo bar";
$news->text = "my new text";
$news->id = "12345678";
$result = $news->insert();


$news = News::findOne('4db5ef81-8aa9-4f2e-8553-1ee32a375bfb');
$news->prio = 5;
$news->save();


public function afterFind()
{
    $this->date = \Yii::$app->formatter->format($this->date, 'date');
}


$result = News::find()
    ->q('berlin')
    ->hl()
    ->hlFl('text, title')
    ->hlFragsize(100)
    ->hlSnippets(2)


[
    $fieldname => $highlighted_snippet,
    $another_fieldname => $another_snippet
]

if (!empty($this->getHighlights())) {
    if (array_key_exists('text', $this->getHighlights())) {
        $this->text = $this->getHighlights()['text'][0];
    }

    if (array_key_exists('title', $this->getHighlights())) {
        $this->title = $this->getHighlights()['title'][0];
    }
}


$query = $News->find()
              ->edismax()
              ->q('berlin')


$query = $News->find()
              ->edismax()
              ->q('berlin')
              ->qf('text title^5')

use b0rner\solr\ActiveDataProvider;

// ...

    $query = News::find()
        ->q('berlin')
        ->where(['author' => ['John Doe', 'Jane Doe']]);

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
        'pagination' => ['pageSize' => 10]
    ]);

    return $this->render('news_view', [
        'dataProvider' => $dataProvider,
    ]);


$news = new News();

// group by field. This example groups by field 'ressorts', that contains a ressort-number

$resultA = $news->find()
            ->edismax()
            ->q('*:*') 
            ->limit(100) // max. number of results to group on. Has no effect on groupSetFormat('grouped')
            ->fq(...)  // filter documents before grouping the result
            ->fl(...) // define the fields that should part of the grouped documents
            ->rows(2)  // define the numer of groups, not the numer of documents per group
            ->group()  // enable grouping
            ->groupSetLimit(5) // set the numer of documents per group, if format=grouped. Has no effect on groupSetFormat('simple'). 
            ->groupAddField('ressort') // set the field for grouping, use comma to seperate multiple fields
            ->groupSetCachepercentage(0) // set solrs group.cache.percent. 0> will not result in better performance in some cases
            ->grouping();  // returning the group result set. Don't use ->one() or ->all()
                           // because solr does not return a result set by default


// $resultA contains the solarium grouping component, including the result of 2 groups with 5 documents per group
###

// group by different queries

$resultB = $news->find()
            ->edismax()
            ->q('*:*') 
            ->fq(...)  // filter documents before grouping the result
            ->fl(...) // define the fields that should part of the grouped documents
            ->limit(150)
            ->rows(2)  // will be ignored, `groupAddQuery` defindes the number of groups
            ->group()  // enable grouping
            ->groupSetLimit(20) // set the numer of documents per group, if format = grouped
            ->groupSetOffset(4) // getting documents 5-25 for each group
            ->groupNumberOfGroup(true) // returning the number og groups in the result set, Solarium default = false
            ->groupAddQuery('berlin') // adding a guery to group on
            ->groupAddQuery('paris') // adding a guery to group on
            ->groupSetSort('last_modified desc') // order documents within a single group (by last_modified)
            ->groupSetFormat('simple') // 
            ->grouping();  // returning the group result set. Don't use ->one() or ->all()
                           // because solr does not return a result set by default

// $resultB contains the solarium grouping component, including 2 groups ('berlin' and 'paris') with 150 docuemnts per group