Tarantool 1.6 - let's get started

Not so long ago, an article about NoSQL base was published on Habré - "Tarantool 1.6 in the first person . " I am sure that this database is well known in its circles and is already gaining popularity. I am also sure that there are those beginners who haven’t gotten their hands on who would like to try Tarantool in action. It is for those who wish that I will give some simple examples to help you get started with this interesting product. As the name of the article implies, we are talking about the Tarantool 1.6 version.

Install


The project website details installation options for different systems. For Ubuntu, it looks like this:

wget http://tarantool.org/dist/public.key
sudo apt-key add ./public.key
release=`lsb_release -c -s`
cat > /etc/apt/sources.list.d/tarantool.list <<- EOF
deb http://tarantool.org/dist/master/ubuntu/ $release main
deb-src http://tarantool.org/dist/master/ubuntu/ $release main
EOF
sudo apt-get update
sudo apt-get install tarantool

Hello world!


Tarantool uses Lua as its built-in language (Lua 5.1 based on on LuaJIT 2.0). The lua language is not complicated, you can quickly learn its basics here or on Habr in the publication “Lua in 15 minutes” . You can use Tarantool as a Lua interpreter.

$ /usr/bin/tarantool
/usr/bin/tarantool: version 1.6.4-509-ga4af00e
type 'help' for interactive help
tarantool> 2 + 3
---
- 5
...
tarantool> print ('Ola lua!')
Ola lua!
---
...

You can also write your own logic using scripts in Lua. We will write the initial init.lua to launch Tarantool and output 'Hello world'.

One of the main tarantool libraries is box . Using box.cfg (in lua {...} is the table), we will create the launch configuration:

box.cfg {
    listen = 3311,
    logger = 'tarantool.log',
} 

Tarantool will be launched on port 3311 and will store logs in tarantool.log:

Create hello () function
local function hello()
    print ('Hello world!)
end
hello()

We start and see:

$ tarantool init.lua 
Hello world!

Data base


In tarantool, tuples are stored in spaces - a kind of analogue of a table.

Create a test space and a primary (primary) index in it (you can also build a secondary one for all fields of the record) using the tree to store the indices:

s = box.schema.space.create('test')
p = s:create_index('primary', {type = 'tree', parts = {1, 'NUM'}})

Fill test with records of the form {key, number}:

for i = 1, 10 do
    s:insert({i, i})
end 

In this case, the s object is a reference to the box.space.test object. Accordingly, it was possible to write:

box.space.test:insert({i, i})

By the way, you may encounter such an error when you restart tarantool:

$ tarantool init.lua 
Hello world!
main/101/init.lua F> Space 'test' already exists

Tarantool stores all its data in RAM. To preserve them, Tarantool takes snapshots and binary logs (xlog). The error occurs due to the fact that at startup Tarantool downloads data from the last use using the .snap files (snapshots) and .xlog (by default in the working directory). Accordingly, your test space is already present in the database. You can delete .snap and .xlog every time you start it, or add a check for the existence of space.

s =  box.space.test
if not s then
    s = box.schema.space.create('test')
    p = s:create_index('primary', {type = 'tree', parts = {1, 'NUM'}})
    for i = 1, 10 do
        s:insert({i, i})
    end
end

It would be very nice to check if our data has been saved, our configuration is running Tarantool. For this, a console for the administrator is provided. In general, in lua, the implementation of connecting various modules, built-in packages, and other files with code occurs through the require mechanism.

local console = require('console')
console.listen(127.0.0.1:3312)

After starting Tarantool, you can connect to the admin console on port 3312 using the nc / telnet and rlwrap utilities (for convenience). By connecting, you can directly work with Tarantool. Let's look, for example, the data of our test space:

$ rlwrap nc 0 3312
Tarantool 1.6.4-509-ga4af00e (Lua console)                     
type 'help' for interactive help                               
box.space.test:select()
---
- - [1, 1]
  - [2, 2]
  - [3, 3]
  - [4, 4]
  - [5, 5]
  - [6, 6]
  - [7, 7]
  - [8, 8]
  - [9, 9]
  - [10, 10]
...
box.space.test:get(6)
---
- [6, 6]
...

Let's see the configuration parameters of our Tarantool:

box.cfg
box.cfg
---
- snapshot_count: 6
  too_long_threshold: 0.5
  slab_alloc_factor: 2
  slab_alloc_maximal: 1048576
  background: false
  logger: tarantool.log
  slab_alloc_arena: 1
  sophia:
    page_size: 131072
    threads: 5
    node_size: 134217728
    memory_limit: 0
  listen: '3311'
  logger_nonblock: true
  snap_dir: .
  coredump: false
  sophia_dir: .
  wal_mode: write
  slab_alloc_minimal: 64
  panic_on_snap_error: true
  panic_on_wal_error: true
  rows_per_wal: 500000
  wal_dir: .
  log_level: 5
  readahead: 16320
  snapshot_period: 0
  wal_dir_rescan_delay: 0.1
...


So, having created space, we will perform the following task: in records with a key> 5, increase the value of the stored number by 10. We will
use the box.index library for the required selection .

for k,v in box.space.test.index.primary:pairs(5, {iterator = box.index.GT}) do
   s:update(v[1], {{'=', 2, v[2] + 10}})
end

box.space.index.primary - means working with the test space and its primary index.
pairs () - an iteration function that returns an iterator (variable k in the loop) and a table of values ​​(consists of a set of records v), takes the input value of the key (5) - start iteration and type of iterator.
iterator = box.index.GT - the GT iterator (greater) returns records with keys greater than the specified one.
update () - update the record in the database, takes the value of the record key (v [1]),
{'=', 2, v [2] + 10} - indicates the update ('=') of the second value to v [2] + 10.

Let's see, using the admin console, the values ​​of our space:

box.space.test:select()
---
- - [1, 1]
  - [2, 2]
  - [3, 3]
  - [4, 4]
  - [5, 5]
  - [6, 16]
  - [7, 17]
  - [8, 18]
  - [9, 19]
  - [10, 20]
...

The general code for our init.lua script:
-- Пример init cкрипта для tarantool
-- Подключение всех необходимых в скрипте модулей
-- удобно описывать в начале
local console = require('console')
-- Стартуем админскую консоль
console.listen('127.0.0.1:3312')
-- Конфигурация tarantool
box.cfg {
    listen = 3311,
    logger = 'tarantool.log',
}
local function hello()
    print ('Hello world!')
end
-- Запуск функции hello
hello()
-- Создаем и заполняем тестовый space, если он отсутствует
s =  box.space.test
if not s then
    s = box.schema.space.create('test')
    -- Первичный индекс
    p = s:create_index('primary', {type = 'tree', parts = {1, 'NUM'}})
    for i = 1, 10 do
        s:insert({i, i})
    end
end
-- Увеличим хранящиеся значения во всех записях, где первичный ключ больше 5
for k,v in box.space.test.index.primary:pairs(5, {iterator = box.index.GT}) do
   s:update(v[1], {{'=', 2, v[2] + 10}})
end


Of course, in order to fully master Tarantool, to know its subtleties, you need to read the documentation on the project website. Indeed, in addition to everything, Tarantool is not only a database, but also a lua application server. For example, there is an http server and queues . But the first step has been taken - you wrote your little script for Tarantool.

You can also read about Tarantool (in the examples there are older versions of the project) in other articles on Habr:
“We study Tarantool + Lua” ,
“Unique features of Tarantool” .

You can also try Tarantool at try.tarantool.org without any installation .

Also popular now: