Coder Social home page Coder Social logo

maxoodf / pg_mystem Goto Github PK

View Code? Open in Web Editor NEW
6.0 2.0 1.0 29 KB

pg_mystem - расширение PostgreSQL для лемматизации (морфологической нормализации) текстов на русском языке. PostgreSQL extension for Yandex Mystem

License: MIT License

Makefile 2.87% C++ 97.13%
postgresql stemmer yandex-mystem nlp nlp-machine-learning nlp-parsing nlp-library russian-specific

pg_mystem's Introduction

pg_mystem - расширение PostgreSQL для поддержки Yandex Mystem

pg_mystem - расширение PostgreSQL для Yandex mystem (стеммер или лемматизатор или морфологический нормализатор - точный термин, как я понимаю, в русском языке не определен). Основная функция данного расширения заключается в объединении лучшего, на мой взгляд, стеммера русского языка mystem и мощнейшей СУБД PostgreSQL.

Установка Yandex Mystem

Необходимо загрузить исполнимый файл mystem, соответствующий вашей архитектуре, и скопировать его в share директорию PostgreSQL.
Пример:

$ wget http://download.cdn.yandex.net/mystem/mystem-3.0-linux3.1-64bit.tar.gz
$ tar xfz mystem-3.0-linux3.1-64bit.tar.gz
$ sudo cp ./mystem `pg_config --sharedir`

Установка pg_mystem

$ git clone https://github.com/maxoodf/pg_mystem.git
$ cd ./pg_mystem
$ git submodule init
$ git submodule update
$ make
$ sudo make install

Настройка pg_mystem

Настройки pg_mystem могут быть изменены. Для этого необходимо отредактировать соответствующие переменные, определенные в Makefile -

  1. DOC_LEN_MAX - максимальный размер документа (в байтах). Если вы работаете с короткими документами (строками), установите значение DOC_LEN_MAX, например, в 1000. Для работы с большими документами (строками), установите DOC_LEN_MAX в необходимое значение.
  2. MYSTEM_PROCS - количество запущенных mystem процессов. Рекомендованное значение - один mystem процесс на 9 KB/sec обрабатываемого текста. Например, если требуется обеспечить производительность лемматизации в 50KB текста в секунду, используйте 6 процессов mystem (приведенные значения являются крайне относительными и зависят от производительности вашей системы).

После изменения настроек необходимо переустановить pg_mystem, как описано ранее.

Регистрация расширения pg_mystem

  1. Измените ваш конфигурационный файл postgresql.conf.
  • необходимо добавить следующую строку - shared_preload_libraries = 'pg_mystem'
  • возможно, вам потребуется увелисить количество max_worker_processes до MYSTEM_PROCS + 1, как минимум. Например, строка конфигурационного файла - max_worker_processes = 24
  1. Перезапустите PostgreSQL
$ sudo service postgresql restart
  1. Выполните следующий запрос для регистрации расширения в PostgreSQL -
$ sudo -u postgres psql
\connect YOUR_DB
CREATE EXTENSION pg_mystem;
\q

Теперь вы можете использовать mystem из PostgreSQL.

SELECT mystem_convert('Ехал грека через реку, сунул грека руку в реку');
                mystem_convert                 
-----------------------------------------------
 ехать грек через река, сунуть грек рука в река +

(1 row)

pg_mystem - PostgreSQL extension for Yandex Mystem

pg_mystem is an implementation of the PostgreSQL extension for Yandex mystem (morphology analyzer/stemmer for Russian language). What is the extension function? You can use the power of the mystem inside of a PostgreSQL database.

Yandex mystem Installation

Download binary mystem file and install it to the PostgreSQL share directory.
Example:

$ wget http://download.cdn.yandex.net/mystem/mystem-3.0-linux3.1-64bit.tar.gz
$ tar xfz mystem-3.0-linux3.1-64bit.tar.gz
$ sudo cp ./mystem `pg_config --sharedir`

pg_mystem Installation

$ git clone https://github.com/maxoodf/pg_mystem.git
$ cd ./pg_mystem
$ git submodule init
$ git submodule update
$ make
$ sudo make install

pg_mystem Configuration

You may wish to change pg_mystem default settings. All you need is to change Makefile defined parameters -

  1. DOC_LEN_MAX - maximum document (string) length. If you work with a short lines, redefine DOC_LEN_MAX to 1000 chars or so. If you work with a large documents, redefine DOC_LEN_MAX to 100000 characters etc.
  2. MYSTEM_PROCS - how many mystem processes to run. I use the following value in my projects - one mystem process throughput is about 9 KB/sec (depends on hardware). So if I need to process, say 50 KB of text in a second I use 6 mystem processes.

You will need to reinstall pg_mystem in case any of these parameters is changed.

pg_mystem Extension registration

  1. Edit your postgresql.conf.
    Add the following line - shared_preload_libraries = 'pg_mystem'
    Also you may need to change max_worker_processes to MYSTEM_PROCS + 1 at least.
    Example - max_worker_processes = 24
  2. Restart PostgreSQL
$ sudo service postgresql restart
  1. Execute the following query inside your database. Example -
$ sudo -u postgres psql
\connect YOUR_DB
CREATE EXTENSION pg_mystem;
\q

That's all. Now you can use mystem from PostgreSQL queries.

SELECT mystem_convert('Ехал грека через реку, сунул грека руку в реку');
                mystem_convert                 
-----------------------------------------------
 ехать грек через река, сунуть грек рука в река +

(1 row)

pg_mystem's People

Contributors

maxoodf avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Forkers

dead-beef

pg_mystem's Issues

Build errors

Hi. I have errors? when i try build this. Postgres version 10.7

pg_mystem.cpp:502:113: error: too few arguments to function ‘int WaitLatch(volatile Latch*, int, long int, uint32)’
 itLatch(MyLatch, WL_LATCH_SET | WL_TIMEOUT | WL_POSTMASTER_DEATH, currTimeout);
                                                                              ^
In file included from pg_mystem.cpp:22:0:
/usr/include/postgresql/10/server/storage/latch.h:174:12: note: declared here
 extern int WaitLatch(volatile Latch *latch, int wakeEvents, long timeout,
            ^~~~~~~~~
pg_mystem.cpp: In function ‘void mainMystemProc(Datum)’:
pg_mystem.cpp:532:16: error: ‘BackgroundWorker {aka struct BackgroundWorker}’ has no member named ‘bgw_main’; did you mean ‘bgw_name’?
         worker.bgw_main = createMystemChilds;
                ^~~~~~~~
                bgw_name
pg_mystem.cpp:543:95: error: too few arguments to function ‘int WaitLatch(volatile Latch*, int, long int, uint32)’
 c = WaitLatch(MyLatch, WL_LATCH_SET | WL_TIMEOUT | WL_POSTMASTER_DEATH, 1000L);
                                                                              ^
In file included from pg_mystem.cpp:22:0:
/usr/include/postgresql/10/server/storage/latch.h:174:12: note: declared here
 extern int WaitLatch(volatile Latch *latch, int wakeEvents, long timeout,
            ^~~~~~~~~
pg_mystem.cpp: In function ‘void _PG_init()’:
pg_mystem.cpp:563:16: error: ‘BackgroundWorker {aka struct BackgroundWorker}’ has no member named ‘bgw_main’; did you mean ‘bgw_name’?
         worker.bgw_main = mainMystemProc;
                ^~~~~~~~
                bgw_name
<встроенное>: recipe for target 'pg_mystem.o' failed
make: *** [pg_mystem.o] Error 1```

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.