Code Monkey home page Code Monkey logo

bitrix-sphinx's Introduction

Olegpro\BitrixSphinx

Build Status Latest Stable Version Total Downloads License

Пакет добавляет в 1С-Битрикс возможность работать с индексами sphinx, через ORM D7, как с привычными сущностями (например \Bitrix\Iblock\ElementTable или \Bitrix\Catalog\PriceTable)

Настройка

Создаём класс ORM-сущность:

<?php

use Bitrix\Main;
use Bitrix\Main\Localization\Loc;
use Olegpro\BitrixSphinx\Entity\SphinxDataManager;
use Olegpro\BitrixSphinx\Entity\SphinxQuery;

Loc::loadMessages(__FILE__);

class SampleTable extends SphinxDataManager
{

    /**
     * Returns index sphinx name for entity.
     *
     * @return string
     */
    public static function getTableName()
    {
        return 'sample_index';
    }

    /**
     * Returns sphinx-connection name for entity
     *
     * @return string
     */
    public static function getConnectionName()
    {
        return 'sphinx';
    }

    /**
     * Creates and returns the Query object for the entity
     *
     * @return SphinxQuery
     */
    public static function query()
    {
        return new SphinxQuery(static::getEntity());
    }

    /**
     * Returns entity map definition.
     *
     * @return array
     */
    public static function getMap()
    {
        return [
            new Main\Entity\IntegerField('id', [
                'primary' => true,
            ]),
            new Main\Entity\StringField('name'),
            new Main\Entity\BooleanField('available', [
                'values' => [0, 1],
            ])
        ];

    }

}

Описываем новое подключение в файле /bitrix/.settings.php в секцию connections:

'connections' =>
    array(
        'value' =>
            array(
                'default' =>
                        array(
                            // ...
                        )
                    ),
                'sphinx' =>
                    array(
                        'className' => '\\Olegpro\\BitrixSphinx\\DB\\SphinxConnection',
                        'host' => '127.0.0.1:9306',
                        'database' => '',
                        'login' => '',
                        'password' => '',
                        'options' => 1,
                    ),
            ),
        'readonly' => true,
    ),

Использование

<?php

use Bitrix\Main\Application;
use Bitrix\Main\Entity\ExpressionFieldd;

require($_SERVER['DOCUMENT_ROOT'] . '/bitrix/header.php');

Application::getConnection(SampleTable::getConnectionName())->startTracker(true);

$iterator = SampleTable::getList([
    'select' => [
        '*',
        new ExpressionField('weight', 'WEIGHT()', 'id'),
    ],
    'match' => 'книга',
    'filter' => [
        '=available' => 1,
    ],
    'limit' => 10,
    'order' => [
        'weight' => 'DESC',
    ],
    'option' => [
        'max_matches' => 50000,
    ],
]);

echo '<pre>';print_r($iterator->getTrackerQuery()->getSql());echo '</pre>';

echo '<pre>';print_r($iterator->fetchAll());echo '</pre>';

С постраничной навигацией

<?php

use Bitrix\Main\Application;
use Bitrix\Main\Entity\ExpressionFieldd;
use Bitrix\Main\UI\PageNavigation;

require($_SERVER['DOCUMENT_ROOT'] . '/bitrix/header.php');

Application::getConnection(SampleTable::getConnectionName())->startTracker(true);

$nav = new PageNavigation('s');

$nav->allowAllRecords(false)
    ->setPageSize(10)
    ->initFromUri();

$iterator = SampleTable::getList([
    'select' => [
        '*',
        new ExpressionField('weight', 'WEIGHT()', 'id'),
    ],
    'match' => 'книга',
    'filter' => [
        '=available' => 1,
    ],
    'count_total' => true,
    'offset' => $nav->getOffset(),
    'limit' => $nav->getLimit(),
    'order' => [
        'weight' => 'DESC',
    ],
    'option' => [
        'max_matches' => 50000,
    ],
]);

$nav->setRecordCount($iterator->getCount());

echo '<pre>';print_r($iterator->getTrackerQuery()->getSql());echo '</pre>';

echo '<pre>';print_r($iterator->fetchAll());echo '</pre>';


$APPLICATION->IncludeComponent(
    "bitrix:main.pagenavigation",
    "",
    array(
        "NAV_OBJECT" => $nav,
        "SEF_MODE" => "N",
    ),
    false
);

Использование только с master-подключением

Можно установить глобально для всего сайта, добавив в /bitrix/.settings.php

'olegpro_bitrix_sphinx' => 
    array (
        'value' => 
            array (
              'use_connection_master_only' => true,
            ),
    'readonly' => false,
),

Можно конкретно для каждого запроса передав use_connection_master_only = true:

$iterator = SampleTable::getList([
    'select' => [
        '*',
        new ExpressionField('weight', 'WEIGHT()', 'id'),
    ],
    'match' => 'книга',
    'filter' => [
        '=available' => 1,
    ],
    'limit' => 10,
    'order' => [
        'weight' => 'DESC',
    ],
    'option' => [
        'max_matches' => 50000,
    ],
    'use_connection_master_only' => true,
]);

Установка пакета

Добавить библиотеку в Composer:

composer require olegpro/bitrix-sphinx

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.