GROONGA(1)

NAME
groonga - groonga documentation

•   news

CHARACTERISTICS OF GROONGA

  Groonga overview

Groonga is a fast and accurate full text search engine based on inverted index. One of the characteristics of groonga is that a newly registered document instantly appears in search results. Also, groonga allows updates without read locks. These characteristics result in superior performance on real-time applications.

Groonga is also a column-oriented database management system (DBMS). Compared with well-known row-oriented systems, such as MySQL and PostgreSQL, column-oriented systems are more suited for aggregate queries. Due to this advantage, groonga can cover weakness of row-oriented systems.

The basic functions of groonga are provided in a C library. Also, libraries for using groonga in other languages, such as Ruby, are provided by related projects. In addition, groonga-based storage engines are provided for MySQL and PostgreSQL. These libraries and storage engines allow any application to use groonga. See usage examples.

  Full text search and Instant update

In widely used DBMSs, updates are immediately processed, for example, a newly registered record appears in the result of the next query. In contrast, some full text search engines do not support instant updates, because it is difficult to dynamically update inverted indexes, the underlying data structure.

Groonga also uses inverted indexes but supports instant updates. In addition, groonga allows you to search documents even when updating the document collection. Due to these superior characteristics, groonga is very flexible as a full text search engine. Also, groonga always shows good performance because it divides a large task, inverted index merging, into smaller tasks.

  Column store and aggregate query

People can collect more than enough data in the Internet era. However, it is difficult to extract informative knowledge from a large database, and such a task requires a many-sided analysis through trial and error. For example, search refinement by date, time and location may reveal hidden patterns. Aggregate queries are useful to perform this kind of tasks.

An aggregate query groups search results by specified column values and then counts the number of records in each group. For example, an aggregate query in which a location column is specified counts the number of records per location. Making a graph from the result of an aggregate query against a date column is an easy way to visualize changes over time. Also, a combination of refinement by location and an aggregate query against a date column allows visualization of changes over time in specific location. Thus refinement and aggregation are important to perform data mining.

A column-oriented architecture allows groonga to efficiently process aggregate queries because a column-oriented database, which stores records by column, allows an aggregate query to access only a specified column. On the other hand, an aggregate query on a row-oriented database, which stores records by row, has to access neighbor columns, even though those columns are not required.

  Inverted index and tokenizer

An inverted index is a traditional data structure used for large-scale full text search. A search engine based on inverted index extracts index terms from a document when it is added. Then in retrieval, a query is divided into index terms to find documents containing those index terms. In this way, index terms play an important role in full text search and thus the way of extracting index terms is a key to a better search engine.

A tokenizer is a module to extract index terms. A Japanese full text search engine commonly uses a word-based tokenizer (hereafter referred to as a word tokenizer) and/or a character-based n-gram tokenizer (hereafter referred to as an n-gram tokenizer). A word tokenizer-based search engine is superior in time, space and precision, which is the fraction of relevant documents in a search result. On the other hand, an n-gram tokenizer-based search engine is superior in recall, which is the fraction of retrieved documents in the perfect search result. The best choice depends on the application in practice.

Groonga supports both word and n-gram tokenizers. The simplest built-in tokenizer uses spaces as word delimiters. Built-in n-gram tokenizers (n = 1, 2, 3) are also available by default. In addition, a yet another built-in word tokenizer is available if MeCab, a part-of-speech and morphological analyzer, is embedded. Note that a tokenizer is pluggable and you can develop your own tokenizer, such as a tokenizer based on another part-of-speech tagger or a named-entity recognizer.

  Sharable storage and read lock-free

Multi-core processors are mainstream today and the number of cores per processor is increasing. In order to exploit multiple cores, executing multiple queries in parallel or dividing a query into sub-queries for parallel processing is becoming more important.

A database of groonga can be shared with multiple threads/processes. Also, multiple threads/processes can execute read queries in parallel even when another thread/process is executing an update query because groonga uses read lock-free data structures. This feature is suited to a real-time application that needs to update a database while executing read queries. In addition, groonga allows you to build flexible systems. For example, a database can receive read queries through the built-in HTTP server of groonga while accepting update queries through MySQL.

  Geo-location (latitude and longitude) search

Location services are getting more convenient because of mobile devices with GPS. For example, if you are going to have lunch or dinner at a nearby restaurant, a local search service for restaurants may be very useful, and for such services, fast geo-location search is becoming more important.

Groonga provides inverted index-based fast geo-location search, which supports a query to find points in a rectangle or circle. Groonga gives high priority to points near the center of an area. Also, groonga supports distance measurement and you can sort points by distance from any point.

  Groonga library

The basic functions of groonga are provided in a C library and any application can use groonga as a full text search engine or a column-oriented database. Also, libraries for languages other than C/C++, such as Ruby, are provided in related projects. See related projects for details.

  Groonga server

Groonga provides a built-in server command which supports HTTP, the memcached binary protocol and the groonga query transfer protocol (gqtp). Also, a groonga server supports query caching, which significantly reduces response time for repeated read queries. Using this command, groonga is available even on a server that does not allow you to install new libraries.

  Groonga storage engine

Groonga works not only as an independent column-oriented DBMS but also as storage engines of well-known DBMSs. For example, mroonga is a MySQL pluggable storage engine using groonga. By using mroonga, you can use groonga for column-oriented storage and full text search. A combination of a built-in storage engine, MyISAM or InnoDB, and a groonga-based full text search engine is also available. All the combinations have good and bad points and the best one depends on the application. See related projects for details.

INSTALL

This section describes how to install groonga on each environment. There are packages for major platforms. It's recommended that you use package instead of building groonga by yourself. But don't warry. There is a document about building groonga from source.

We distribute both 32-bit and 64-bit packages but we strongly recommend a 64-bit package for server. You should use a 32-bit package just only for tests or development. You will encounter an out of memory error with a 32-bit package even if you just process medium size data.

  Windows

This section describes how to install groonga on Windows. You can install groogna by extracting a zip package or running an installer.

We distribute both 32-bit and 64-bit packages but we strongly recommend a 64-bit package for server. You should use a 32-bit package just only for tests or development. You will encounter an out of memory error with a 32-bit package even if you just process medium size data.

  Installer

For 32-bit environment, download x86 executable binary from packages.groonga.org.

You can download such a binary by command line operation.

Start command prompt cmd.exe and download x86 executable binary by default browser:

> "c:\\Program Files\\Internet Explorer\\iexplore.exe" http://packages.groonga.org/windows/groonga/groonga-3.0.0-x86.exe

Then run it.

For 64-bit environment, download x64 executable binary from packages.groonga.org.

Start command prompt cmd.exe and download x64 executable binary by default browser:

> "c:\\Program Files\\Internet Explorer\\iexplore.exe" http://packages.groonga.org/windows/groonga/groonga-3.0.0-x64.exe

Then run it.

Use command prompt for /reference/executables/groonga installed in start menu.

  zip

For 32-bit environment, download x86 zip archive from packages.groonga.org.

You can download such a binary by command line operation.

Start command prompt cmd.exe and download x86 zip archive by default browser:

> "c:\\Program Files\\Internet Explorer\\iexplore.exe" http://packages.groonga.org/windows/groonga/groonga-3.0.0-x86.zip

Then extract it.

For 64-bit environment, download x64 zip archive from packages.groonga.org.

Start command prompt cmd.exe and download x64 zip archive by default browser:

> "c:\\Program Files\\Internet Explorer\\iexplore.exe" http://packages.groonga.org/windows/groonga/groonga-3.0.0-x64.zip

Then extract it.

/reference/executables/groonga is in bin folder.

  Build from source

First, you need to install required tools for building groonga on Windows. Here are required tools:

•   Microsoft Visual Studio 2010 Express

•   CMake

    Download zipped source from packages.groonga.org.

    You can download such a zipped source file by command line operation.

    Start Visual Studio Command Prompt (2010) installed by Microsoft Visual Studio 2010 Express and download it by default browser:

    > cd c:\Users\%USERNAME%\Downloads
    > "c:\\Program Files\\Internet Explorer\\iexplore.exe" http://packages.groonga.org/source/groonga/groonga-3.0.0.zip

    Then extract it.

    Move to the groonga's source folder:

    > cd c:\Users\%USERNAME%\Downloads\groonga-3.0.0

    Configure by cmake. The following commnad line is for 64-bit version. To build 32-bit version, use -G "Visual Studio 10" parameter instead:

    groonga-3.0.0> cmake . -G "Visual Studio 10 Win64" -DCMAKE_INSTALL_PREFIX=C:\groonga

    Build by Visual C++ 2010 Express:

    groonga-3.0.0> msbuild groonga.sln /p:Configuration=Release

    Install by Visual C++ 2010 Express:

    groonga-3.0.0> msbuild groonga.sln /p:Configuration=Release /t:Install

    If you installed Visual Studio 2010, use can use devenv instead.

    Build by Visual Studio 2010:

    groonga-3.0.0> devenv groonga.sln /Build Release

    Install by Visual Studio 2010:

    groonga-3.0.0> devenv groonga.sln /Build Release /Project Install

    After the above steps, /reference/executables/groonga is found in c:\groonga\bin\groonga.exe.

  Mac OS X

This section describes how to install groonga on Mac OS X. You can install groonga by MacPorts or Homebrew.

We distribute both 32-bit and 64-bit packages but we strongly recommend a 64-bit package for server. You should use a 32-bit package just only for tests or development. You will encounter an out of memory error with a 32-bit package even if you just process medium size data.

  MacPorts

Install:

% sudo port install groonga

  Homebrew

Install:

% brew install groonga

  Build from source

Install Xcode.

Download source:

% curl -O http://packages.groonga.org/source/groonga/groonga-3.0.0.tar.gz
% tar xvzf groonga-3.0.0.tar.gz
% cd groonga-3.0.0

Configure (see source-configure about configure options):

% ./configure

Build:

% make -j$(/usr/sbin/sysctl -n hw.ncpu)

Install:

% sudo make intall

  Debian GNU/Linux

This section describes how to install groonga related deb packages on Debian GNU/Linux. You can install them by apt.

We distribute both 32-bit and 64-bit packages but we strongly recommend a 64-bit package for server. You should use a 32-bit package just only for tests or development. You will encounter an out of memory error with a 32-bit package even if you just process medium size data.

Note
    The package 'groonga' is the mininum set of fulltext search engine. If you want to use groonga for server use, you can install additional preconfigured packages.

    There are three packages for server use.

•   groonga-server-http (simple HTTP protocol based server package)

•   groonga-httpd (nginx and HTTP protocol based server package)

•   groonga-server-gqtp (GQTP protocol based server package)

    See /server section about details.

  squeeze

Add the groonga apt repository.

/etc/apt/sources.list.d/groonga.list:

deb http://packages.groonga.org/debian/ squeeze main
deb-src http://packages.groonga.org/debian/ squeeze main

Install:

% sudo aptitude update
% sudo aptitude -V -D -y --allow-untrusted install groonga-keyring
% sudo aptitude update
% sudo aptitude -V -D -y install groonga

If you want to use MeCab as a tokenizer, install groonga-tokenizer-mecab package.

Install groonga-tokenizer-mecab package:

% sudo aptitude -V -D -y install groonga-tokenizer-mecab

There is a package that provides Munin plugins. If you want to monitor groonga status by Munin, install groonga-munin-plugins package.

Install groonga-munin-plugins package:

% sudo aptitude -V -D -y install groonga-munin-plugins

There is a package that provides MySQL compatible normalizer as groonga plugins. If you want to use that one, install groonga-normalizer-mysql package.

Install groonga-normalizer-mysql package:

% sudo aptitude -V -D -y install groonga-normalizer-mysql

  wheezy

Add the groonga apt repository.

/etc/apt/sources.list.d/groonga.list:

deb http://packages.groonga.org/debian/ wheezy main
deb-src http://packages.groonga.org/debian/ wheezy main

Install:

% sudo apt-get update
% sudo apt-get -y --allow-unauthenticated install groonga-keyring
% sudo apt-get update
% sudo apt-get -y install groonga

If you want to use MeCab as a tokenizer, install groonga-tokenizer-mecab package.

Install groonga-tokenizer-mecab package:

% sudo aptitude -V -D -y install groonga-tokenizer-mecab

There is a package that provides Munin plugins. If you want to monitor groonga status by Munin, install groonga-munin-plugins package.

Install groonga-munin-plugins package:

% sudo aptitude -V -D -y install groonga-munin-plugins

There is a package that provides MySQL compatible normalizer as groonga plugins. If you want to use that one, install groonga-normalizer-mysql package.

Install groonga-normalizer-mysql package:

% sudo aptitude -V -D -y install groonga-normalizer-mysql

  sid

Add the groonga apt repository.

/etc/apt/sources.list.d/groonga.list:

deb http://packages.groonga.org/debian/ unstable main
deb-src http://packages.groonga.org/debian/ unstable main

Install:

% sudo aptitude update
% sudo aptitude -V -D -y --allow-untrusted install groonga-keyring
% sudo aptitude update
% sudo aptitude -V -D -y install groonga

If you want to use MeCab as a tokenizer, install groonga-tokenizer-mecab package.

Install groonga-tokenizer-mecab package:

% sudo aptitude -V -D -y install groonga-tokenizer-mecab

There is a package that provides Munin plugins. If you want to monitor groonga status by Munin, install groonga-munin-plugins package.

Install groonga-munin-plugins package:

% sudo aptitude -V -D -y install groonga-munin-plugins

There is a package that provides MySQL compatible normalizer as groonga plugins. If you want to use that one, install groonga-normalizer-mysql package.

Install groonga-normalizer-mysql package:

% sudo aptitude -V -D -y install groonga-normalizer-mysql

  Build from source

Install required packages to build groonga:

% sudo aptitude -V -D -y install wget tar build-essential zlib1g-dev liblzo2-dev libmsgpack-dev libzmq-dev libevent-dev libmecab-dev

Download source:

% wget http://packages.groonga.org/source/groonga/groonga-3.0.0.tar.gz
% tar xvzf groonga-3.0.0.tar.gz
% cd groonga-3.0.0

Configure (see source-configure about configure options):

% ./configure

Build:

% make -j$(grep '^processor' /proc/cpuinfo | wc -l)

Install:

% sudo make intall

  Ubuntu

This section describes how to install groonga related deb packages on Ubuntu. You can install them by apt.

We distribute both 32-bit and 64-bit packages but we strongly recommend a 64-bit package for server. You should use a 32-bit package just only for tests or development. You will encounter an out of memory error with a 32-bit package even if you just process medium size data.

Note
    The package 'groonga' is the mininum set of fulltext search engine. If you want to use groonga for server use, you can install additional preconfigured packages.

    There are three packages for server use.

•   groonga-server-http (simple HTTP protocol based server package)

•   groonga-httpd (nginx and HTTP protocol based server package)

•   groonga-server-gqtp (GQTP protocol based server package)

    See /server section about details.

  10.04 LTS Lucid Lynx

Note
    Enable the universe repository to install groonga:

    % sudo cp /etc/apt/sources.list /etc/apt/sources.list.d/universe.list
    % sudo sed -i'' -e 's/main/universe/' /etc/apt/sources.list.d/universe.list

Add the groonga apt repository.

/etc/apt/sources.list.d/groonga.list:

deb http://packages.groonga.org/ubuntu/ lucid universe
deb-src http://packages.groonga.org/ubuntu/ lucid universe

Install:

% sudo apt-get update
% sudo apt-get -y --allow-unauthenticated install groonga-keyring
% sudo apt-get update
% sudo apt-get -y install groonga

If you want to use MeCab as a tokenizer, install groonga-tokenizer-mecab package.

Install groonga-tokenizer-mecab package:

% sudo apt-get -y install groonga-tokenizer-mecab

There is a package that provides Munin plugins. If you want to monitor groonga status by Munin, install groonga-munin-plugins package.

Install groonga-munin-plugins package:

% sudo apt-get -y install groonga-munin-plugins

There is a package that provides MySQL compatible normalizer as groonga plugins. If you want to use that one, install groonga-normalizer-mysql package.

Install groonga-normalizer-mysql package:

% sudo apt-get -y install groonga-normalizer-mysql

  11.10 Oneiric Ocelot

Note
    Enable the universe repository to install groonga:

    % sudo cp /etc/apt/sources.list /etc/apt/sources.list.d/universe.list
    % sudo sed -i'' -e 's/main/universe/' /etc/apt/sources.list.d/universe.list

Add the groonga apt repository.

/etc/apt/sources.list.d/groonga.list:

deb http://packages.groonga.org/ubuntu/ oneiric universe
deb-src http://packages.groonga.org/ubuntu/ oneiric universe

Install:

% sudo apt-get update
% sudo apt-get -y --allow-unauthenticated install groonga-keyring
% sudo apt-get update
% sudo apt-get -y install groonga

If you want to use MeCab as a tokenizer, install groonga-tokenizer-mecab package.

Install groonga-tokenizer-mecab package:

% sudo apt-get -y install groonga-tokenizer-mecab

There is a package that provides Munin plugins. If you want to monitor groonga status by Munin, install groonga-munin-plugins package.

Install groonga-munin-plugins package:

% sudo apt-get -y install groonga-munin-plugins

There is a package that provides MySQL compatible normalizer as groonga plugins. If you want to use that one, install groonga-normalizer-mysql package.

Install groonga-normalizer-mysql package:

% sudo apt-get -y install groonga-normalizer-mysql

  12.04 LTS Precise Pangolin

Note
    Enable the universe repository to install groonga:

    % sudo cp /etc/apt/sources.list /etc/apt/sources.list.d/universe.list
    % sudo sed -i'' -e 's/main/universe/' /etc/apt/sources.list.d/universe.list

Add the groonga apt repository.

/etc/apt/sources.list.d/groonga.list:

deb http://packages.groonga.org/ubuntu/ precise universe
deb-src http://packages.groonga.org/ubuntu/ precise universe

Install:

% sudo apt-get update
% sudo apt-get -y --allow-unauthenticated install groonga-keyring
% sudo apt-get update
% sudo apt-get -y install groonga

If you want to use MeCab as a tokenizer, install groonga-tokenizer-mecab package.

Install groonga-tokenizer-mecab package:

% sudo apt-get -y install groonga-tokenizer-mecab

There is a package that provides Munin plugins. If you want to monitor groonga status by Munin, install groonga-munin-plugins package.

Install groonga-munin-plugins package:

% sudo apt-get -y install groonga-munin-plugins

There is a package that provides MySQL compatible normalizer as groonga plugins. If you want to use that one, install groonga-normalizer-mysql package.

Install groonga-normalizer-mysql package:

% sudo apt-get -y install groonga-normalizer-mysql

  12.10 Quantal Quetzal

Note
    Enable the universe repository to install groonga:

    % sudo cp /etc/apt/sources.list /etc/apt/sources.list.d/universe.list
    % sudo sed -i'' -e 's/main/universe/' /etc/apt/sources.list.d/universe.list

Add the groonga apt repository.

/etc/apt/sources.list.d/groonga.list:

deb http://packages.groonga.org/ubuntu/ quantal universe
deb-src http://packages.groonga.org/ubuntu/ quantal universe

Install:

% sudo apt-get update
% sudo apt-get -y --allow-unauthenticated install groonga-keyring
% sudo apt-get update
% sudo apt-get -y install groonga

If you want to use MeCab as a tokenizer, install groonga-tokenizer-mecab package.

Install groonga-tokenizer-mecab package:

% sudo apt-get -y install groonga-tokenizer-mecab

There is a package that provides Munin plugins. If you want to monitor groonga status by Munin, install groonga-munin-plugins package.

Install groonga-munin-plugins package:

% sudo apt-get -y install groonga-munin-plugins

There is a package that provides MySQL compatible normalizer as groonga plugins. If you want to use that one, install groonga-normalizer-mysql package.

Install groonga-normalizer-mysql package:

% sudo apt-get -y install groonga-normalizer-mysql

  Build from source

Install required packages to build groonga:

% sudo apt-get -V -y install wget tar build-essential zlib1g-dev liblzo2-dev libmsgpack-dev libzmq-dev libevent-dev libmecab-dev

Download source:

% wget http://packages.groonga.org/source/groonga/groonga-3.0.0.tar.gz
% tar xvzf groonga-3.0.0.tar.gz
% cd groonga-3.0.0

Configure (see source-configure about configure options):

% ./configure

Build:

% make -j$(grep '^processor' /proc/cpuinfo | wc -l)

Install:

% sudo make intall

  CentOS

This section describes how to install groonga related RPM packages on CentOS. You can install them by yum.

We distribute both 32-bit and 64-bit packages but we strongly recommend a 64-bit package for server. You should use a 32-bit package just only for tests or development. You will encounter an out of memory error with a 32-bit package even if you just process medium size data.

Note
    The package 'groonga' is the mininum set of fulltext search engine. If you want to use groonga for server use, you can install additional preconfigured packages.

    There are three packages for server use.

•   groonga-server-http (simple HTTP protocol based server package)

•   groonga-httpd (nginx and HTTP protocol based server package)

•   groonga-server-gqtp (GQTP protocol based server package)

    See /server section about details.

  CentOS 5

Install:

% sudo rpm -ivh http://packages.groonga.org/centos/groonga-release-1.1.0-1.noarch.rpm
% sudo yum makecache
% sudo yum install -y groonga

If you want to use MeCab as a tokenizer, install groonga-tokenizer-mecab package.

Install groonga-tokenizer-mecab package:

% sudo yum install -y groonga-tokenizer-mecab

Then install MeCab dictionary. (mecab-ipadic or mecab-jumandic)

Install IPA dictionary:

% sudo yum install -y mecab-ipadic

Or install Juman dictionary:

% sudo yum install -y mecab-jumandic

There is a package that provides Munin plugins. If you want to monitor groonga status by Munin, install groonga-munin-plugins package.

Note
    Groonga-munin-plugins package requires munin-node package that isn't included in the official CentOS repository. You need to enable Repoforge (RPMforge) repository or EPEL repository to install it by yum.

    Enable Repoforge (RPMforge) repository on i386 environment:

    % wget http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.2-2.el5.rf.i386.rpm
    % sudo rpm -ivh rpmforge-release-0.5.2-2.el5.rf.i386.rpm

    Enable Repoforge (RPMforge) repository on x86_64 environment:

    % wget http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.2-2.el5.rf.x86_64.rpm
    % sudo rpm -ivh rpmforge-release-0.5.2-2.el5.rf.x86_64.rpm

    Enable EPEL repository on any environment:

    % wget http://download.fedoraproject.org/pub/epel/5/i386/epel-release-5-4.noarch.rpm
    % sudo rpm -ivh epel-release-5-4.noarch.rpm

Install groonga-munin-plugins package:

% sudo yum install -y groonga-munin-plugins

There is a package that provides MySQL compatible normalizer as groonga plugins. If you want to use that one, install groonga-normalizer-mysql package.

Install groonga-normalizer-mysql package:

% sudo yum install -y install groonga-normalizer-mysql

  CentOS 6

Install:

% sudo rpm -ivh http://packages.groonga.org/centos/groonga-release-1.1.0-1.noarch.rpm
% sudo yum makecache
% sudo yum install -y groonga

If you want to use MeCab as a tokenizer, install groonga-tokenizer-mecab package.

Install groonga-tokenizer-mecab package:

% sudo yum install -y groonga-tokenizer-mecab

Then install MeCab dictionary. (mecab-ipadic or mecab-jumandic)

Install IPA dictionary:

% sudo yum install -y mecab-ipadic

Or install Juman dictionary:

% sudo yum install -y mecab-jumandic

There is a package that provides Munin plugins. If you want to monitor groonga status by Munin, install groonga-munin-plugins package.

Note
    Groonga-munin-plugins package requires munin-node package that isn't included in the official CentOS repository. You need to enable EPEL repository to install it by yum.

    Enable EPEL repository on any environment:

    % sudo rpm -ivh http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm

Install groonga-munin-plugins package:

% sudo yum install -y groonga-munin-plugins

There is a package that provides MySQL compatible normalizer as groonga plugins. If you want to use that one, install groonga-normalizer-mysql package.

Install groonga-normalizer-mysql package:

% sudo yum install -y install groonga-normalizer-mysql

  Build from source

Install required packages to build groonga:

% sudo yum install -y wget tar gcc-c++ make mecab-devel

Download source:

% wget http://packages.groonga.org/source/groonga/groonga-3.0.0.tar.gz
% tar xvzf groonga-3.0.0.tar.gz
% cd groonga-3.0.0

Configure (see source-configure about configure options):

% ./configure

Build:

% make -j$(grep '^processor' /proc/cpuinfo | wc -l)

Install:

% sudo make intall

  Fedora

This section describes how to install groonga related RPM packages on Fedora. You can install them by yum.

Groonga related RPM pakcages are also in the official Fedora yum repository. So you can use them instead of the groonga yum repository. The different between the groonga yum repository and the official Fedora yum repository is that the groonga yum repository provides the latest version at the release day but the official Fedora yum repository provides the latest version a few days later. That is, the different is very small. :-)

We distribute both 32-bit and 64-bit packages but we strongly recommend a 64-bit package for server. You should use a 32-bit package just only for tests or development. You will encounter an out of memory error with a 32-bit package even if you just process medium size data.

Note
    The package 'groonga' is the mininum set of fulltext search engine. If you want to use groonga for server use, you can install additional preconfigured packages.

    There are three packages for server use.

•   groonga-server-http (simple HTTP protocol based server package)

•   groonga-httpd (nginx and HTTP protocol based server package)

•   groonga-server-gqtp (GQTP protocol based server package)

    See /server section about details.

  Fedora 18

Install:

% sudo rpm -ivh http://packages.groonga.org/fedora/groonga-release-1.1.0-1.noarch.rpm
% sudo yum update
% sudo yum install -y groonga

If you want to use MeCab as a tokenizer, install groonga-tokenizer-mecab package.

Install groonga-tokenizer-mecab package:

% sudo yum install -y groonga-tokenizer-mecab

Then install MeCab dictionary. (mecab-ipadic or mecab-jumandic)

Install IPA dictionary:

% sudo yum install -y mecab-ipadic

Or install Juman dictionary:

% sudo yum install -y mecab-jumandic

There is a package that provides Munin plugins. If you want to monitor groonga status by Munin, install groonga-munin-plugins package.

Install groonga-munin-plugins package:

% sudo yum install -y groonga-munin-plugins

There is a package that provides MySQL compatible normalizer as groonga plugins. If you want to use that one, install groonga-normalizer-mysql package.

Install groonga-normalizer-mysql package:

% sudo yum install -y install groonga-normalizer-mysql

  Build from source

Install required packages to build groonga:

% sudo yum install -y wget tar gcc-c++ make mecab-devel libedit-devel

Download source:

% wget http://packages.groonga.org/source/groonga/groonga-3.0.0.tar.gz
% tar xvzf groonga-3.0.0.tar.gz
% cd groonga-3.0.0

Configure (see source-configure about configure options):

% ./configure

Build:

% make -j$(grep '^processor' /proc/cpuinfo | wc -l)

Install:

% sudo make intall

  Oracle Solaris

This section describes how to install groonga from source on Oracle Solaris.

  Oracle Solaris 11

Install required packages to build groonga:

% sudo pkg install gnu-tar gcc-45 system/header

Download source:

% wget http://packages.groonga.org/source/groonga/groonga-3.0.0.tar.gz
% gtar xvzf groonga-3.0.0.tar.gz
% cd groonga-3.0.0

Configure with CFLAGS="-m64" CXXFLAGS="-m64" variables. They are needed for building 64-bit version. To build 32-bit version, just remove those variables. (see source-configure about configure options):

% ./configure CFLAGS="-m64" CXXFLAGS="-m64"

Build:

% make

Install:

% sudo make install

  Others

This section describes how to install groonga from source on UNIX like environment.

To get more detail about installing groonga from source on the specific environment, find the document for the specific environment from /install.

  Dependencies

Groonga doesn't require any special libraries but requires some tools for build.

  Tools

Here are required tools:

•   wget, curl or Web browser for downloading source archive

•   tar and gzip for extracting source archive

•   shell (many shells such as dash, bash and zsh will work)

•   C compiler and C++ compiler (gcc and g++ are supported but other compilers may work)

•   make (GNU make is supported but other make like BSD make will work)

    You must get them ready.

    You can use CMake instead of shell but this document doesn't describe about building with CMake.

    Here are optional tools:

•   pkg-config for detecting libraries

•   sudo for installing built groonga

    You must get them ready if you want to use optional libraries.

  Libraries

All libraries are optional. Here are optional libraries:

•   MeCab for tokenizing full-text search target document by morphological analysis

•   KyTea for tokenizing full-text search target document by morphological analysis

•   ZeroMQ for /suggest

•   libevent for /suggest

•   MessagePack for supporting MessagePack output and /suggest

•   libedit for command line editing in /reference/executables/groonga

•   zlib for compressing column value

•   LZO for compressing column value

    If you want to use those all or some libraries, you need to install them before installing groonga.

  Build from source

Groonga uses GNU build system. So the following is the simplest build steps:

% wget http://packages.groonga.org/source/groonga/groonga-3.0.0.tar.gz
% tar xvzf groonga-3.0.0.tar.gz
% cd groonga-3.0.0
% ./configure
% make
% sudo make install

After the above steps, /reference/executables/groonga is found in /usr/local/bin/groonga.

The default build will work well but you can customize groonga at configure step.

The following describes details about each step.

  configure

First, you need to run configure. Here are important configure options:

  --prefix=PATH

Specifies the install base directory. Groonga related files are installed under ${PATH}/ directory.

The default is /usr/local. In this case, /reference/executables/groonga is installed into /usr/local/bin/groonga.

Here is an example that installs groonga into ~/local for an user use instead of system wide use:

% ./configure --prefix=$HOME/local

  --localstatedir=PATH

Specifies the base directory to place modifiable file such as log file, PID file and database files. For example, log file is placed at ${PATH}/log/groonga.log.

The default is /usr/local/var.

Here is an example that system wide /var is used for modifiable files:

% ./configure --localstatedir=/var

  --with-log-path=PATH

Specifies the default log file path. You can override the default log path is /reference/executables/groonga command's --log-path command line option. So this option is not critical build option. It's just for convenient.

The default is /usr/local/var/log/groonga.log. The /usr/local/var part is changed by --localestatedir option.

Here is an example that log file is placed into shared NFS directory /nfs/log/groonga.log:

% ./configure --with-log-path=/nfs/log/groonga.log

  --with-default-encoding=ENCODING

Specifies the default encoding. Available encodings are euc_jp, sjis, utf8, latin1, koi8r and none.

The default is utf-8.

Here is an example that Shift_JIS is used as the default encoding:

% ./configure --with-default-encoding=sjis

  --with-match-escalation-threshold=NUMBER

Specifies the default match escalation threshold. See match-escalation-threshold about match escalation threshold. -1 means that match operation never escalate.

The default is 0.

Here is an example that match escalation isn't used by default:

% ./configure --with-match-escalation-threshold=-1

  --with-zlib

Enables column value compression by zlib.

The default is disabled.

Here is an example that enables column value compression by zlib:

% ./configure --with-zlib

  --with-lzo

Enables column value compression by LZO.

The default is disabled.

Here is an example that enables column value compression by LZO:

% ./configure --with-lzo

  --with-message-pack=MESSAGE_PACK_INSTALL_PREFIX

Specifies where MessagePack is installed. If MessagePack isn't installed with --prefix=/usr, you need to specify this option with path that you use for building MessagePack.

If you installed MessagePack with --prefix=$HOME/local option, you sholud specify --with-message-pack=$HOME/local to groonga's configure.

The default is /usr.

Here is an example that uses MessagePack built with --prefix=$HOME/local option:

% ./configure --with-message-pack=$HOME/local

  --with-munin-plugins

Installs Munin plugins for groonga. They are installed into ${PREFIX}/share/groonga/munin/plugins/.

Those plugins are not installed by default.

Here is an example that installs Munin plugins for groonga:

% ./configure --with-munin-plugins

  --with-package-platform=PLATFORM

Installs platform specific system management files such as init script. Available platforms are redhat and fedora. redhat is for Red Hat and Red Hat clone distributions such as CentOS. fedora is for Fedora.

Those system management files are not installed by default.

Here is an example that installs CentOS specific system management files:

% ./configure --with-package-platform=redhat

  --help

Shows all configure options.

  make

configure is succeeded, you can build groonga by make:

% make

If you have multi cores CPU, you can make faster by using -j option. If you have 4 cores CPU, it's good for using -j4 option:

% make -j4

If you get some errors by make, please report them to us: /contribution/report

  make install

Now, you can install built groonga!:

% sudo make install

If you have write permission for ${PREFIX}, you don't need to use sudo. e.g. --prefix=$HOME/local case. In this case, use make install:

% make install

COMMUNITY

There are some places for sharing groonga information. We welcome you to join our community.

  Mailing List

There are mailing lists for discussion about groonga.

For English speakers
    groonga-talk@lists.sourceforge.net

For Japanese speakers
    groonga-dev@lists.sourceforge.jp

  Twitter

@groonga tweets groonga related information.

Please follow the account to get the latest groonga related information!

  Facebook

groonga page on Facebook shares groonga related information.

Please like the page to get the latest groonga related information!

TUTORIAL

  Basic operations

A groonga package provides a C library (libgroonga) and a command line tool (groonga). This tutorial explains how to use the command line tool, with which you can create/operate databases, start a server, establish a connection with a server, etc.

  Create a database

The first step to using groonga is to create a new database. The following shows how to do it.

Form:

groonga -n DB_PATH

The -n option specifies to create a new database and DB_PATH specifies the path of the new database. Actually, a database consists of a series of files and DB_PATH specifies the file which will be the entrance to the new database. DB_PATH also specifies the path prefix for other files. Note that database creation fails if DB_PATH points to an existing file.

This command creates a new database and then enters into interactive mode in which groonga prompts you to enter commands for operating that database. You can terminate this mode with Ctrl-d.

Execution example:

% groonga -n /tmp/groonga-databases/introduction.db

After this database creation, you can find a series of files in /tmp/groonga-databases.

  Operate a database

The following shows how to operate an existing database.

Form:

groonga DB_PATH [COMMAND]

DB_PATH specifies the path of a target database. This command fails if the specified database does not exist.

If COMMAND is specified, groonga executes COMMAND and returns the result. Otherwise, groonga starts in interactive mode that reads commands from the standard input and executes them one by one. This tutorial focuses on the interactive mode.

Let's see the status of a groonga process by using a /reference/commands/status command.

Execution example:

% groonga /tmp/groonga-databases/introduction.db
status
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   {
#     "uptime": 0,
#     "max_command_version": 2,
#     "n_queries": 0,
#     "cache_hit_rate": 0.0,
#     "version": "2.1.0",
#     "alloc_count": 152,
#     "command_version": 1,
#     "starttime": 1356678603,
#     "default_command_version": 1
#   }
# ]

As shown in the above example, a command returns a JSON array. The first element contains an error code, execution time, etc. The second element is the result of an operation.

  Command format

Commands for operating a database accept arguments as follows:

Form_1: COMMAND VALUE_1 VALUE_2 ..
Form_2: COMMAND --NAME_1 VALUE_1 --NAME_2 VALUE_2 ..

In the first form, arguments must be passed in order. This kind of arguments are called positional arguments because the position of each argument determines its meaning.

In the second form, you can specify a parameter name with its value. So, the order of arguments is not defined. This kind of arguments are known as named parameters or keyword arguments.

If you want to specify a value which contains white-spaces or special characters, such as quotes and parentheses, please enclose the value with single-quotes or double-quotes.

For details, see also the paragraph of "command" in /reference/executables/groonga.

  Basic commands

/reference/commands/status
    shows status of a groonga process.

/reference/commands/table_list
    shows a list of tables in a database.

/reference/commands/column_list
    shows a list of columns in a table.

/reference/commands/table_create
    adds a table to a database.

/reference/commands/column_create
    adds a column to a table.

/reference/commands/select
    searches records from a table and shows the result.

/reference/commands/load
    inserts records to a table.

  Create a table

A /reference/commands/table_create command creates a new table.

In most cases, a table has a primary key which must be specified with its data type and index type.

There are various data types such as integers, strings, etc. See also /reference/types for more details. The index type determines the search performance and the availability of prefix searches. The details will be described later.

Let's create a table. The following example creates a table with a primary key. The name parameter specifies the name of the table. The flags parameter specifies the index type for the primary key. The key_type parameter specifies the data type of the primary key.

Execution example:

table_create --name Site --flags TABLE_HASH_KEY --key_type ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]

The second element of the result indicates that the operation succeeded.

  View a table

A /reference/commands/select command can enumerate records in a table.

Execution example:

select --table Site
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         0
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ]
#       ]
#     ]
#   ]
# ]

When only a table name is specified with a table parameter, a /reference/commands/select command returns the first (at most) 10 records in the table. [0] in the result shows the number of records in the table. The next array is a list of columns. ["_id","Uint32"] is a column of UInt32, named _id. ["_key","ShortText"] is a column of ShortText, named _key.

The above two columns, _id and _key, are the necessary columns. The _id column stores IDs those are automatically allocated by groonga. The _key column is associated with the primary key. You are not allowed to rename these columns.

  Create a column

A /reference/commands/column_create command creates a new column.

Let's add a column. The following example adds a column to the Site table. The table parameter specifies the target table. The name parameter specifies the name of the column. The type parameter specifies the data type of the column.

Execution example:

column_create --table Site --name title --type ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
select --table Site
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         0
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "title",
#           "ShortText"
#         ]
#       ]
#     ]
#   ]
# ]

  Load records

A /reference/commands/load command loads JSON-formatted records into a table.

The following example loads nine records into the Site table.

Execution example:

load --table Site
[
{"_key":"http://example.org/","title":"This is test record 1!"},
{"_key":"http://example.net/","title":"test record 2."},
{"_key":"http://example.com/","title":"test test record three."},
{"_key":"http://example.net/afr","title":"test record four."},
{"_key":"http://example.org/aba","title":"test test test record five."},
{"_key":"http://example.com/rab","title":"test test test test record six."},
{"_key":"http://example.net/atv","title":"test test test record seven."},
{"_key":"http://example.org/gat","title":"test test record eight."},
{"_key":"http://example.com/vdw","title":"test test record nine."},
]
# [[0, 1337566253.89858, 0.000355720520019531], 9]

The second element of the result indicates how many records were successfully loaded. In this case, all the records are successfully loaded.

Let's make sure that these records are correctly stored.

Execution example:

select --table Site
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         9
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "title",
#           "ShortText"
#         ]
#       ],
#       [
#         1,
#         "http://example.org/",
#         "This is test record 1!"
#       ],
#       [
#         2,
#         "http://example.net/",
#         "test record 2."
#       ],
#       [
#         3,
#         "http://example.com/",
#         "test test record three."
#       ],
#       [
#         4,
#         "http://example.net/afr",
#         "test record four."
#       ],
#       [
#         5,
#         "http://example.org/aba",
#         "test test test record five."
#       ],
#       [
#         6,
#         "http://example.com/rab",
#         "test test test test record six."
#       ],
#       [
#         7,
#         "http://example.net/atv",
#         "test test test record seven."
#       ],
#       [
#         8,
#         "http://example.org/gat",
#         "test test record eight."
#       ],
#       [
#         9,
#         "http://example.com/vdw",
#         "test test record nine."
#       ]
#     ]
#   ]
# ]

  Get a record

A /reference/commands/select command can search records in a table.

If a search condition is specified with a query parameter, a /reference/commands/select command searches records matching the search condition and returns the matched records.

Let's get a record having a specified record ID. The following example gets the first record in the Site table. More precisely, the query parameter specifies a record whose _id column stores 1.

Execution example:

select --table Site --query _id:1
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "title",
#           "ShortText"
#         ]
#       ],
#       [
#         1,
#         "http://example.org/",
#         "This is test record 1!"
#       ]
#     ]
#   ]
# ]

Next, let's get a record having a specified key. The following example gets the record whose primary key is "http://example.org/". More precisely, the query parameter specifies a record whose _key column stores "http://example.org/".

Execution example:

select --table Site --query '_key:"http://example.org/"'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "title",
#           "ShortText"
#         ]
#       ],
#       [
#         1,
#         "http://example.org/",
#         "This is test record 1!"
#       ]
#     ]
#   ]
# ]

  Create a lexicon table for full text search

Let's go on to how to make full text search.

Groonga uses an inverted index to provide fast full text search. So, the first step is to create a lexicon table which stores an inverted index, also known as postings lists. The primary key of this table is associated with a vocabulary made up of index terms and each record stores postings lists for one index term.

The following shows a command which creates a lexicon table named Terms. The data type of its primary key is ShortText.

Execution example:

table_create --name Terms --flags TABLE_PAT_KEY|KEY_NORMALIZE --key_type ShortText --default_tokenizer TokenBigram
# [[0, 1337566253.89858, 0.000355720520019531], true]

The /reference/commands/table_create command takes many parameters but you don't need to understand all of them. Please skip the next paragraph if you are not interested in how it works.

The TABLE_PAT_KEY flag specifies to store index terms in a patricia trie. The KEY_NORMALIZE flag specifies to normalize index terms. In this example, both flags are validated by using a '|'. The default_tokenizer parameter specifies the method for tokenizing text. This example uses TokenBigram that is generally called N-gram.

  Create an index column for full text search

The second step is to create an index column, which allows you to search records from its associated column. That is to say this step specifies which column needs an index.

Let's create an index column. The following example creates an index column for a column in the Site table.

Execution example:

column_create --table Terms --name blog_title --flags COLUMN_INDEX|WITH_POSITION --type Site --source title
# [[0, 1337566253.89858, 0.000355720520019531], true]

The table parameter specifies the index table and the name parameter specifies the index column. The type parameter specifies the target table and the source parameter specifies the target column. The COLUMN_INDEX flag specifies to create an index column and the WITH_POSITION flag specifies to create a full inverted index, which contains the positions of each index term. This combination, COLUMN_INDEX|WITH_POSITION, is recommended for the general purpose.

Note
    You can create a lexicon table and index columns before/during/after loading records. If a target column already has records, groonga creates an inverted index in a static manner. In contrast, if you load records into an already indexed column, groonga updates the inverted index in a dynamic manner.

  Full text search

It's time. You can make full text search with a /reference/commands/select command.

A query for full text search is specified with a query parameter. The following example searches records whose "title" column contains "this". The '@' specifies to make full text search. Note that a lower case query matches upper case and capitalized terms in a record if KEY_NORMALIZE was specified when creating a lexcon table.

Execution example:

select --table Site --query title:@this
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "title",
#           "ShortText"
#         ]
#       ],
#       [
#         1,
#         "http://example.org/",
#         "This is test record 1!"
#       ]
#     ]
#   ]
# ]

In this example, the first record matches the query because its title contains "This", that is the capitalized form of the query.

A /reference/commands/select command accepts an optional parameter, named match_columns, that specifies the default target columns. This parameter is used if target columns are not specified in a query. [1]

The combination of "--match_columns title" and "--query this" brings you the same result that "--query title:@this" does.

Execution example:

select --table Site --match_columns title --query this
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "title",
#           "ShortText"
#         ]
#       ],
#       [
#         1,
#         "http://example.org/",
#         "This is test record 1!"
#       ]
#     ]
#   ]
# ]

  Specify output columns

An output_columns parameter of a /reference/commands/select command specifies columns to appear in the search result. If you want to specify more than one columns, please separate column names by commas (',').

Execution example:

select --table Site --output_columns _key,title,_score --query title:@test
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         9
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "title",
#           "ShortText"
#         ],
#         [
#           "_score",
#           "Int32"
#         ]
#       ],
#       [
#         "http://example.org/",
#         "This is test record 1!",
#         1
#       ],
#       [
#         "http://example.net/",
#         "test record 2.",
#         1
#       ],
#       [
#         "http://example.com/",
#         "test test record three.",
#         2
#       ],
#       [
#         "http://example.net/afr",
#         "test record four.",
#         1
#       ],
#       [
#         "http://example.org/aba",
#         "test test test record five.",
#         3
#       ],
#       [
#         "http://example.com/rab",
#         "test test test test record six.",
#         4
#       ],
#       [
#         "http://example.net/atv",
#         "test test test record seven.",
#         3
#       ],
#       [
#         "http://example.org/gat",
#         "test test record eight.",
#         2
#       ],
#       [
#         "http://example.com/vdw",
#         "test test record nine.",
#         2
#       ]
#     ]
#   ]
# ]

This example specifies three output columns including the _score column, which stores the relevance score of each record.

  Specify output ranges

A /reference/commands/select command returns a part of its search result if offset and/or limit parameters are specified. These parameters are useful to paginate a search result, a widely-used interface which shows a search result on a page by page basis.

An offset parameter specifies the starting point and a limit parameter specifies the maximum number of records to be returned. If you need the first record in a search result, the offset parameter must be 0 or omitted.

Execution example:

select --table Site --offset 0 --limit 3
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         9
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "title",
#           "ShortText"
#         ]
#       ],
#       [
#         1,
#         "http://example.org/",
#         "This is test record 1!"
#       ],
#       [
#         2,
#         "http://example.net/",
#         "test record 2."
#       ],
#       [
#         3,
#         "http://example.com/",
#         "test test record three."
#       ]
#     ]
#   ]
# ]
select --table Site --offset 3 --limit 3
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         9
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "title",
#           "ShortText"
#         ]
#       ],
#       [
#         4,
#         "http://example.net/afr",
#         "test record four."
#       ],
#       [
#         5,
#         "http://example.org/aba",
#         "test test test record five."
#       ],
#       [
#         6,
#         "http://example.com/rab",
#         "test test test test record six."
#       ]
#     ]
#   ]
# ]
select --table Site --offset 7 --limit 3
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         9
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "title",
#           "ShortText"
#         ]
#       ],
#       [
#         8,
#         "http://example.org/gat",
#         "test test record eight."
#       ],
#       [
#         9,
#         "http://example.com/vdw",
#         "test test record nine."
#       ]
#     ]
#   ]
# ]

  Sort a search result

A /reference/commands/select command sorts its result when used with a sortby parameter.

A sortby parameter specifies a column as a sorting creteria. A search result is arranged in ascending order of the column values. If you want to sort a search result in reverse order, please add a leading hyphen ('-') to the column name in a parameter.

The following example shows records in the Site table in reverse order.

Execution example:

select --table Site --sortby -_id
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         9
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "title",
#           "ShortText"
#         ]
#       ],
#       [
#         9,
#         "http://example.com/vdw",
#         "test test record nine."
#       ],
#       [
#         8,
#         "http://example.org/gat",
#         "test test record eight."
#       ],
#       [
#         7,
#         "http://example.net/atv",
#         "test test test record seven."
#       ],
#       [
#         6,
#         "http://example.com/rab",
#         "test test test test record six."
#       ],
#       [
#         5,
#         "http://example.org/aba",
#         "test test test record five."
#       ],
#       [
#         4,
#         "http://example.net/afr",
#         "test record four."
#       ],
#       [
#         3,
#         "http://example.com/",
#         "test test record three."
#       ],
#       [
#         2,
#         "http://example.net/",
#         "test record 2."
#       ],
#       [
#         1,
#         "http://example.org/",
#         "This is test record 1!"
#       ]
#     ]
#   ]
# ]

The next example uses the _score column as the sorting criteria for ranking the search result. The result is sorted in relevance order.

Execution example:

select --table Site --query title:@test --output_columns _id,_score,title --sortby -_score
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         9
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_score",
#           "Int32"
#         ],
#         [
#           "title",
#           "ShortText"
#         ]
#       ],
#       [
#         6,
#         4,
#         "test test test test record six."
#       ],
#       [
#         5,
#         3,
#         "test test test record five."
#       ],
#       [
#         7,
#         3,
#         "test test test record seven."
#       ],
#       [
#         8,
#         2,
#         "test test record eight."
#       ],
#       [
#         3,
#         2,
#         "test test record three."
#       ],
#       [
#         9,
#         2,
#         "test test record nine."
#       ],
#       [
#         1,
#         1,
#         "This is test record 1!"
#       ],
#       [
#         4,
#         1,
#         "test record four."
#       ],
#       [
#         2,
#         1,
#         "test record 2."
#       ]
#     ]
#   ]
# ]

If you want to specify more than one columns, please separate column names by commas (','). In such a case, a search result is sorted in order of the values in the first column, and then records having the same values in the first column are sorted in order of the second column values.

Execution example:

select --table Site --query title:@test --output_columns _id,_score,title --sortby -_score,_id
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         9
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_score",
#           "Int32"
#         ],
#         [
#           "title",
#           "ShortText"
#         ]
#       ],
#       [
#         6,
#         4,
#         "test test test test record six."
#       ],
#       [
#         5,
#         3,
#         "test test test record five."
#       ],
#       [
#         7,
#         3,
#         "test test test record seven."
#       ],
#       [
#         3,
#         2,
#         "test test record three."
#       ],
#       [
#         8,
#         2,
#         "test test record eight."
#       ],
#       [
#         9,
#         2,
#         "test test record nine."
#       ],
#       [
#         1,
#         1,
#         "This is test record 1!"
#       ],
#       [
#         2,
#         1,
#         "test record 2."
#       ],
#       [
#         4,
#         1,
#         "test record four."
#       ]
#     ]
#   ]
# ]
footnote

[1] Currently, a match_columns parameter is available iff there exists an inverted index for full text search. A match_columns parameter for a regular column is not supported.

  Remote access

You can use groonga as a server which allows remote access. Groonga supports the original protocol (gqtp), the memcached binary protocol and HTTP.

  Groonga query transfer protocol (gqtp)

  How to run a gqtp server

Groonga has a special protocol, named groonga query transfer ptorotocl (gqtp), for remote access to a database. The following form shows how to run groonga as a gqtp server.

Form:

groonga [-p PORT_NUMBER] -s DB_PATH

The -s option specifies to run groonga as a server. DB_PATH specifies the path of the existing database to be hosted. The -p option and its argument, PORT_NUMBER, specify the port number of the server. The default port number is 10041, which is used when you don't specify PORT_NUMBER.

The following command runs a server that listens on the default port number. The server accepts operations to the specified database.

Execution example:

% groonga -s /tmp/groonga-databases/introduction.db
Ctrl-c
%

  How to run a gqtp daemon

You can also run a gqtp server as a daemon by using the -d option, instead of the -s option.

Form:

groonga [-p PORT_NUMBER] -d DB_PATH

A groonga daemon prints its process ID as follows. In this example, the process ID is 12345. Then, the daemon opens a specified database and accepts operations to that database.

Execution example:

% groonga -d /tmp/groonga-databases/introduction.db
12345
%

  How to run a gqtp client

You can run groonga as a gqtp client as follows:

Form:

groonga [-p PORT_NUMBER] -c [HOST_NAME_OR_IP_ADDRESS]

This command establishes a connection with a gqtp server and then enters into interactive mode. HOST_NAME_OR_IP_ADDRESS specifies the hostname or the IP address of the server. If not specifed, groonga uses the default hostname "localhost". The -p option and its argument, PORT_NUMBER, specify the port number of the server. If not specified, groonga uses the default port number 10041.

Execution example:

% groonga -c
status
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   {
#     "uptime": 0,
#     "max_command_version": 2,
#     "n_queries": 0,
#     "cache_hit_rate": 0.0,
#     "version": "2.0.5",
#     "alloc_count": 121,
#     "command_version": 1,
#     "starttime": 1343713541,
#     "default_command_version": 1
#   }
# ]
> ctrl-d
%

In interactive mode, groonga reads commands from the standard input and executes them one by one.

  How to terminate a gqtp server

You can terminate a gqtp server with a /reference/commands/shutdown command.

Execution example:

% groonga -c
> shutdown
%

  Memcached binary protocol

Groonga supports the memcached binary protocol. The following form shows how to run groonga as a memcached binary protocol server daemon.

Form:

groonga [-p PORT_NUMBER] -d --protocol memcached DB_PATH

The --protocol option and its argument specify the protocol of the server. "memcached" specifies to use the memcached binary protocol.

  Hypertext transfer protocol (HTTP)

  How to run an HTTP server

Groonga supports the hypertext transfer protocol (HTTP). The following form shows how to run groonga as an HTTP server daemon.

Form:

groonga [-p PORT_NUMBER] -d --protocol http DB_PATH

The --protocol option and its argument specify the protocol of the server. "http" specifies to use HTTP.

The following command runs an HTTP server that listens on the port number 80.

Execution example:

% groonga -p 80 -d --protocol http /tmp/groonga-databases/introduction.db
%

  How to send a command to an HTTP server

You can send a command to an HTTP server by sending a GET request to /d/COMMAND_NAME. Command parameters can be passed as parameters of the GET request. The format is "?NAME_1=VALUE_1&NAME_2=VALUE_2&...".

The following example shows how to send commands to an HTTP server.

Execution example:

http://HOST_NAME_OR_IP_ADDRESS[:PORT_NUMBER]/d/status
Executed command:
status
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   {
#     "uptime": 0,
#     "max_command_version": 2,
#     "n_queries": 0,
#     "cache_hit_rate": 0.0,
#     "version": "2.0.5",
#     "alloc_count": 122,
#     "command_version": 1,
#     "starttime": 1343713541,
#     "default_command_version": 1
#   }
# ]
http://HOST_NAME_OR_IP_ADDRESS[:PORT_NUMBER]/d/select?table=Site&query=title:@this
Executed command:
select --table Site --query title:@this
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "country",
#           "SiteCountry"
#         ],
#         [
#           "domain",
#           "SiteDomain"
#         ],
#         [
#           "link",
#           "Site"
#         ],
#         [
#           "links",
#           "Site"
#         ],
#         [
#           "location",
#           "WGS84GeoPoint"
#         ],
#         [
#           "title",
#           "ShortText"
#         ]
#       ],
#       [
#         1,
#         "http://example.org/",
#         "japan",
#         ".org",
#         "http://example.net/",
#         [
#           "http://example.net/",
#           "http://example.org/",
#           "http://example.com/"
#         ],
#         "128452975x503157902",
#         "This is test record 1!"
#       ]
#     ]
#   ]
# ]

  Administration tool (HTTP)

An HTTP server of groonga provides a browser based administration tool that makes database management easy. After starting an HTTP server, you can use the administration tool by accessing http://HOST_NAME_OR_IP_ADDRESS[:PORT_NUMBER]/. Note that Javascript must be enabled for the tool to work properly.

  Security issues

Groonga servers don't support user authentication. Everyone can view and modify databases hosted by groonga servers. You are recommended to restrict IP addresses that can access groonga servers. You can use iptables or similar for this purpose.

  Various data types

Groonga is a full text search engine but also serves as a column-oriented data store. Groonga supports various data types, such as numeric types, string types, date and time type, longitude and latitude types, etc. This tutorial shows a list of data types and explains how to use them.

  Overview

The basic data types of groonga are roughly divided into 5 groups --- boolean type, numeric types, string types, date/time type and longitude/latitude types. The numeric types are further divided according to whether integer or floating point number, signed or unsigned and the number of bits allocated to each integer. The string types are further divided according to the maximum length. The longitude/latitude types are further divided according to the geographic coordinate system. For more details, see /reference/types.

In addition, groonga supports reference types and vector types. Reference types are designed for accessing other tables. Vector types are designed for storing a variable number of values in one element.

First, let's create a table for this tutorial.

Execution example:

table_create --name ToyBox --flags TABLE_HASH_KEY --key_type ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]

  Boolean type

The boolean type is used to store true or false. To create a boolean type column, specify Bool to the type parameter of /reference/commands/column_create command. The default value of the boolean type is false.

The following example creates a boolean type column and adds three records. Note that the third record has the default value because no value is specified.

Execution example:

column_create --table ToyBox --name is_animal --type Bool
# [[0, 1337566253.89858, 0.000355720520019531], true]
load --table ToyBox
[
{"_key":"Monkey","is_animal":true}
{"_key":"Flower","is_animal":false}
{"_key":"Block"}
]
# [[0, 1337566253.89858, 0.000355720520019531], 3]
select --table ToyBox --output_columns _key,is_animal
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         3
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "is_animal",
#           "Bool"
#         ]
#       ],
#       [
#         "Monkey",
#         true
#       ],
#       [
#         "Flower",
#         false
#       ],
#       [
#         "Block",
#         false
#       ]
#     ]
#   ]
# ]

  Numeric types

The numeric types are divided into integer types and a floating point number type. The integer types are further divided into the signed integer types and unsigned integer types. In addition, you can choose the number of bits allocated to each integer. For more details, see /reference/types. The default value of the numeric types is 0.

The following example creates an Int8 column and a Float column, and then updates existing records. The /reference/commands/load command updates the weight column as expected. On the other hand, the price column values are different from the specified values because 15.9 is not an integer and 200 is too large. 15.9 is converted to 15 by removing the fractional part. 200 causes an overflow and the result becomes -56. Note that the result of an overflow/underflow is undefined.

Execution example:

column_create --table ToyBox --name price --type Int8
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create --table ToyBox --name weight --type Float
# [[0, 1337566253.89858, 0.000355720520019531], true]
load --table ToyBox
[
{"_key":"Monkey","price":15.9}
{"_key":"Flower","price":200,"weight":0.13}
{"_key":"Block","weight":25.7}
]
# [[0, 1337566253.89858, 0.000355720520019531], 3]
select --table ToyBox --output_columns _key,price,weight
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         3
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "price",
#           "Int8"
#         ],
#         [
#           "weight",
#           "Float"
#         ]
#       ],
#       [
#         "Monkey",
#         15,
#         0.0
#       ],
#       [
#         "Flower",
#         -56,
#         0.13
#       ],
#       [
#         "Block",
#         0,
#         25.7
#       ]
#     ]
#   ]
# ]

  String types

The string types are divided according to the maximum length. For more details, see /reference/types. The default value is the zero-length string.

The following example creates a ShortText column and updates existing records. The third record has the default value because not updated.

Execution example:

column_create --table ToyBox --name name --type ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
load --table ToyBox
[
{"_key":"Monkey","name":"Grease"}
{"_key":"Flower","name":"Rose"}
]
# [[0, 1337566253.89858, 0.000355720520019531], 2]
select --table ToyBox --output_columns _key,name
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         3
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "name",
#           "ShortText"
#         ]
#       ],
#       [
#         "Monkey",
#         "Grease"
#       ],
#       [
#         "Flower",
#         "Rose"
#       ],
#       [
#         "Block",
#         ""
#       ]
#     ]
#   ]
# ]

  Date and time type

The date and time type of groonga is Time. Actually, a Time column stores a date and time as the number of microseconds since the Epoch, 1970-01-01 00:00:00. A Time value can represent a date and time before the Epoch because the actual data type is a signed integer. Note that /reference/commands/load and /reference/commands/select commands use a decimal number to represent a data and time in seconds. The default value is 0.0, which means the Epoch.

The following example creates a Time column and updates existing records. The first record has the default value because not updated.

Execution example:

column_create --table ToyBox --name time --type Time
# [[0, 1337566253.89858, 0.000355720520019531], true]
load --table ToyBox
[
{"_key":"Flower","time":1234567890.1234569999}
{"_key":"Block","time":-1234567890}
]
# [[0, 1337566253.89858, 0.000355720520019531], 2]
select --table ToyBox --output_columns _key,time
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         3
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "time",
#           "Time"
#         ]
#       ],
#       [
#         "Monkey",
#         0.0
#       ],
#       [
#         "Flower",
#         1234567890.12346
#       ],
#       [
#         "Block",
#         -1234567890.0
#       ]
#     ]
#   ]
# ]

  Longitude and latitude types

The longitude and latitude types are divided according to the geographic coordinate system. For more details, see /reference/types. To represent a longitude and latitude, groonga uses a string formatted as follows:

•   "longitude x latitude" in milliseconds (e.g.: "128452975x503157902")

•   "longitude x latitude" in degrees (e.g.: "35.6813819x139.7660839")

    A number with/without a decimal point represents a longitude or latitude in milliseconds/degrees respectively. Note that a combination of a number with a decimal point and a number without a decimal point (e.g. 35.1x139) must not be used. A comma (',') is also available as a delimiter. The default value is "0x0".

    The following example creates a WGS84GeoPoint column and updates existing records. The second record has the default value because not updated.

    Execution example:

    column_create --table ToyBox --name location --type WGS84GeoPoint
    # [[0, 1337566253.89858, 0.000355720520019531], true]
    load --table ToyBox
    [
    {"_key":"Monkey","location":"128452975x503157902"}
    {"_key":"Block","location":"35.6813819x139.7660839"}
    ]
    # [[0, 1337566253.89858, 0.000355720520019531], 2]
    select --table ToyBox --output_columns _key,location
    # [
    #   [
    #     0,
    #     1337566253.89858,
    #     0.000355720520019531
    #   ],
    #   [
    #     [
    #       [
    #         3
    #       ],
    #       [
    #         [
    #           "_key",
    #           "ShortText"
    #         ],
    #         [
    #           "location",
    #           "WGS84GeoPoint"
    #         ]
    #       ],
    #       [
    #         "Monkey",
    #         "128452975x503157902"
    #       ],
    #       [
    #         "Flower",
    #         "0x0"
    #       ],
    #       [
    #         "Block",
    #         "128452975x503157902"
    #       ]
    #     ]
    #   ]
    # ]

  Reference types

Groonga supports a reference column, which stores references to records in its associated table. In practice, a reference column stores the IDs of the referred records in the associated table and enables access to those records.

You can specify a column in the associated table to the output_columns parameter of a /reference/commands/select command. The format is "Src.Dest" where Src is the name of the reference column and Dest is the name of the target column. If only the reference column is specified, it is handled as "Src._key". Note that if a reference does not point to a valid record, a /reference/commands/select command outputs the default value of the target column.

The following example adds a reference column to the Site table that was created in the previous tutorial. The new column, named link, is designed for storing links among records in the Site table.

Execution example:

column_create --table Site --name link --type Site
# [[0, 1337566253.89858, 0.000355720520019531], true]
load --table Site
[{"_key":"http://example.org/","link":"http://example.net/"}]
select --table Site --output_columns _key,title,link._key,link.title --query title:@this
# [[0, 1337566253.89858, 0.000355720520019531], 1]
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "title",
#           "ShortText"
#         ],
#         [
#           "link._key",
#           "ShortText"
#         ],
#         [
#           "link.title",
#           "ShortText"
#         ]
#       ],
#       [
#         "http://example.org/",
#         "This is test record 1!",
#         "http://example.net/",
#         "test record 2."
#       ]
#     ]
#   ]
# ]

The type parameter of the /reference/commands/column_create command specifies the table to be associated with the reference column. In this example, the reference column is associated with the own table. Then, the /reference/commands/load command registers a link from "http://example.org" to "http://example.net". Note that a reference column requires the primary key, not the ID, of the record to be referred to. After that, the link is confirmed by the /reference/commands/select command. In this case, the primary key and the title of the referred record are output because link._key and link.title are specified to the output_columns parameter.

  Vector types

Groonga supports a vector column, in which each element can store a variable number of values. To create a vector column, specify the COLUMN_VECTOR flag to the flags parameter of a /reference/commands/column_create command. A vector column is useful to represent a many-to-many relationship.

The previous example used a regular column, so each record could have at most one link. Obviously, the specification is insufficient because a site usually has more than one links. To solve this problem, the following example uses a vector column.

Execution example:

column_create --table Site --name links --flags COLUMN_VECTOR --type Site
# [[0, 1337566253.89858, 0.000355720520019531], true]
load --table Site
[{"_key":"http://example.org/","links":["http://example.net/","http://example.org/","http://example.com/"]}]
select --table Site --output_columns _key,title,links._key,links.title --query title:@this
# [[0, 1337566253.89858, 0.000355720520019531], 1]
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "title",
#           "ShortText"
#         ],
#         [
#           "links._key",
#           "ShortText"
#         ],
#         [
#           "links.title",
#           "ShortText"
#         ]
#       ],
#       [
#         "http://example.org/",
#         "This is test record 1!",
#         [
#           "http://example.net/",
#           "http://example.org/",
#           "http://example.com/"
#         ],
#         [
#           "test record 2.",
#           "This is test record 1!",
#           "test test record three."
#         ]
#       ]
#     ]
#   ]
# ]

The only difference at the first step is the flags parameter that specifies to create a vector column. The type parameter of the /reference/commands/column_create command is the same as in the previous example. Then, the /reference/commands/load command registers three links from "http://example.org/" to "http://example.net/", "http://example.org/" and "http://example.com/". After that, the links are confirmed by the /reference/commands/select command. In this case, the primary keys and the titles are output as arrays because links._key and links.title are specified to the output_columns parameter.

  さまざまな検索条件の指定

groongaは、JavaScriptに似た文法での条件絞込や、計算した値を用いたソートを行うことができます。また、位置情報(緯度・経度)を用いた絞込・ソートを行うことができます。

  JavaScriptに似た文法での絞込・全文検索

selectコマンドのfilterパラメータは、queryパラメータと同様に、レコードの検索条件を指定します。filterパラメータとqueryパラメータが異なる点は、filterパラメータには、JavaScriptの式に似た文法で条件を指定する点です。

Execution example:

select --table Site --filter "_id <= 1" --output_columns _id,_key
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ]
#       ],
#       [
#         1,
#         "http://example.org/"
#       ]
#     ]
#   ]
# ]

ここで、filterパラメータには _id <= 1

という条件を指定しています。この場合は_idの値が1以下のレコードが検索結果として得られます。

また、&& や || を使って、条件のAND・OR指定をすることもできます。

Execution example:

select --table Site --filter "_id >= 4 && _id <= 6" --output_columns _id,_key
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         3
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ]
#       ],
#       [
#         4,
#         "http://example.net/afr"
#       ],
#       [
#         5,
#         "http://example.org/aba"
#       ],
#       [
#         6,
#         "http://example.com/rab"
#       ]
#     ]
#   ]
# ]
select --table Site --filter "_id <= 2 || _id >= 7" --output_columns _id,_key
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         5
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ]
#       ],
#       [
#         1,
#         "http://example.org/"
#       ],
#       [
#         2,
#         "http://example.net/"
#       ],
#       [
#         7,
#         "http://example.net/atv"
#       ],
#       [
#         8,
#         "http://example.org/gat"
#       ],
#       [
#         9,
#         "http://example.com/vdw"
#       ]
#     ]
#   ]
# ]

queryパラメータとfilterパラメータを同時に指定すると、両者の条件をともに満たすレコードが結果として返ります。

  scorerを利用したソート

selectコマンドのscorerパラメータは、 全文検索を行った結果の各レコードに対して処理を行うためのパラメータです。

filterパラメータと同様に、 JavaScriptの式に似たな文法で様々な条件を指定することができます。

Execution example:

select --table Site --filter "1" --scorer "_score = rand()" --output_columns _id,_key,_score --sortby _score
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         9
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "_score",
#           "Int32"
#         ]
#       ],
#       [
#         6,
#         "http://example.com/rab",
#         424238335
#       ],
#       [
#         9,
#         "http://example.com/vdw",
#         596516649
#       ],
#       [
#         7,
#         "http://example.net/atv",
#         719885386
#       ],
#       [
#         2,
#         "http://example.net/",
#         846930886
#       ],
#       [
#         8,
#         "http://example.org/gat",
#         1649760492
#       ],
#       [
#         3,
#         "http://example.com/",
#         1681692777
#       ],
#       [
#         4,
#         "http://example.net/afr",
#         1714636915
#       ],
#       [
#         1,
#         "http://example.org/",
#         1804289383
#       ],
#       [
#         5,
#         "http://example.org/aba",
#         1957747793
#       ]
#     ]
#   ]
# ]
select --table Site --filter "1" --scorer "_score = rand()" --output_columns _id,_key,_score --sortby _score
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         9
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "_score",
#           "Int32"
#         ]
#       ],
#       [
#         4,
#         "http://example.net/afr",
#         783368690
#       ],
#       [
#         2,
#         "http://example.net/",
#         1025202362
#       ],
#       [
#         5,
#         "http://example.org/aba",
#         1102520059
#       ],
#       [
#         1,
#         "http://example.org/",
#         1189641421
#       ],
#       [
#         3,
#         "http://example.com/",
#         1350490027
#       ],
#       [
#         8,
#         "http://example.org/gat",
#         1365180540
#       ],
#       [
#         9,
#         "http://example.com/vdw",
#         1540383426
#       ],
#       [
#         7,
#         "http://example.net/atv",
#         1967513926
#       ],
#       [
#         6,
#         "http://example.com/rab",
#         2044897763
#       ]
#     ]
#   ]
# ]

検索結果には、'_score'という名前の、全文検索のスコアが代入されている仮想的なカラムが付与されることをチュートリアル中ソートの項目で説明しました。

上記の実行例では、scorerパラメータに _score = rand()

という条件を指定しています。ここでは、rand()という乱数を返す関数を用いて、全文検索のスコアを乱数で上書きしています。

sortbyパラメータには、 _score

を指定しています。これは、スコア順に昇順にソートすることを意味しています。

よって、上記のクエリは実行されるたびに検索結果の並び順がランダムに変わります。

  位置情報を用いた絞込・ソート

groongaでは、位置情報（経緯度）を保存することができます。また、保存した経緯度を用いて絞込やソートができます。

位置情報を保存するためのカラムの型として、TokyoGeoPoint/WGS84GeoPointの２つの型があります。前者は日本測地系、後者は世界測地系(WGS84相当)の経緯度を保存します。

経緯度は以下のいずれかの形式の文字列として指定します。

•   "[緯度のミリ秒]x[経度のミリ秒]"（例: "128452975x503157902"）

•   "[緯度のミリ秒],[経度のミリ秒]"（例: "128452975,503157902"）

•   "[緯度の小数表記の度数]x[経度の小数表記の度数]"（例: "35.6813819x139.7660839"）

•   "[緯度の小数表記の度数],[経度の小数表記の度数]"（例: "35.6813819,139.7660839"）

    ここでは、ためしに東京駅と新宿駅とついて、世界測地系での位置情報を保存してみましょう。東京駅は緯度が35度40分52.975秒、経度が139度45分57.902秒です。新宿駅は緯度が35度41分27.316秒、経度が139度42分0.929秒です。よって、ミリ秒表記の場合はそれぞれ"128452975x503157902"/"128487316x502920929"となります。度数表記の場合はそれぞれ"35.6813819x139.7660839"/"35.6909211x139.7002581"となります。ここではミリ秒表記で登録しましょう。

    Execution example:

    column_create --table Site --name location --type WGS84GeoPoint
    # [[0, 1337566253.89858, 0.000355720520019531], true]
    load --table Site
    [
     {"_key":"http://example.org/","location":"128452975x503157902"}
     {"_key":"http://example.net/","location":"128487316x502920929"},
    ]
    # [[0, 1337566253.89858, 0.000355720520019531], 2]
    select --table Site --query "_id:1 OR _id:2" --output_columns _key,location
    # [
    #   [
    #     0,
    #     1337566253.89858,
    #     0.000355720520019531
    #   ],
    #   [
    #     [
    #       [
    #         2
    #       ],
    #       [
    #         [
    #           "_key",
    #           "ShortText"
    #         ],
    #         [
    #           "location",
    #           "WGS84GeoPoint"
    #         ]
    #       ],
    #       [
    #         "http://example.org/",
    #         "128452975x503157902"
    #       ],
    #       [
    #         "http://example.net/",
    #         "128487316x502920929"
    #       ]
    #     ]
    #   ]
    # ]

    scorerパラメータにおいて、 /reference/functions/geo_distance 関数を用いることにより、２点間の距離を計算することができます。

    ここでは、秋葉原駅からの距離を表示させてみましょう。世界測地系では、秋葉原駅の位置は緯度が35度41分55.259秒、経度が139度46分27.188秒です。よって、geo_distance関数に与える文字列は"128515259x503187188"となります。

    Execution example:

    select --table Site --query "_id:1 OR _id:2" --output_columns _key,location,_score --scorer '_score = geo_distance(location, "128515259x503187188")'
    # [
    #   [
    #     0,
    #     1337566253.89858,
    #     0.000355720520019531
    #   ],
    #   [
    #     [
    #       [
    #         2
    #       ],
    #       [
    #         [
    #           "_key",
    #           "ShortText"
    #         ],
    #         [
    #           "location",
    #           "WGS84GeoPoint"
    #         ],
    #         [
    #           "_score",
    #           "Int32"
    #         ]
    #       ],
    #       [
    #         "http://example.org/",
    #         "128452975x503157902",
    #         2054
    #       ],
    #       [
    #         "http://example.net/",
    #         "128487316x502920929",
    #         6720
    #       ]
    #     ]
    #   ]
    # ]

    この結果を見ると、東京駅と秋葉原駅は2054m、秋葉原駅と新宿駅は6720m離れているようです。

    geo_distance関数は、_scoreを通じてソートでも用いることができます。

    Execution example:

    select --table Site --query "_id:1 OR _id:2" --output_columns _key,location,_score --scorer '_score = geo_distance(location, "128515259x503187188")' --sortby -_score
    # [
    #   [
    #     0,
    #     1337566253.89858,
    #     0.000355720520019531
    #   ],
    #   [
    #     [
    #       [
    #         2
    #       ],
    #       [
    #         [
    #           "_key",
    #           "ShortText"
    #         ],
    #         [
    #           "location",
    #           "WGS84GeoPoint"
    #         ],
    #         [
    #           "_score",
    #           "Int32"
    #         ]
    #       ],
    #       [
    #         "http://example.net/",
    #         "128487316x502920929",
    #         6720
    #       ],
    #       [
    #         "http://example.org/",
    #         "128452975x503157902",
    #         2054
    #       ]
    #     ]
    #   ]
    # ]

    「ある地点から何m以内に存在する」といった絞込も可能です。

    filterパラメータにおいて、 /reference/functions/geo_in_circle 関数を用いることにより、２点間の距離が指定のm以下におさまるかどうかを判定することができます。

    たとえば、秋葉原駅から5000m以内にあるレコードを検索してみましょう。

    Execution example:

    select --table Site --output_columns _key,location --filter 'geo_in_circle(location, "128515259x503187188", 5000)'
    # [
    #   [
    #     0,
    #     1337566253.89858,
    #     0.000355720520019531
    #   ],
    #   [
    #     [
    #       [
    #         1
    #       ],
    #       [
    #         [
    #           "_key",
    #           "ShortText"
    #         ],
    #         [
    #           "location",
    #           "WGS84GeoPoint"
    #         ]
    #       ],
    #       [
    #         "http://example.org/",
    #         "128452975x503157902"
    #       ]
    #     ]
    #   ]
    # ]

    また、経緯度が指定の矩形領域内であるかどうかを判定する /reference/functions/geo_in_rectangle 関数も存在します。

  ドリルダウン

groongaでは、特定のカラム値で検索結果をグループ化することができます。これをドリルダウンと呼びます。

Siteテーブルに２つのカラムを追加します。TLDドメイン名を格納するdomainカラムと、国名を格納するcountryカラムです。これらのカラムの型は、それぞれドメイン名を主キーとするSiteDomainテーブルと、国名を主キーとするSiteCountryテーブルとします。

Execution example:

table_create --name SiteDomain --flags TABLE_HASH_KEY --key_type ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
table_create --name SiteCountry --flags TABLE_HASH_KEY --key_type ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create --table Site --name domain --flags COLUMN_SCALAR --type SiteDomain
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create --table Site --name country --flags COLUMN_SCALAR --type SiteCountry
# [[0, 1337566253.89858, 0.000355720520019531], true]
load --table Site
[
{"_key":"http://example.org/","domain":".org","country":"japan"},
{"_key":"http://example.net/","domain":".net","country":"brazil"},
{"_key":"http://example.com/","domain":".com","country":"japan"},
{"_key":"http://example.net/afr","domain":".net","country":"usa"},
{"_key":"http://example.org/aba","domain":".org","country":"korea"},
{"_key":"http://example.com/rab","domain":".com","country":"china"},
{"_key":"http://example.net/atv","domain":".net","country":"china"},
{"_key":"http://example.org/gat","domain":".org","country":"usa"},
{"_key":"http://example.com/vdw","domain":".com","country":"japan"}
]
# [[0, 1337566253.89858, 0.000355720520019531], 9]

domainカラムとcountryカラムでドリルダウンを行う例を以下に示します。

Execution example:

select --table Site --limit 0 --drilldown domain
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         9
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "country",
#           "SiteCountry"
#         ],
#         [
#           "domain",
#           "SiteDomain"
#         ],
#         [
#           "link",
#           "Site"
#         ],
#         [
#           "links",
#           "Site"
#         ],
#         [
#           "location",
#           "WGS84GeoPoint"
#         ],
#         [
#           "title",
#           "ShortText"
#         ]
#       ]
#     ],
#     [
#       [
#         3
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "_nsubrecs",
#           "Int32"
#         ]
#       ],
#       [
#         ".org",
#         3
#       ],
#       [
#         ".net",
#         3
#       ],
#       [
#         ".com",
#         3
#       ]
#     ]
#   ]
# ]

テーブル型を持つカラムに対してドリルダウンを行った場合、参照先のテーブルに存在するカラム値を取得することもできます。ドリルダウンを行ったテーブルには、_nsubrecsという仮想的なカラムが追加されます。このカラムには、グループ化されたレコード数が入ります。

Execution example:

select --table Site --limit 0 --drilldown domain --drilldown_output_columns _id,_key,_nsubrecs
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         9
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "country",
#           "SiteCountry"
#         ],
#         [
#           "domain",
#           "SiteDomain"
#         ],
#         [
#           "link",
#           "Site"
#         ],
#         [
#           "links",
#           "Site"
#         ],
#         [
#           "location",
#           "WGS84GeoPoint"
#         ],
#         [
#           "title",
#           "ShortText"
#         ]
#       ]
#     ],
#     [
#       [
#         3
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "_nsubrecs",
#           "Int32"
#         ]
#       ],
#       [
#         1,
#         ".org",
#         3
#       ],
#       [
#         2,
#         ".net",
#         3
#       ],
#       [
#         3,
#         ".com",
#         3
#       ]
#     ]
#   ]
# ]

複数のカラムに対してドリルダウンを行うことができます。複数のカラムに対してドリルダウンを行う場合には、drilldownパラメータにカラム名をカンマ区切りで与えます。

Execution example:

select --table Site --limit 0 --drilldown domain,country
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         9
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "country",
#           "SiteCountry"
#         ],
#         [
#           "domain",
#           "SiteDomain"
#         ],
#         [
#           "link",
#           "Site"
#         ],
#         [
#           "links",
#           "Site"
#         ],
#         [
#           "location",
#           "WGS84GeoPoint"
#         ],
#         [
#           "title",
#           "ShortText"
#         ]
#       ]
#     ],
#     [
#       [
#         3
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "_nsubrecs",
#           "Int32"
#         ]
#       ],
#       [
#         ".org",
#         3
#       ],
#       [
#         ".net",
#         3
#       ],
#       [
#         ".com",
#         3
#       ]
#     ],
#     [
#       [
#         5
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "_nsubrecs",
#           "Int32"
#         ]
#       ],
#       [
#         "japan",
#         3
#       ],
#       [
#         "brazil",
#         1
#       ],
#       [
#         "usa",
#         2
#       ],
#       [
#         "korea",
#         1
#       ],
#       [
#         "china",
#         2
#       ]
#     ]
#   ]
# ]

ドリルダウン結果を並びかえることができます。例えば、_nsubrecsパラメータの降順で並び替えることができます。

Execution example:

select --table Site --limit 0 --drilldown country --drilldown_sortby _nsubrecs
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         9
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "country",
#           "SiteCountry"
#         ],
#         [
#           "domain",
#           "SiteDomain"
#         ],
#         [
#           "link",
#           "Site"
#         ],
#         [
#           "links",
#           "Site"
#         ],
#         [
#           "location",
#           "WGS84GeoPoint"
#         ],
#         [
#           "title",
#           "ShortText"
#         ]
#       ]
#     ],
#     [
#       [
#         5
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "_nsubrecs",
#           "Int32"
#         ]
#       ],
#       [
#         "brazil",
#         1
#       ],
#       [
#         "korea",
#         1
#       ],
#       [
#         "usa",
#         2
#       ],
#       [
#         "china",
#         2
#       ],
#       [
#         "japan",
#         3
#       ]
#     ]
#   ]
# ]

ドリルダウン結果は、デフォルトでは10件のみ表示されます。drilldown_offsetパラメータと、drilldown_limitパラメータによって、offsetとlimitを指定することができます。

Execution example:

select --table Site --limit 0 --drilldown country --drilldown_sortby _nsubrecs --drilldown_limit 2 --drilldown_offset 2
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         9
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "country",
#           "SiteCountry"
#         ],
#         [
#           "domain",
#           "SiteDomain"
#         ],
#         [
#           "link",
#           "Site"
#         ],
#         [
#           "links",
#           "Site"
#         ],
#         [
#           "location",
#           "WGS84GeoPoint"
#         ],
#         [
#           "title",
#           "ShortText"
#         ]
#       ]
#     ],
#     [
#       [
#         5
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "_nsubrecs",
#           "Int32"
#         ]
#       ],
#       [
#         "usa",
#         2
#       ],
#       [
#         "china",
#         2
#       ]
#     ]
#   ]
# ]

文字列型のカラムに対するドリルダウンは、他の型でのドリルダウンに比べて低速です。文字列でのドリルダウンを行いたい場合には、このチュートリアルのように、文字列型を主キーとするテーブルを別途作成し、そのテーブルを型とするカラムを作成します。

  タグ検索・参照関係の逆引き

本チュートリアルで、groongaはカラム値として他のテーブルへの参照の配列を持つことができることを紹介いたしました。実は、テーブルへの参照の配列データを用いることによって、いわゆるタグ検索を行うことが可能となります。

タグ検索はgroongaの転置インデックスというデータ構造を用いて高速に行われます。

  タグ検索

動画共有サイトの検索エンジンを作ることを想定します。1つの動画には、その動画の特徴を表す、複数の語句が付与されています。「ある語句が付与されている動画の一覧を取得する」検索を行いたいとします。

実際に、動画情報のテーブルを作成し、検索をしてみましょう。

動画の情報を保存する、Videoテーブルを作成します。Videoテーブルでは、動画のタイトルをtitleカラムに、動画のタグ情報をtagsカラムにTagテーブル型で複数格納しています。 タグの情報を保存する、Tagテーブルを作成します。Tagテーブルでは、タグ文字列を主キーに格納し、Videoテーブルのtagsカラムに対するインデックスをindex_tagsカラムに格納しています。

Execution example:

table_create --name Video --flags TABLE_HASH_KEY --key_type UInt32
# [[0, 1337566253.89858, 0.000355720520019531], true]
table_create --name Tag --flags TABLE_HASH_KEY --key_type ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create --table Video --name title --flags COLUMN_SCALAR --type ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create --table Video --name tags --flags COLUMN_VECTOR --type Tag
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create --table Tag --name index_tags --flags COLUMN_INDEX --type Video --source tags
# [[0, 1337566253.89858, 0.000355720520019531], true]
load --table Video
[
{"_key":1,"title":"Soccer 2010","tags":["Sports","Soccer"]},
{"_key":2,"title":"Zenigata Kinjirou","tags":["Variety","Money"]},
{"_key":3,"title":"groonga Demo","tags":["IT","Server","groonga"]},
{"_key":4,"title":"Moero!! Ultra Baseball","tags":["Sports","Baseball"]},
{"_key":5,"title":"Hex Gone!","tags":["Variety","Quiz"]},
{"_key":6,"title":"Pikonyan 1","tags":["Animation","Pikonyan"]},
{"_key":7,"title":"Draw 8 Month","tags":["Animation","Raccoon"]},
{"_key":8,"title":"K.O.","tags":["Animation","Music"]}
]
# [[0, 1337566253.89858, 0.000355720520019531], 8]

インデックスカラムを作成すると、全文検索が高速に行えるようになります。インデックスカラムは、対象のカラムに保存されたデータに更新があったとき、自動的に更新されます。

「ある語句が付与されている動画の一覧を取得する」検索を行いましょう。

Execution example:

select --table Video --query tags:@Variety --output_columns _key,title
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_key",
#           "UInt32"
#         ],
#         [
#           "title",
#           "ShortText"
#         ]
#       ],
#       [
#         2,
#         "Zenigata Kinjirou"
#       ],
#       [
#         5,
#         "Hex Gone!"
#       ]
#     ]
#   ]
# ]
select --table Video --query tags:@Sports --output_columns _key,title
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_key",
#           "UInt32"
#         ],
#         [
#           "title",
#           "ShortText"
#         ]
#       ],
#       [
#         1,
#         "Soccer 2010"
#       ],
#       [
#         4,
#         "Moero!! Ultra Baseball"
#       ]
#     ]
#   ]
# ]
select --table Video --query tags:@Animation --output_columns _key,title
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         3
#       ],
#       [
#         [
#           "_key",
#           "UInt32"
#         ],
#         [
#           "title",
#           "ShortText"
#         ]
#       ],
#       [
#         6,
#         "Pikonyan 1"
#       ],
#       [
#         7,
#         "Draw 8 Month"
#       ],
#       [
#         8,
#         "K.O."
#       ]
#     ]
#   ]
# ]

このように、「Variety」、「Sports」、「Animation」のようなタグで検索を行うことができました。

  参照関係の逆引き

groongaはテーブル間の参照関係の逆引きを高速に行うためのインデックスを付与することができます。タグ検索は、その1例にすぎません。

例えば、ソーシャルネットワーキングサイトにおける友人関係を逆引き検索することができます。

以下の例では、ユーザー情報を格納するUserテーブルを作成し、ユーザー名を格納するusernameカラム、ユーザーの友人一覧を配列で格納するfriendsカラムとそのインデックスのindex_friendsカラムを追加しています。

Execution example:

table_create --name User --flags TABLE_HASH_KEY --key_type ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create --table User --name username --flags COLUMN_SCALAR --type ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create --table User --name friends --flags COLUMN_VECTOR --type User
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create --table User --name index_friends --flags COLUMN_INDEX --type User --source friends
# [[0, 1337566253.89858, 0.000355720520019531], true]
load --table User
[
{"_key":"ken","username":"健作","friends":["taro","jiro","tomo","moritapo"]}
{"_key":"moritapo","username":"森田","friends":["ken","tomo"]}
{"_key":"taro","username":"ぐるんが太郎","friends":["jiro","tomo"]}
{"_key":"jiro","username":"ぐるんが次郎","friends":["taro","tomo"]}
{"_key":"tomo","username":"トモちゃん","friends":["ken","hana"]}
{"_key":"hana","username":"花子","friends":["ken","taro","jiro","moritapo","tomo"]}
]
# [[0, 1337566253.89858, 0.000355720520019531], 6]

指定したユーザーを友人リストに入れているユーザーの一覧を表示してみましょう。

Execution example:

select --table User --query friends:@tomo --output_columns _key,username
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         5
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "username",
#           "ShortText"
#         ]
#       ],
#       [
#         "ken",
#         "健作"
#       ],
#       [
#         "taro",
#         "ぐるんが太郎"
#       ],
#       [
#         "jiro",
#         "ぐるんが次郎"
#       ],
#       [
#         "moritapo",
#         "森田"
#       ],
#       [
#         "hana",
#         "花子"
#       ]
#     ]
#   ]
# ]
select --table User --query friends:@jiro --output_columns _key,username
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         3
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "username",
#           "ShortText"
#         ]
#       ],
#       [
#         "ken",
#         "健作"
#       ],
#       [
#         "taro",
#         "ぐるんが太郎"
#       ],
#       [
#         "hana",
#         "花子"
#       ]
#     ]
#   ]
# ]

さらに、ドリルダウンを使って、友人リストに入っている数の一覧を表示してみましょう。

Execution example:

select --table User --limit 0 --drilldown friends
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         6
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "friends",
#           "User"
#         ],
#         [
#           "index_friends",
#           "User"
#         ],
#         [
#           "username",
#           "ShortText"
#         ]
#       ]
#     ],
#     [
#       [
#         6
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "_nsubrecs",
#           "Int32"
#         ]
#       ],
#       [
#         "taro",
#         3
#       ],
#       [
#         "jiro",
#         3
#       ],
#       [
#         "tomo",
#         5
#       ],
#       [
#         "moritapo",
#         2
#       ],
#       [
#         "ken",
#         3
#       ],
#       [
#         "hana",
#         1
#       ]
#     ]
#   ]
# ]

このように、テーブルの参照関係を逆にたどる検索ができました。

  インデックス付きジオサーチ

位置情報のカラムに対して、インデックスを付与することが出来ます。大量の位置情報レコードを検索する場合に、検索速度が速くなります。

Execution example:

table_create --name GeoIndex --flags TABLE_PAT_KEY --key_type WGS84GeoPoint
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create --table GeoIndex --name index_point --type Site --flags COLUMN_INDEX --source location
# [[0, 1337566253.89858, 0.000355720520019531], true]
load --table Site
[
 {"_key":"http://example.org/","location":"128452975x503157902"},
 {"_key":"http://example.net/","location":"128487316x502920929"}
]
# [[0, 1337566253.89858, 0.000355720520019531], 2]
select --table Site --filter 'geo_in_circle(location, "128515259x503187188", 5000)' --output_columns _key,location
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "location",
#           "WGS84GeoPoint"
#         ]
#       ],
#       [
#         "http://example.org/",
#         "128452975x503157902"
#       ]
#     ]
#   ]
# ]

同様に、位置情報レコードを用いてソートする場合に、ソート速度が速くなります。

Execution example:

select --table Site --filter 'geo_in_circle(location, "128515259x503187188", 50000)' --output_columns _key,location,_score --sortby '-geo_distance(location, "128515259x503187188")' --scorer '_score = geo_distance(location, "128515259x503187188")'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "location",
#           "WGS84GeoPoint"
#         ],
#         [
#           "_score",
#           "Int32"
#         ]
#       ],
#       [
#         "http://example.org/",
#         "128452975x503157902",
#         2054
#       ],
#       [
#         "http://example.net/",
#         "128487316x502920929",
#         6720
#       ]
#     ]
#   ]
# ]

  match_columnsパラメータ

  複数のカラムを対象とした全文検索

groongaでは、複数のカラムを対象とした全文検索を行うことができます。例えば、ブログのテーブルで、タイトルと内容とがそれぞれ別のカラムに入ったものがあるとしましょう。「タイトルもしくは内容に特定の単語を含む」検索を行いたいとします。

この場合、2つのインデックス作成方式があります。1つは、それぞれのカラムに1つずつインデックスを付与する方式です。もう1つは、複数のカラムに対して1つのインデックスを付与する方式です。groongaでは、どちらの形式のインデックスが存在している場合でも、同一の記法で全文検索を行うことができます。

  カラムごとにインデックスを付与する場合

Blog1テーブルを作り、タイトル文字列のtitleカラム、本文のmessageカラムを追加しています。 インデックス用のIndexBlog1テーブルも作り、titleカラムのインデックス用にindex_titleカラム、messageカラムのインデック用にindex_messageカラムと、それぞれ1カラムごとに1つずつ追加しています。

Execution example:

table_create --name Blog1 --flags TABLE_HASH_KEY --key_type ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create --table Blog1 --name title --flags COLUMN_SCALAR --type ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create --table Blog1 --name message --flags COLUMN_SCALAR --type ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
table_create --name IndexBlog1 --flags TABLE_PAT_KEY|KEY_NORMALIZE --key_type ShortText --default_tokenizer TokenBigram
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create --table IndexBlog1 --name index_title --flags COLUMN_INDEX|WITH_POSITION --type Blog1 --source title
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create --table IndexBlog1 --name index_message --flags COLUMN_INDEX|WITH_POSITION --type Blog1 --source message
# [[0, 1337566253.89858, 0.000355720520019531], true]
load --table Blog1
[
{"_key":"grn1","title":"groonga test","message":"groonga message"},
{"_key":"grn2","title":"baseball result","message":"rakutan eggs 4 - 4 groonga moritars"},
{"_key":"grn3","title":"groonga message","message":"none"}
]
# [[0, 1337566253.89858, 0.000355720520019531], 3]

match_columnsオプションで、検索対象のカラムを複数指定することが出来ます。検索する文字列はqueryオプションで指定します。これを使うことで、タイトルと本文を全文検索することができます。

実際に検索してみましょう。

Execution example:

select --table Blog1 --match_columns title||message --query groonga
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         3
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "message",
#           "ShortText"
#         ],
#         [
#           "title",
#           "ShortText"
#         ]
#       ],
#       [
#         1,
#         "grn1",
#         "groonga message",
#         "groonga test"
#       ],
#       [
#         3,
#         "grn3",
#         "none",
#         "groonga message"
#       ],
#       [
#         2,
#         "grn2",
#         "rakutan eggs 4 - 4 groonga moritars",
#         "baseball result"
#       ]
#     ]
#   ]
# ]
select --table Blog1 --match_columns title||message --query message
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "message",
#           "ShortText"
#         ],
#         [
#           "title",
#           "ShortText"
#         ]
#       ],
#       [
#         3,
#         "grn3",
#         "none",
#         "groonga message"
#       ],
#       [
#         1,
#         "grn1",
#         "groonga message",
#         "groonga test"
#       ]
#     ]
#   ]
# ]
select --table Blog1 --match_columns title --query message
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "message",
#           "ShortText"
#         ],
#         [
#           "title",
#           "ShortText"
#         ]
#       ],
#       [
#         3,
#         "grn3",
#         "none",
#         "groonga message"
#       ]
#     ]
#   ]
# ]

  複数のカラムにまたがったインデックスを付与する場合

内容は上の例とほぼ同じですが、titleとmessageの2つのカラムに対するインデックスが共通になっており、インデックスカラムが1つしかありません。

共通のインデックスを用いても、titleカラムのみでの検索、messageカラムのみでの検索、titleもしくはmessageカラムでの検索、全ての検索を行うことができます。

Execution example:

table_create --name Blog2 --flags TABLE_HASH_KEY --key_type ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create --table Blog2 --name title --flags COLUMN_SCALAR --type ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create --table Blog2 --name message --flags COLUMN_SCALAR --type ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
table_create --name IndexBlog2 --flags TABLE_PAT_KEY|KEY_NORMALIZE --key_type ShortText --default_tokenizer TokenBigram
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create --table IndexBlog2 --name index_blog --flags COLUMN_INDEX|WITH_POSITION|WITH_SECTION --type Blog2 --source title,message
# [[0, 1337566253.89858, 0.000355720520019531], true]
load --table Blog2
[
{"_key":"grn1","title":"groonga test","message":"groonga message"},
{"_key":"grn2","title":"baseball result","message":"rakutan eggs 4 - 4 groonga moritars"},
{"_key":"grn3","title":"groonga message","message":"none"}
]
# [[0, 1337566253.89858, 0.000355720520019531], 3]

実際に検索してみましょう。結果は上の例と同じになります。

Execution example:

select --table Blog2 --match_columns title||message --query groonga
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         3
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "message",
#           "ShortText"
#         ],
#         [
#           "title",
#           "ShortText"
#         ]
#       ],
#       [
#         1,
#         "grn1",
#         "groonga message",
#         "groonga test"
#       ],
#       [
#         2,
#         "grn2",
#         "rakutan eggs 4 - 4 groonga moritars",
#         "baseball result"
#       ],
#       [
#         3,
#         "grn3",
#         "none",
#         "groonga message"
#       ]
#     ]
#   ]
# ]
select --table Blog2 --match_columns title||message --query message
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "message",
#           "ShortText"
#         ],
#         [
#           "title",
#           "ShortText"
#         ]
#       ],
#       [
#         1,
#         "grn1",
#         "groonga message",
#         "groonga test"
#       ],
#       [
#         3,
#         "grn3",
#         "none",
#         "groonga message"
#       ]
#     ]
#   ]
# ]
select --table Blog2 --match_columns title --query message
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "message",
#           "ShortText"
#         ],
#         [
#           "title",
#           "ShortText"
#         ]
#       ],
#       [
#         3,
#         "grn3",
#         "none",
#         "groonga message"
#       ]
#     ]
#   ]
# ]

  インデックス名を指定した全文検索

執筆中です。

  Nested index search among related table by column index

If there are relationships among multiple table with column index, you can search multiple table by specifying reference column name.

Here is the concrete example.

There are tables which store blog articles, comments for articles. The table which stores articles has columns for article and comment. And the comment column refers Comments table. The table which stores comments has columns for comment and column index to article table.

if you want to search the articles which contain specified keyword in comment, you need to execute fulltext search for table of comment, then search the records which contains fulltext search results.

But, you can search the records by specifying the reference column index at once.

Here is the sample schema.

Execution example:

table_create Comments TABLE_HASH_KEY UInt32
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Comments content COLUMN_SCALAR ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
table_create Articles TABLE_NO_KEY
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Articles content COLUMN_SCALAR Text
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Articles comment COLUMN_SCALAR Comments
# [[0, 1337566253.89858, 0.000355720520019531], true]
table_create Lexicon TABLE_PAT_KEY|KEY_NORMALIZE ShortText --default_tokenizer TokenBigram
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Lexicon articles_content COLUMN_INDEX|WITH_POSITION Articles content
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Lexicon comments_content COLUMN_INDEX|WITH_POSITION Comments content
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Comments article COLUMN_INDEX Articles comment
# [[0, 1337566253.89858, 0.000355720520019531], true]

Here is the sample data.

Execution example:

load --table Comments
[
{"_key": 1, "content": "I'm using groonga too!"},
{"_key": 2, "content": "I'm using groonga and mroonga!"},
{"_key": 3, "content": "I'm using mroonga too!"}
]
# [[0, 1337566253.89858, 0.000355720520019531], 3]
load --table Articles
[
{"content": "Groonga is fast!", "comment": 1},
{"content": "Groonga is useful!"},
{"content": "Mroonga is fast!", "comment": 3}
]
# [[0, 1337566253.89858, 0.000355720520019531], 3]

You can write the query that search the records which contains specified keyword as a comment, then fetch the articles which refers to it.

Query for searching the records described above:

select Articles --match_columns comment.content --query groonga --output_columns "_id, _score, *"

You need to concatenate comment column of Articles table and content column of Comments table with period(.) as --match_columns arguments.

At first, this query execute fulltext search from content of Comments table, then fetch the records of Articles table which refers to already searched records of Comments table. (Because of this, if you comment out the query which create column index 'article' of Comments table, you can't get intended search results.)

Execution example:

select Articles --match_columns comment.content --query groonga --output_columns "_id, _score, *"
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_score",
#           "Int32"
#         ],
#         [
#           "comment",
#           "Comments"
#         ],
#         [
#           "content",
#           "Text"
#         ]
#       ],
#       [
#         1,
#         1,
#         1,
#         "Groonga is fast!"
#       ]
#     ]
#   ]
# ]

Now, you can search articles which contains specific keywords as a comment.

The feature of nested index search is not limited to the relationship between two table only.

Here is the sample schema similar to previous one. The difference is added table which express 'Reply' and relationship is extended to three tables.

Execution example:

table_create Replies2 TABLE_HASH_KEY UInt32
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Replies2 content COLUMN_SCALAR ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
table_create Comments2 TABLE_HASH_KEY UInt32
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Comments2 content COLUMN_SCALAR ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Comments2 comment COLUMN_SCALAR Replies2
# [[0, 1337566253.89858, 0.000355720520019531], true]
table_create Articles2 TABLE_NO_KEY
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Articles2 content COLUMN_SCALAR Text
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Articles2 comment COLUMN_SCALAR Comments2
# [[0, 1337566253.89858, 0.000355720520019531], true]
table_create Lexicon2 TABLE_PAT_KEY|KEY_NORMALIZE ShortText --default_tokenizer TokenBigram
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Lexicon2 articles_content COLUMN_INDEX|WITH_POSITION Articles2 content
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Lexicon2 comments_content COLUMN_INDEX|WITH_POSITION Comments2 content
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Lexicon2 replies_content COLUMN_INDEX|WITH_POSITION Replies2 content
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Comments2 article COLUMN_INDEX Articles2 comment
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Replies2 reply_to COLUMN_INDEX Comments2 comment
# [[0, 1337566253.89858, 0.000355720520019531], true]

Here is the sample data.

Execution example:

load --table Replies2
[
{"_key": 1, "content": "I'm using rroonga too!"},
{"_key": 2, "content": "I'm using groonga and mroonga and rroonga!"},
{"_key": 3, "content": "I'm using nroonga too!"}
]
# [[0, 1337566253.89858, 0.000355720520019531], 3]
load --table Comments2
[
{"_key": 1, "content": "I'm using groonga too!", "comment": 1},
{"_key": 2, "content": "I'm using groonga and mroonga!", "comment": 2},
{"_key": 3, "content": "I'm using mroonga too!"}
]
# [[0, 1337566253.89858, 0.000355720520019531], 3]
load --table Articles2
[
{"content": "Groonga is fast!", "comment": 1},
{"content": "Groonga is useful!", "comment": 2},
{"content": "Mroonga is fast!", "comment": 3}
]
# [[0, 1337566253.89858, 0.000355720520019531], 3]

Query for searching the records described above:

select Articles2 --match_columns comment.content --query mroonga --output_columns "_id, _score, *"
select Articles2 --match_columns comment.comment.content --query mroonga --output_columns "_id, _score, *"

The first query searches 'mroonga' from Comments2 table, the second one searches 'mroonga' from Replies2 and Comment2 table by using reference column index.

Execution example:

select Articles2 --match_columns comment.content --query mroonga --output_columns "_id, _score, *"
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_score",
#           "Int32"
#         ],
#         [
#           "comment",
#           "Comments2"
#         ],
#         [
#           "content",
#           "Text"
#         ]
#       ],
#       [
#         2,
#         1,
#         2,
#         "Groonga is useful!"
#       ],
#       [
#         3,
#         1,
#         3,
#         "Mroonga is fast!"
#       ]
#     ]
#   ]
# ]
select Articles2 --match_columns comment.comment.content --query mroonga --output_columns "_id, _score, *"
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_score",
#           "Int32"
#         ],
#         [
#           "comment",
#           "Comments2"
#         ],
#         [
#           "content",
#           "Text"
#         ]
#       ],
#       [
#         2,
#         1,
#         2,
#         "Groonga is useful!"
#       ]
#     ]
#   ]
# ]

As a result, the first query matches two article because of Comments2 table has two records which contains 'mroonga' as keyword.

On the other hand, the second one matches one article only because of Replies2 table has only one record which contains 'mroonga' as keyword, and there is one record which contains same keyword and refers to the record in Comments2 table.

  インデックスの重み

執筆中です。

  パトリシア木による前方一致検索

groongaのテーブルは、テーブル作成時にパトリシア木オプションを指定すると、前方一致検索を行うことができます。また、追加のオプションを指定することにより、主キーの後方一致検索をも行うことができます。

  主キーによる前方一致検索

table_createコマンドのflagsオプションにTABLE_PAT_KEYを指定することで、主キーによる前方一致検索ができるようになります。

Execution example:

table_create --name PatPrefix --flags TABLE_PAT_KEY --key_type ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
load --table PatPrefix
[
{"_key":"ひろゆき"},
{"_key":"まろゆき"},
{"_key":"ひろあき"},
{"_key":"ゆきひろ"}
]
# [[0, 1337566253.89858, 0.000355720520019531], 4]
select --table PatPrefix --query _key:^ひろ
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ]
#       ],
#       [
#         1,
#         "ひろゆき"
#       ],
#       [
#         3,
#         "ひろあき"
#       ]
#     ]
#   ]
# ]

  主キーによる後方一致検索

table_createコマンドのflagsオプションにTABLE_PAT_KEYとKEY_WITH_SISを指定することで、主キーによる前方一致検索・後方一致検索の両方が可能となります。

KEY_WITH_SISフラグを付与すると、データを追加する際に後方一致用のレコードも追加されてしまいます。そのため、単純に検索すると、元のレコードに加えて自動的に追加されたレコードまでヒットしてしまいます。元のレコードのみ検索するために、一工夫必要になります。

例えば、元のレコードと自動的に追加されたレコードとの区別をつけるために、元のレコードであることを示すoriginalカラムを追加して、検索時にはoriginalカラムが true も検索条件に加えます。 --query オプションでは Bool 型の値を直感的に指定することができないので --filter オプションを使っていることに注意してください。

Execution example:

table_create --name PatSuffix --flags TABLE_PAT_KEY|KEY_WITH_SIS --key_type ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create --table PatSuffix --name original --type Bool
# [[0, 1337566253.89858, 0.000355720520019531], true]
load --table PatSuffix
[
{"_key":"ひろゆき","original":true},
{"_key":"まろゆき","original":true},
{"_key":"ひろあき","original":true},
{"_key":"ゆきひろ","original":true}
]
# [[0, 1337566253.89858, 0.000355720520019531], 4]
select --table PatSuffix --query _key:$ゆき
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         4
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "original",
#           "Bool"
#         ]
#       ],
#       [
#         3,
#         "ゆき",
#         false
#       ],
#       [
#         2,
#         "ろゆき",
#         false
#       ],
#       [
#         5,
#         "まろゆき",
#         true
#       ],
#       [
#         1,
#         "ひろゆき",
#         true
#       ]
#     ]
#   ]
# ]
select --table PatSuffix --filter '_key @$ "ゆき" && original == true'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "original",
#           "Bool"
#         ]
#       ],
#       [
#         5,
#         "まろゆき",
#         true
#       ],
#       [
#         1,
#         "ひろゆき",
#         true
#       ]
#     ]
#   ]
# ]

  全文検索の語彙表に対する追加情報

groongaでは、全文検索に用いるための語意表がテーブルとして扱えます。よって、語彙ごとに複数の情報を保持することができます。例えば、語彙の出現数や検索ストップワードのフラグ、単語の重要度などを保持することができます。

この項目については、現在執筆中です。

  マイクロブログ検索システムの作成

これまで学んだgroongaの機能を用いて、マイクロブログの検索システムを作成してみましょう。マイクロブログとは、Twitterのような短いメッセージを投稿するブログです。

  テーブルの作成

まずは、テーブルを作成します。

table_create --name Users --flags TABLE_HASH_KEY --key_type ShortText
table_create --name Comments --flags TABLE_HASH_KEY --key_type ShortText
table_create --name HashTags --flags TABLE_HASH_KEY --key_type ShortText
table_create --name Bigram --flags TABLE_PAT_KEY|KEY_NORMALIZE --key_type ShortText --default_tokenizer TokenBigram
column_create --table Users --name name --flags COLUMN_SCALAR --type ShortText
column_create --table Users --name follower --flags COLUMN_VECTOR --type Users
column_create --table Users --name favorites --flags COLUMN_VECTOR --type Comments
column_create --table Users --name location --flags COLUMN_SCALAR --type WGS84GeoPoint
column_create --table Users --name location_str --flags COLUMN_SCALAR --type ShortText
column_create --table Users --name description --flags COLUMN_SCALAR --type ShortText
column_create --table Users --name followee --flags COLUMN_INDEX --type Users --source follower
column_create --table Comments --name comment --flags COLUMN_SCALAR --type ShortText
column_create --table Comments --name last_modified --flags COLUMN_SCALAR --type Time
column_create --table Comments --name replied_to --flags COLUMN_SCALAR --type Comments
column_create --table Comments --name replied_users --flags COLUMN_VECTOR --type Users
column_create --table Comments --name hash_tags --flags COLUMN_VECTOR --type HashTags
column_create --table Comments --name location --flags COLUMN_SCALAR --type WGS84GeoPoint
column_create --table Comments --name posted_by --flags COLUMN_SCALAR --type Users
column_create --table Comments --name favorited_by --flags COLUMN_INDEX --type Users --source favorites
column_create --table HashTags --name hash_index --flags COLUMN_INDEX --type Comments --source hash_tags
column_create --table Bigram --name users_index --flags COLUMN_INDEX|WITH_POSITION|WITH_SECTION --type Users --source name,location_str,description
column_create --table Bigram --name comment_index --flags COLUMN_INDEX|WITH_POSITION --type Comments --source comment

  Usersテーブル

ユーザーの名前や自己紹介文、フォローしているユーザー一覧など、ユーザー情報を格納するためのテーブルです。

_key
    ユーザーID

name
    ユーザー名

follower
    フォローしているユーザーの一覧

favorites
    お気に入りのコメント一覧

location
    ユーザーの現在地（緯度経度座標）

location_str
    ユーザーの現在地（文字列）

description
    ユーザーの自己紹介

followee
    Usersテーブルのfollowerカラムに対するインデックス。 このインデックスを作ることで、あるユーザーをフォローしているユーザーを検索できるようになります。

  Commentsテーブル

コメント内容や投稿日時、返信先情報など、コメントに関する内容を格納するテーブルです。

_key
    コメントID

comment
    コメント内容

last_modified
    投稿日時

replied_to
    返信元のコメント内容

replied_users
    返信先のユーザーの一覧

hash_tags
    コメントのハッシュタグの一覧

location
    投稿場所(緯度経度座標のため)

posted_by
    コメントを書いたユーザー

favorited_by
    Usersテーブルのfavoritesカラムに対するインデックス。 このインデックスを作ることで、指定したコメントを誰がお気に入りに入れているのかを検索できるようになります。

  HashTagsテーブル

コメントのハッシュタグを一覧で保存するためのテーブルです。

_key
    ハッシュタグ

hash_index
    「Comments.hash_tags」のインデックス。 このインデックスを作ることで、指定したハッシュタグのついているコメントの一覧を出すことが出来るようになります。

  Bigramテーブル

ユーザー情報・コメントで全文検索が出来るようにするためのインデックスを格納するテーブルです。

_key
    単語

users_index
    ユーザー情報のインデックス。 このカラムは、ユーザー名「Users.name」、現在地「Users.location_str」、自己紹介文「Users.description」のインデックスになっています。

comment_index
    コメント内容「Comments.comment」のインデックス

  データのロード

つづいて、テスト用データをロードします。

load --table Users
[
  {
    "_key": "daijiro",
    "name": "hsiomaneki",
    "follower": ["tasukuchan"],
    "favorites": [],
    "location": "127678039x502643091",
    "location_str": "神奈川県",
    "description": "groonga developer"
  },
  {
    "_key": "tasukuchan",
    "name": "グニャラくん",
    "follower": ["daijiro","OffGao"],
    "favorites": ["daijiro:1","OffGao:1"],
    "location": "128423343x502929252",
    "location_str": "東京都渋谷区",
    "description": "エロいおっさん"
  },
  {
    "_key": "OffGao",
    "name": "OffGao",
    "follower": ["tasukuchan","daijiro"],
    "favorites": ["tasukuchan:1","daijiro:1"],
    "location": "128544408x502801502",
    "location_str": "東京都中野区",
    "description": "がおがお"
  }
]
load --table Comments
[
  {
    "_key": "daijiro:1",
    "comment": "マイクロブログ作ってみました（甘栗むいちゃいました的な感じで）。",
    "last_modified": "2010/03/17 12:05:00",
    "posted_by": "daijiro",
  },
  {
    "_key": "tasukuchan:1",
    "comment": "初の書き込み。テストテスト。",
    "last_modified": "2010/03/17 12:00:00",
    "posted_by": "tasukuchan",
  },
  {
    "_key": "daijiro:2",
    "comment": "@tasukuchan ようこそ!!!",
    "last_modified": "2010/03/17 12:05:00",
    "replied_to": "tasukuchan:1",
    "replied_users": ["tasukuchan"],
    "posted_by": "daijiro",
  },
  {
    "_key": "tasukuchan:2",
    "comment": "@daijiro ありがとう！",
    "last_modified": "2010/03/17 13:00:00",
    "replied_to": "daijiro:2",
    "replied_users": ["daijiro"],
    "posted_by": "tasukuchan",
  },
  {
    "_key": "tasukuchan:3",
    "comment": "groongaなう #groonga",
    "last_modified": "2010/03/17 14:00:00",
    "hash_tags": ["groonga"],
    "location": "127972422x503117107",
    "posted_by": "tasukuchan",
  },
  {
    "_key": "tasukuchan:4",
    "comment": "groonga開発合宿のため羽田空港に来ました！ #groonga #travel",
    "last_modified": "2010/03/17 14:05:00",
    "hash_tags": ["groonga", "travel"],
    "location": "127975798x502919856",
    "posted_by": "tasukuchan",
  },
  {
    "_key": "OffGao:1",
    "comment": "@daijiro @tasukuchan 登録してみましたよー！",
    "last_modified": "2010/03/17 15:00:00",
    "replied_users": ["daijiro", "tasukuchan"],
    "location": "128551935x502796433",
    "posted_by": "OffGao",
  }
  {
    "_key": "OffGao:2",
    "comment": "中野ブロードウェイなうなう",
    "last_modified": "2010/03/17 15:05:00",
    "location": "128551935x502796434",
    "posted_by": "OffGao",
  }
]

Usersテーブルのfollowerカラムとfavoritesカラム、そしてCommentsテーブルのreplied_usersカラムは、ベクターカラムです。そのため、これらのカラムは配列で値を指定します。

Usersテーブルのlocationカラムと、Commentsテーブルのlocationカラムは、GeoPoint型です。この型での値の指定は、"[緯度]x[経度]"と記述して指定します。

Commentsテーブルのlast_modifiedカラムは、Time型です。この型での値を指定する方法は2つあります。 1つ目の方法は、1970年1月1日0時0分0秒からの経過秒数の値を直接指定する方法です。このとき、小数部分を指定することでマイクロ秒数での指定が可能です。指定した値は、データのロードの際にマイクロ秒を単位とする整数値に変換後、格納されます。 2つ目の方法は、文字列で日時と時刻を指定する方法です。"年/月/日 時:分:秒"というフォーマットで記述することで、データロードの際に文字列からキャストされ、マイクロ秒数の値が格納されます。

  検索

それでは、実際に検索をしてみましょう。

  キーワードでユーザー検索

ここでは、 match_columns で扱った、複数カラムを対象とした検索を行います。 指定された文字列で、ユーザー名・現在地・自己紹介文を対象に検索をします。

Execution example:

select --table Users --match_columns name,location_str,description --query 東京 --output_columns _key,name
# [[0, 1337566253.89858, 0.000355720520019531], true]
# [[0, 1337566253.89858, 0.000355720520019531], true]
# [[0, 1337566253.89858, 0.000355720520019531], true]
# [[0, 1337566253.89858, 0.000355720520019531], true]
# [[0, 1337566253.89858, 0.000355720520019531], true]
# [[0, 1337566253.89858, 0.000355720520019531], true]
# [[0, 1337566253.89858, 0.000355720520019531], true]
# [[0, 1337566253.89858, 0.000355720520019531], true]
# [[0, 1337566253.89858, 0.000355720520019531], true]
# [[0, 1337566253.89858, 0.000355720520019531], true]
# [[0, 1337566253.89858, 0.000355720520019531], true]
# [[0, 1337566253.89858, 0.000355720520019531], true]
# [[0, 1337566253.89858, 0.000355720520019531], true]
# [[0, 1337566253.89858, 0.000355720520019531], true]
# [[0, 1337566253.89858, 0.000355720520019531], true]
# [[0, 1337566253.89858, 0.000355720520019531], true]
# [[0, 1337566253.89858, 0.000355720520019531], true]
# [[0, 1337566253.89858, 0.000355720520019531], true]
# [[0, 1337566253.89858, 0.000355720520019531], true]
# [[0, 1337566253.89858, 0.000355720520019531], true]
# [[0, 1337566253.89858, 0.000355720520019531], true]
# [[0, 1337566253.89858, 0.000355720520019531], true]
# [[0, 1337566253.89858, 0.000355720520019531], 3]
# [[0, 1337566253.89858, 0.000355720520019531], 8]
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "name",
#           "ShortText"
#         ]
#       ],
#       [
#         "tasukuchan",
#         "グニャラくん"
#       ],
#       [
#         "OffGao",
#         "OffGao"
#       ]
#     ]
#   ]
# ]

「東京」をキーワードにユーザー検索した結果、東京都に住んでいる「グニャラくん」と「OffGao」がヒットしました。

  GeoPointでユーザー検索

ここでは、 search で扱った、GeoPoint型のカラムで検索をします。 以下の例では、指定された位置から5000m以内にいるユーザーを検索しています。

Execution example:

select --table Users --filter 'geo_in_circle(location,"128484216x502919856",5000)' --output_columns _key,name
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "name",
#           "ShortText"
#         ]
#       ],
#       [
#         "tasukuchan",
#         "グニャラくん"
#       ],
#       [
#         "OffGao",
#         "OffGao"
#       ]
#     ]
#   ]
# ]

新宿駅から5km以内にすんでいるユーザーを検索したところ、「グニャラくん」と「OffGao」がヒットしました。

  あるユーザーをフォローしているユーザーの検索

ここでは、 index で扱った、参照関係の逆引きをします。 以下の例では、Usersテーブルのfollowerカラムにあるフォローリストを逆引きします。

Execution example:

select --table Users --query follower:@tasukuchan --output_columns _key,name
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "name",
#           "ShortText"
#         ]
#       ],
#       [
#         "daijiro",
#         "hsiomaneki"
#       ],
#       [
#         "OffGao",
#         "OffGao"
#       ]
#     ]
#   ]
# ]

「グニャラくん」をフォローしている「hsiomaneki」と「OffGao」がヒットしました。

  GeoPointでコメント検索

ある範囲内で書かれたコメントを検索します。 また、 drilldown で扱ったドリルダウンも行います。検索結果をハッシュタグとユーザーでドリルダウンし、ユーザー別・ハッシュタグ別のカウントを出します。

Execution example:

select --table Comments --filter 'geo_in_circle(location,"127975798x502919856",20000)' --output_columns posted_by.name,comment --drilldown hash_tags,posted_by
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         4
#       ],
#       [
#         [
#           "posted_by.name",
#           "ShortText"
#         ],
#         [
#           "comment",
#           "ShortText"
#         ]
#       ],
#       [
#         "OffGao",
#         "@daijiro @tasukuchan 登録してみましたよー！"
#       ],
#       [
#         "グニャラくん",
#         "groongaなう #groonga"
#       ],
#       [
#         "グニャラくん",
#         "groonga開発合宿のため羽田空港に来ました！ #groonga #travel"
#       ],
#       [
#         "OffGao",
#         "中野ブロードウェイなうなう"
#       ]
#     ],
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "_nsubrecs",
#           "Int32"
#         ]
#       ],
#       [
#         "groonga",
#         2
#       ],
#       [
#         "travel",
#         1
#       ]
#     ],
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "_nsubrecs",
#           "Int32"
#         ]
#       ],
#       [
#         "OffGao",
#         2
#       ],
#       [
#         "tasukuchan",
#         2
#       ]
#     ]
#   ]
# ]

範囲を広く指定したため、位置情報のあるすべてのコメントがヒットしました。そして、ヒットしたコメントからドリルダウンされた結果も返ってきており、ハッシュタグは「#groonga」が2つに「#travel」が1つ、投稿者は「グニャラくん」「OffGao」がそれぞれ2件ずつであることがわかります。

  キーワードでコメント検索

あるキーワードを含むコメントを検索します。 さらに、 search で扱った、スコア値_scoreも出してみましょう。

Execution example:

select --table Comments --query comment:@なう --output_columns comment,_score
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "comment",
#           "ShortText"
#         ],
#         [
#           "_score",
#           "Int32"
#         ]
#       ],
#       [
#         "groongaなう #groonga",
#         1
#       ],
#       [
#         "中野ブロードウェイなうなう",
#         2
#       ]
#     ]
#   ]
# ]

「なう」をキーワードにコメント検索した結果、2件のコメントがヒットしました。また、_scoreの値も返ってきており、「なう」の数が出力されていることが確認できます。

  GeoPointとキーワードでコメント検索

今度は、キーワードとGeoPointの両方を条件に検索をしてみます。--queryと--filterの両方を使用した場合、両方の条件に一致するレコードがヒットします。

Execution example:

select --table Comments --query comment:@羽田 --filter 'geo_in_circle(location,"127975798x502919856",20000)' --output_columns posted_by.name,comment --drilldown hash_tags,posted_by
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "posted_by.name",
#           "ShortText"
#         ],
#         [
#           "comment",
#           "ShortText"
#         ]
#       ],
#       [
#         "グニャラくん",
#         "groonga開発合宿のため羽田空港に来ました！ #groonga #travel"
#       ]
#     ],
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "_nsubrecs",
#           "Int32"
#         ]
#       ],
#       [
#         "groonga",
#         1
#       ],
#       [
#         "travel",
#         1
#       ]
#     ],
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "_nsubrecs",
#           "Int32"
#         ]
#       ],
#       [
#         "tasukuchan",
#         1
#       ]
#     ]
#   ]
# ]

両方の条件を満たすコメントが1件ヒットしました。また、ドリルダウンの結果も返ってきており、「グニャラくん」のコメント1件であることがわかります。

  ハッシュタグでコメント検索

あるハッシュタグのついているコメントを検索します。 これも、 index で扱った、参照関係の逆引きを使います。

Execution example:

select --table Comments --query hash_tags:@groonga --output_columns posted_by.name,comment --drilldown posted_by
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "posted_by.name",
#           "ShortText"
#         ],
#         [
#           "comment",
#           "ShortText"
#         ]
#       ],
#       [
#         "グニャラくん",
#         "groongaなう #groonga"
#       ],
#       [
#         "グニャラくん",
#         "groonga開発合宿のため羽田空港に来ました！ #groonga #travel"
#       ]
#     ],
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "_nsubrecs",
#           "Int32"
#         ]
#       ],
#       [
#         "tasukuchan",
#         2
#       ]
#     ]
#   ]
# ]

#groongaタグの付いている2件のコメントがヒットしました。また、投稿者のドリルダウンも返ってきており、2件とも「グニャラくん」のものであることがわかります。

  ユーザーIDでコメント検索

あるユーザーが投稿したコメントを検索します。

Execution example:

select --table Comments --query posted_by:tasukuchan --output_columns comment --drilldown hash_tags
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         4
#       ],
#       [
#         [
#           "comment",
#           "ShortText"
#         ]
#       ],
#       [
#         "初の書き込み。テストテスト。"
#       ],
#       [
#         "@daijiro ありがとう！"
#       ],
#       [
#         "groongaなう #groonga"
#       ],
#       [
#         "groonga開発合宿のため羽田空港に来ました！ #groonga #travel"
#       ]
#     ],
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "_nsubrecs",
#           "Int32"
#         ]
#       ],
#       [
#         "groonga",
#         2
#       ],
#       [
#         "travel",
#         1
#       ]
#     ]
#   ]
# ]

「グニャラくん」が書き込んだ4件のコメントがヒットしました。また、ハッシュタグでドリルダウンした結果も返ってきており、ハッシュタグは「#groonga」が2つに「#travel」が1つあることがわかります。

  ユーザーのお気に入りコメントを検索

あるユーザーがお気に入りに入れているコメントを検索します。

Execution example:

select --table Users --query _key:tasukuchan --output_columns favorites.posted_by,favorites.comment
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "favorites.posted_by",
#           "Users"
#         ],
#         [
#           "favorites.comment",
#           "ShortText"
#         ]
#       ],
#       [
#         [
#           "daijiro",
#           "OffGao"
#         ],
#         [
#           "マイクロブログ作ってみました（甘栗むいちゃいました的な感じで）。",
#           "@daijiro @tasukuchan 登録してみましたよー！"
#         ]
#       ]
#     ]
#   ]
# ]

「グニャラくん」がお気に入りに入れている2件のコメントがヒットしました。

  投稿時間でコメント検索

コメントの投稿時間で検索をします。Time型については data で扱っています。 この例では、指定した時間よりも前に投稿されているコメントを検索します。

Execution example:

select Comments --filter 'last_modified<=1268802000' --output_columns posted_by.name,comment,last_modified --drilldown hash_tags,posted_by
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         5
#       ],
#       [
#         [
#           "posted_by.name",
#           "ShortText"
#         ],
#         [
#           "comment",
#           "ShortText"
#         ],
#         [
#           "last_modified",
#           "Time"
#         ]
#       ],
#       [
#         "hsiomaneki",
#         "マイクロブログ作ってみました（甘栗むいちゃいました的な感じで）。",
#         1268795100.0
#       ],
#       [
#         "グニャラくん",
#         "初の書き込み。テストテスト。",
#         1268794800.0
#       ],
#       [
#         "hsiomaneki",
#         "@tasukuchan ようこそ!!!",
#         1268795100.0
#       ],
#       [
#         "グニャラくん",
#         "@daijiro ありがとう！",
#         1268798400.0
#       ],
#       [
#         "グニャラくん",
#         "groongaなう #groonga",
#         1268802000.0
#       ]
#     ],
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "_nsubrecs",
#           "Int32"
#         ]
#       ],
#       [
#         "groonga",
#         1
#       ]
#     ],
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "_nsubrecs",
#           "Int32"
#         ]
#       ],
#       [
#         "daijiro",
#         2
#       ],
#       [
#         "tasukuchan",
#         3
#       ]
#     ]
#   ]
# ]

2010/03/17 14:00:00以前に書かれたコメント5件がヒットしました。また、ドリルダウンの結果も返ってきており、「hsiomaneki」が2件、「グニャラくん」が3件ヒットしていることがわかります。

  クエリ拡張

groongaでは、 /reference/commands/select コマンドにquery_expansionパラメータを指定することによって、ユーザが指定した検索文字列を適宜拡張することが可能です。

たとえば、ユーザが'シークヮーサー'という文字列で検索した場合に、'シークヮーサー OR シークァーサー'で検索した場合と同一の結果を返すことによって、本来ユーザが必要とする結果をよりもれなく検索できるようになります。

  準備

クエリ拡張機能を使用するためには、検索対象となる文書を格納するテーブル(ここでは文書テーブルと呼びます)以外に、ユーザの指定した検索文字列を置換するためのテーブル(ここでは置換テーブルと呼びます)を準備します。置換テーブルでは、その主キーが置換前の文字列となり、文字列型(ShortText)のカラムの値が置換後の文字列となります。

TODO: 文字列型のベクターカラムでも可能であり、その場合は各要素をORでつなげたものに置換されるということを記述する。

実際に文書テーブルと置換テーブルを作成してみましょう。

Execution example:

table_create Doc TABLE_PAT_KEY ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Doc body COLUMN_SCALAR ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
table_create Term TABLE_PAT_KEY|KEY_NORMALIZE ShortText --default_tokenizer TokenBigram
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Term Doc_body COLUMN_INDEX|WITH_POSITION Doc body
# [[0, 1337566253.89858, 0.000355720520019531], true]
table_create Synonym TABLE_PAT_KEY ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Synonym body COLUMN_SCALAR ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
load --table Doc
[
{"_key": "001", "body": "すっぱいブドウと甘いシークァーサー"},
{"_key": "002", "body": "シークヮーサージュースとゴーヤチャンプル"},
]
# [[0, 1337566253.89858, 0.000355720520019531], 2]
load --table Synonym
[
{"_key": "シークァーサー", "body": "(シークァーサー OR シークヮーサー)"},
{"_key": "シークヮーサー", "body": "(シークァーサー OR シークヮーサー)"},
]
# [[0, 1337566253.89858, 0.000355720520019531], 2]

この例では、ユーザが"シークァーサー"と入力しても、"シークヮーサー"と入力しても、それぞれの異なる表記の文書をもれなく検索するための置換テーブルを作成しています。

  検索

それでは実際に、準備した置換テーブルを使ってみましょう。まずは、query_expansionパラメータを指定せずにselectコマンドを使って検索してみます。

Execution example:

select Doc --match_columns body --query "シークァーサー"
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "body",
#           "ShortText"
#         ]
#       ],
#       [
#         1,
#         "001",
#         "すっぱいブドウと甘いシークァーサー"
#       ]
#     ]
#   ]
# ]
select Doc --match_columns body --query "シークヮーサー"
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "body",
#           "ShortText"
#         ]
#       ],
#       [
#         2,
#         "002",
#         "シークヮーサージュースとゴーヤチャンプル"
#       ]
#     ]
#   ]
# ]

指定された文字列に完全に一致するレコードのみがそれぞれヒットします。次に、query_expansionパラメータに、準備したSynonymテーブルのbodyカラムを指定してみましょう。

Execution example:

select Doc --match_columns body --query "シークァーサー" --query_expansion Synonym.body
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "body",
#           "ShortText"
#         ]
#       ],
#       [
#         1,
#         "001",
#         "すっぱいブドウと甘いシークァーサー"
#       ],
#       [
#         2,
#         "002",
#         "シークヮーサージュースとゴーヤチャンプル"
#       ]
#     ]
#   ]
# ]
select Doc --match_columns body --query "シークヮーサー" --query_expansion Synonym.body
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "body",
#           "ShortText"
#         ]
#       ],
#       [
#         1,
#         "001",
#         "すっぱいブドウと甘いシークァーサー"
#       ],
#       [
#         2,
#         "002",
#         "シークヮーサージュースとゴーヤチャンプル"
#       ]
#     ]
#   ]
# ]

どちらのクエリ文字列も、"(シークァーサー OR シークヮーサー)"という文字列に置換されてから検索されるため、表記の揺れを吸収して検索できるようになりました。

SUGGEST

Groonga has the suggest feature. This section describes how to use it and how it works.

  Introduction

The suggest feature in groonga provides the following features:

•   Completion

•   Correction

•   Suggestion

  Completion

Completion helps user input. If user inputs a partial word, groonga can return complete words from registered words.

For example, there are registered words:

•   "groonga"

•   "complete"

•   "correction"

•   "suggest"

    An user inputs "co" and groonga returns "complete" and "correction" because they starts with "co".

    An user inputs "sug" and groonga returns "suggest" because "suggest" starts with "sug".

    An user inputs "ab" and groonga returns nothing because no word starts with "ab".

  Correction

Correction also helps user input. If user inputs a wrong word, groonga can return correct words from registered correction pairs.

For example, there are registered correction pairs:
wrong word | correct word
grroonga | groonga
gronga | groonga
gronnga | groonga

An user inputs "gronga" and groonga returns "groonga" because "gronga" is in wrong word and corresponding correct word is "groonga".

An user inputs "roonga" and groonga returns nothing because "roonga" isn't in wrong word.

  Suggestion

Suggestion helps that user filters many found documents. If user inputs a query, groonga can return new queries that has more additional keywords from registered related query pairs.

For example, there are registered related query pairs:
keyword | related query
groonga | groonga search engine
search | Google search
speed | groonga speed

An user inputs "groonga" and groonga returns "groonga search engine" because "groonga" is in keyword column and related query column is "groonga search engine".

An user inputs "MySQL" and groonga returns nothing because "MySQL" isn't in keyword column values.

  Learning

The suggest feature requires registered data before using the feature. Those data can be registered from user inputs. Gronnga-suggest-httpd and groonga-suggest-learner commands are provided for the propose.

  Tutorial

TODO...

  Completion

This section describes about the following completion features:

•   How it works

•   How to use

•   How to learn

  How it works

The completion feature uses three searches to compute completed words:

1.  Prefix RK search against registered words.

2.  Cooccurrence search against learned data.

3.  Prefix search against registered words. (optional)

  Prefix RK search

RK means Romaji and Katakana. Prefix RK search can find registered words that start with user's input by romaji, katakana or hiragana. It's useful for searching in Japanese.

For example, there is a registered word "日本". And "ニホン" (it must be katakana) is registered as its reading. An user can find "日本" by "ni", "二" or "に".

  Cooccurrence search

Cooccurrence search can find registered words from user's partial input. It uses user input sequences that will be learned from query logs, access logs and so on.

For example, there is the following user input sequence:
input | submit
s | no
se | no
sea | no
sear | no
searc | no
search | yes
e | no
en | no
eng | no
engi | no
engin | no
engine | no
enginen | no (typo!)
engine | yes

Groonga creates the following completion pairs:
input | completed word
s | search
se | search
sea | search
sear | search
searc | search
e | engine
en | engine
eng | engine
engi | engine
engin | engine
engine | engine
enginen | engine

All user not-submitted inputs (e.g. "s", "se" and so on) before each an user submission maps to the submitted input (e.g. "search").

To be precise, this description isn't correct because it omits about time stamp. Groonga doesn't case about "all user not-submitted inputs before each an user submission". Groonga just case about "all user not-submitted inputs within a minute from an user submission before each an user submission". Groonga doesn't treat user inputs before a minute ago.

If an user inputs "sea" and cooccurrence search returns "search" because "sea" is in input column and corresponding completed word column value is "search".

  Prefix search

Prefix search can find registered word that start with user's input. This search doesn't care about romaji, katakana and hiragana not like Prefix RK search.

This search isn't always ran. It's just ran when it's requested explicitly or both prefix RK search and cooccurrence search return nothing.

For example, there is a registered word "search". An user can find "search" by "s", "se", "sea", "sear", "searc" and "search".

  How to use

Groonga provides /reference/commands/suggest command to use completion. --type complete option requests completion.

For example, here is an command to get completion results by "en":

Execution example:

suggest --table item_query --column kana --types complete --frequency_threshold 1 --query en
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   {
#     "complete": [
#       [
#         1
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "_score",
#           "Int32"
#         ]
#       ],
#       [
#         "engine",
#         1
#       ]
#     ]
#   }
# ]

  How it learns

Cooccurrence search uses learned data. They are based on query logs, access logs and so on. To create learned data, groonga needs user input sequence with time stamp and user submit input with time stamp.

For example, an user wants to search by "engine". The user inputs the query with the following sequence:

1.  2011-08-10T13:33:23+09:00: e

2.  2011-08-10T13:33:23+09:00: en

3.  2011-08-10T13:33:24+09:00: eng

4.  2011-08-10T13:33:24+09:00: engi

5.  2011-08-10T13:33:24+09:00: engin

6.  2011-08-10T13:33:25+09:00: engine (submit!)

    Groonga can be learned from the input sequence by the following command:

    load --table event_query --each 'suggest_preparer(_id, type, item, sequence, time, pair_query)'
    [
    {"sequence": "1", "time": 1312950803.86057, "item": "e"},
    {"sequence": "1", "time": 1312950803.96857, "item": "en"},
    {"sequence": "1", "time": 1312950804.26057, "item": "eng"},
    {"sequence": "1", "time": 1312950804.56057, "item": "engi"},
    {"sequence": "1", "time": 1312950804.76057, "item": "engin"},
    {"sequence": "1", "time": 1312950805.86057, "item": "engine", "type": "submit"}
    ]

  Correction

This section describes about the following correction features:

•   How it works

•   How to use

•   How to learn

  How it works

The correction feature uses three searches to compute corrected words:

1.  Cooccurrence search against learned data.

2.  Similar search against registered words. (optional)

  Cooccurrence search

Cooccurrence search can find registered words from user's wrong input. It uses user submit sequences that will be learned from query logs, access logs and so on.

For example, there are the following user submissions:
query | time
serach (typo!) | 2011-08-10T22:20:50+09:00
search (fixed!) | 2011-08-10T22:20:52+09:00

Groonga creates the following correction pair from the above submissions:
input | corrected word
serach | search

Groonga treats continuous submissions within a minute as input correction by user. Not submitted user input sequence between two submissions isn't used as learned data for correction.

If an user inputs "serach" and cooccurrence search returns "search" because "serach" is in input column and corresponding corrected word column value is "search".

  Similar search

Similar search can find registered words that has one or more the same tokens as user input. TokenBigram tokenizer is used for tokenization because suggest dataset schema created by /reference/executables/groonga-suggest-create-dataset uses TokenBigram tokenizer as the default tokenizer.

For example, there is a registered query "search engine". An user can find "search engine" by "web search service", "sound engine" and so on. Because "search engine" and "web search engine" have the same token "search" and "search engine" and "sound engine" have the same token "engine".

"search engine" is tokenized to "search" and "engine" tokens. (Groonga's TokenBigram tokenizer doesn't tokenize two characters for continuous alphabets and continuous digits for reducing search noise. TokenBigramSplitSymbolAlphaDigit tokenizer should be used to ensure tokenizing to two characters.) "web search service" is tokenized to "web", "search" and "service". "sound engine" is tokenized to "sound" and "engine".

  How to use

Groonga provides /reference/commands/suggest command to use correction. --type correct option requests corrections.

For example, here is an command to get correction results by "saerch":

Execution example:

suggest --table item_query --column kana --types correction --frequency_threshold 1 --query saerch
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   {
#     "correct": [
#       [
#         1
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "_score",
#           "Int32"
#         ]
#       ],
#       [
#         "search",
#         1
#       ]
#     ]
#   }
# ]

  How it learns

Cooccurrence search uses learned data. They are based on query logs, access logs and so on. To create learned data, groonga needs user submit inputs with time stamp.

For example, an user wants to search by "search" but the user has typo "saerch" before inputs the correct query. The user inputs the query with the following sequence:

1.  2011-08-10T13:33:23+09:00: s

2.  2011-08-10T13:33:23+09:00: sa

3.  2011-08-10T13:33:24+09:00: sae

4.  2011-08-10T13:33:24+09:00: saer

5.  2011-08-10T13:33:24+09:00: saerc

6.  2011-08-10T13:33:25+09:00: saerch (submit!)

7.  2011-08-10T13:33:29+09:00: serch (correcting...)

8.  2011-08-10T13:33:30+09:00: search (submit!)

    Groonga can be learned from the input sequence by the following command:

    load --table event_query --each 'suggest_preparer(_id, type, item, sequence, time, pair_query)'
    [
    {"sequence": "1", "time": 1312950803.86057, "item": "s"},
    {"sequence": "1", "time": 1312950803.96857, "item": "sa"},
    {"sequence": "1", "time": 1312950804.26057, "item": "sae"},
    {"sequence": "1", "time": 1312950804.56057, "item": "saer"},
    {"sequence": "1", "time": 1312950804.76057, "item": "saerc"},
    {"sequence": "1", "time": 1312950805.76057, "item": "saerch", "type": "submit"},
    {"sequence": "1", "time": 1312950809.76057, "item": "serch"},
    {"sequence": "1", "time": 1312950810.86057, "item": "search", "type": "submit"}
    ]

  Suggestion

This section describes about the following completion features:

•   How it works

•   How to use

•   How to learn

  How it works

The suggestion feature uses a search to compute suggested words:

1.  Cooccurrence search against learned data.

  Cooccurrence search

Cooccurrence search can find related words from user's input. It uses user submissions that will be learned from query logs, access logs and so on.

For example, there are the following user submissions:
query
search engine
web search realtime

Groonga creates the following suggestion pairs:
input | suggested words
search | search engine
engine | search engine
web | web search realtime
search | web search realtime
realtime | web search realtime

Those pairs are created by the following steps:

1.  Tokenizes user input query by TokenDelimit tokenizer that uses a space as token delimiter. (e.g. "search engine" is tokenized to two tokens "search" and "engine".)

2.  Creates a pair that is consists of a token and original query for each token.

    If an user inputs "search" and cooccurrence search returns "search engine" and "web search realtime" because "search" is in two input columns and corresponding suggested word columns have "search engine" and "web search realtime".

  How to use

Groonga provides /reference/commands/suggest command to use suggestion. --type suggest option requests suggestion

For example, here is an command to get suggestion results by "search":

Execution example:

suggest --table item_query --column kana --types suggest --frequency_threshold 1 --query search
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   {
#     "suggest": [
#       [
#         2
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "_score",
#           "Int32"
#         ]
#       ],
#       [
#         "search engine",
#         1
#       ],
#       [
#         "web search realtime",
#         1
#       ]
#     ]
#   }
# ]

  How it learns

Cooccurrence search uses learned data. They are based on query logs, access logs and so on. To create learned data, groonga needs user input sequence with time stamp and user submit input with time stamp.

For example, an user wants to search by "engine". The user inputs the query with the following sequence:

1.  2011-08-10T13:33:23+09:00: search engine (submit)

2.  2011-08-10T13:33:28+09:00: web search realtime (submit)

    Groonga can be learned from the submissions by the following command:

    load --table event_query --each 'suggest_preparer(_id, type, item, sequence, time, pair_query)'
    [
    {"sequence": "1", "time": 1312950803.86057, "item": "search engine", "type": "submit"},
    {"sequence": "1", "time": 1312950808.86057, "item": "web search realtime", "type": "submit"}
    ]

GEOLOCATION SEARCH

Groonga supports geolocation search. It uses index for search. It means that you can search by geolocation fast like fulltext search.

  Supported features

Groonga supports only point as data type. Line, surface and so on aren't supported yet. Here is a feature list:

1.  Groonga can store a point to a column.

2.  Groonga can search records that have a point in the specified rectangle.

3.  Groonga can search records that have a point in the specified circle.

4.  Groonga can calculate distance between two points.

5.  Groonga can sort records by distance from the specified point in ascending order.

    Here are use cases for groonga's geolocation search:

•   You list McDonald's around a station.

•   You list KFS around the current location sort by distance from the current location in ascending order with distance.

    Here are not use cases:

•   You search McDonald's in a city. (Groonga doesn't support geolocation search by a shape except a rectangle and a circle.)

•   You store a region instead of a point as a lake record. (A column can't has geolocation data except a point.)

    The following figures show about groonga's geolocation search features.

    Here is a figure that only has records. A black point describes a record. The following figures shows how records are treated. [image: only records] [image]

    Coming soon...

SERVER

  Server packages

The package groonga is the mininum set of fulltext search engine. If you want to use groonga for server use, you can install additional preconfigured packages.

There are three packages for server use.

•   groonga-httpd (nginx and HTTP protocol based server package)

•   groonga-server-http (simple HTTP protocol based server package)

•   groonga-server-gqtp (GQTP protocol based server package)

    Note that there is a conflict between groonga-httpd and groonga-server-http package because of port number. See /server/http/comparison if you want to know which package meets your demands.

  groonga-httpd

groonga-httpd is a nginx and HTTP protocol based server package.

Preconfigured setting:
Item | Default value
Port number | 10041
Access log path | /var/log/groonga/httpd/acccess.log
Error log path | /var/log/groonga/http-query.log
Database | /var/lib/groonga/db/*
Configuration file | /etc/groonga/httpd/groonga-httpd.conf

  Start HTTP server

Starting groonga HTTP server(Debian/Ubuntu/CentOS):

% sudo service groonga-httpd start

Starting groonga HTTP server(Fedora):

% sudo systemctl start groonga-httpd

  Stop HTTP server

Stopping groonga HTTP server(Debian/Ubuntu/CentOS):

% sudo service groonga-httpd stop

Starting groonga HTTP server(Fedora):

% sudo systemctl stop groonga-httpd

  Restart HTTP server

Restarting groonga HTTP server(Debian/Ubuntu/CentOS):

% sudo service groonga-httpd restart

Restarting groonga HTTP server(Fedora):

% sudo systemctl restart groonga-httpd

  groonga-server-http

groonga-server-http is a simple HTTP protocol based server package.

Preconfigured setting:
Item | Default value
Port number | 10041
process-log | /var/log/groonga/groonga-http.log
query-log | /var/log/groonga/http-query.log
Database | /var/lib/groonga/db/*

Configuration file for server setting (Debian/Ubuntu):

/etc/default/groonga/groonga-server-http

Configuration file for server setting (CentOS):

/etc/sysconfig/groonga-server-http

  Start HTTP server

Starting groonga HTTP server(Debian/Ubuntu/CentOS):

% sudo service groonga-server-http start

Starting groonga HTTP server(Fedora):

% sudo systemctl start groonga-server-http

  Stop HTTP server

Stopping groonga HTTP server(Debian/Ubuntu/CentOS):

% sudo service groonga-server-http stop

Stopping groonga HTTP server(Fedora):

% sudo systemctl stop groonga-server-http

  Restart HTTP server

Restarting groonga HTTP server(Debian/Ubuntu/CentOS):

% sudo service groonga-server-http restart

Restarting groonga HTTP server(Fedora):

% sudo systemctl restart groonga-server-http

  groonga-server-gqtp

groonga-server-gqtp is a GQTP protocol based server package.
Item | Default value
Port number | 10043
process-log | /var/log/groonga/groonga-gqtp.log
query-log | /var/log/groonga/gqtp-query.log
Database | /var/lib/groonga/db/*

Configuration file for server setting (Debian/Ubuntu):

/etc/default/groonga/groonga-server-gqtp

Configuration file for server setting (CentOS):

/etc/sysconfig/groonga-server-gqtp

  Start GQTP server

Starting groonga GQTP server(Debian/Ubuntu/CentOS):

% sudo service groonga-server-gqtp start

Starting groonga GQTP server(Fedora):

% sudo systemctl start groonga-server-gqtp

  Stop GQTP server

Stopping groonga GQTP server(Debian/Ubuntu/CentOS):

% sudo service groonga-server-http stop

Stopping groonga GQTP server(Fedora):

% sudo systemctl stop groonga-server-gqtp

  Restart GQTP server

Restarting groonga HTTP server(Debian/Ubuntu/CentOS):

% sudo service groonga-server-gqtp restart

Restarting groonga HTTP server(Fedora):

% sudo systemctl restart groonga-server-gqtp

  GQTP

TODO

See /reference/executables/groonga.

  HTTP

Groonga provides two HTTP server implementations.

•   http/groonga

•   http/groonga-httpd

    http/groonga is a simple implemntation. It is fast but doesn't have many HTTP features. It is convenient to try groonga because it requires just a few command line options to run.

    http/groonga-httpd is a nginx based implementation. It is also fast and has many HTTP features.

Note
    http/groonga-httpd is still experimental.

  Comparison

There are many differences between groonga and groonga-httpd. Here is a comparison table.
 | groonga | groonga-httpd
Performance | o | o
Using multi CPU cores | o (by multi threading) | o (by multi process)
Configuration file | optional | required
Custom prefix path | x | o
Custom command version | o | x (comming soon)
Multi databases | x | o
Authentication | x | o
Gzip compression | x | o
POST | x | o
HTTPS | x | o
Access log | x | o
Upgrading without downtime | x | o

  Performance

Both groonga and groonga-httpd are very fast. They can work with the same throughput.

  Using multi CPU cores

Groonga scales on multi CPU cores. groonga scales by multi threading. groonga-httpd scales by multi processes.

groonga uses the same number of threads as CPU cores by default. If you have 8 CPU cores, 8 threads are used by default.

groonga-httpd uses 1 process by default. You need to set worker_processes directive to use CPU cores. If you have 8 CPU cores, specify worker_processes 8 in configuration file like the following:

worker_processes 8;
http {
  # ...
}

  Configuration file

groonga can work without configuration file. All configuration items such as port number and the max number of threads can be specified by command line. Configuration file is also used to specify configuration items.

It's very easy to run groonga HTTP server because groonga requires just a few options to run. Here is the most simple command line to start HTTP server by groonga:

% groonga --protocol http -d /PATH/TO/DATABASE

groonga-httpd requires configuration file to run. Here is the most simple configuration file to start HTTP server by groonga-httpd:

events {
}
http {
  server {
    listen 10041;
    location /d/ {
      groonga on;
      groonga_database /PATH/TO/DATABASE;
    }
  }
}

  Custom prefix path

groonga accepts a path that starts with /d/ as command URL such as http://localhost:10041/d/status. You cannot change the prefix path /d/.

groonga-httpd can custom prefix path. For example, you can use http://localhost:10041/api/status as command URL. Here is a sample configuration to use /api/ as prefix path:

events {
}
http {
  server {
    listen 10041;
    location /api/ { # <- change this
      groonga on;
      groonga_database /PATH/TO/DATABASE;
    }
  }
}

  Custom command version

Groonga has /reference/command/command_version mechanism. It is for upgrading groonga commands with backward compatibility.

groonga can change the default command veresion by --default-command-version option. Here is a sample command line to use command version 2 as the default command version:

% groonga --protocol http --default-command-version 2 -d /PATH/TO/DATABASE

groonga-httpd cannot custom the default command version yet. But it will be supported soon. If it is supported, you can provides different command version groonga commands in the same groonga-httpd process. Here is a sample configuration to provide command version 1 commands under /api/1/ and command version 2 comamnds under /api/2/:

events {
}
http {
  server {
    listen 10041;
    groonga_database /PATH/TO/DATABASE;
    location /api/1/ {
      groonga on;
      groogna_default_command_version 1;
    }
    location /api/2/ {
      groonga on;
      groogna_default_command_version 2;
    }
  }
}

  Multi databases

groonga can use only one database in a process.

groonga-httpd can use one or more databases in a process. Here is a sample configuration to provide /tmp/db1 database under /db1/ path and /tmp/db2 database under /db2/ path:

events {
}
http {
  server {
    listen 10041;
    location /db1/ {
      groonga on;
      groonga_database /tmp/db1;
    }
    location /db2/ {
      groonga on;
      groonga_database /tmp/db2;
    }
  }
}

  Authentication

HTTP supports authentications such as basic authentication and digest authentication. It can be used for restricting use of danger command such as /reference/commands/shutdown.

groonga doesn't support any authentications. To restrict use of danger command, other tools such as iptables and reverse proxy are needed.

groonga-httpd supports basic authentication. Here is a sample configuration to restrict use of /reference/commands/shutdown command:

events {
}
http {
  server {
    listen 10041;
    groonga_database /PATH/TO/DATABASE;
    location /d/shutdown {
      groonga on;
      auth_basic           "manager is required!";
      auth_basic_user_file "/etc/managers.htpasswd";
    }
    location /d/ {
      groonga on;
    }
  }
}

  Gzip compression

HTTP supports response compression by gzip with Content-Encoding: gzip response header. It can reduce network flow. It is useful for large search response.

groonga doesn't support compression. To support compression, reverse proxy is needed.

groonga-httpd supports gzip compression. Here is a sample configuration to compress response by gzip:

events {
}
http {
  server {
    listen 10041;
    groonga_database /PATH/TO/DATABASE;
    location /d/ {
      groonga    on;
      gzip       on;
      gzip_types *;
    }
  }
}

Note that gzip_types * is specified. It's one of the important configuration. gzip_types specifies gzip target data formats by MIME types. groonga-httpd returns one of JSON, XML or MessagePack format data. But those formats aren't included in the default value of gzip_types. The default value of gzip_types is text/html.

To compress response data from groonga-httpd by gzip, you need to specify gzip_types * or gzip_types application/json text/xml application/x-msgpack explicitly. gzip_types * is recommended. There are two reasons for it. The first, groonga may support more formats in the future. The second, all requests for the location are processed by groonga. You don't need to consider about other modules.

  POST

You can load your data by POST JSON data. You need follow the following rules to use loading by POST.

•   Content-Type header value must be application/json.

•   JSON data is sent as body.

•   Table name is specified by query parameter such as table=NAME.

    Here is an example curl command line that loads two users alice and bob to Users table:

    % curl --data-binary '[{"_key": "alice"}, {"_key": "bob"}]' -H "Content-Type: application/json" "http://localhost:10041/d/load?table=Users"

  HTTPS

TODO

  Access log

TODO

  Upgrading without downtime

TODO

  groonga

TODO

  groonga-httpd

TODO

リファレンスマニュアル

  実行ファイル

groongaパッケージが提供する実行ファイルについて説明します。

  grnslap

  名前

grnslap - groongaプロセスの通信層のパフォーマンスをチェックするツール

  書式

grnslap [options] [dest]

  説明

grnslapは、groongaプロセスに対してリクエストを多重に行い、パフォーマンスをチェックするためのツールです。

groonga独自プロトコルであるgqtpと、httpの両プロトコルでリクエストを行うことができます。また、リクエストの多重度を指定することができます。

クエリの内容を標準入力から与えることができます。実稼動環境でのクエリパタンに近いクエリを標準入力に与えることによって、実稼動環境に近い状態での検証を行うことができます。

現在は、make installしてもインストールは行われない。

  オプション

-P  リクエストのプロトコルを指定します。

    http httpでリクエストします。対象のhttpのパス群(GETパラメータを含む)をLF区切り形式で標準入力に与えると、それらのパスに順次アクセスします。

    gqtp gqtpでリクエストします。gqtpのリクエストをLF区切り形式で標準入力に与えると、それらのリクエストを順次行います。

-m  リクエストの多重度を指定します。初期値は10です。

  引数

dest
    接続先のホスト名とポート番号をを指定します(デフォルト値は'localhost:10041')。ポート番号を指定しない場合には、10041が指定されたものとします。

  サンプル

http://localhost:10041/d/status に、多重度100でリクエストを行う。

> yes /d/status | head -n 100 | grnslap -P http -m 100 localhost:10041
2009-11-12 19:34:09.998696|begin: max_concurrency=100 max_tp=10000
2009-11-12 19:34:10.011208|end  : n=100 min=46 max=382 avg=0 qps=7992.966190 etime=0.012511

  grntest

  名前

grntest - groongaテストプログラム

  書式

grntest  [options...] [script] [db]

  説明

grntestは、groonga汎用テストツールです。

groongaを単独のプロセスとして利用する場合はもちろん、サーバプログラムとして利用する場合の動作確認や実行速度測定が可能です。

grntest用のデータファイルは自分で作成することも既存のものを利用することもできます。既存のデータファイルは、ftp.groonga.orgから必要に応じダウンロードします。そのため、groonga及びgrntestが動作し、インターネットに接続できる環境であればgroongaコマンドの知識がなくてもgroongaの動作を確認できます。

現在は、Linux 及びWindows上で動作します。make installしてもインストールは行われません。

  オプション

-i, --host <ip/hostname>
    接続するgroongaサーバを、ipアドレスまたはホスト名で指定します。指定先にgroongaサーバが立ち上がっていない場合、接続不能となることに注意してください。このオプションを指定しない場合、grntestは自動的にlocalhostのgroongaサーバを起動して接続します。

-p, --port <port number>
    自動的に起動するgroongaサーバ、または明示的に指定した接続先のgroonga サーバが利用するポート番号を指定します。接続先のgroongaサーバが利用しているポートと、このオプションで指定したポート番号が異なる場合、接続不能となることに注意してください。

--dir
    ftp.groonga.org に用意されているスクリプトファイルを表示します。

--ftp
    ftp.groonga.orgとFTP通信を行い、scriptファイルの同期やログファイルの送信を行います。

--log-output-dir
    デフォルトでは、grntest終了後のログファイルの出力先ははカレントディレクトリです。このオプションを利用すると、任意のディレクトリに出力先を変更することができます。

--groonga <groonga_path>
    groongaコマンドのパスを指定します。デフォルトでは、PATHの中からgroongaコマンドを探します。

--protocol <gqtp|http>
    groongaコマンドが使うプロトコルとして gqtp または http を指定します。

  引数

script
    grntestの動作方法(以下、grntest命令と呼びます)を記述したテキストファイルです。拡張子は.scrです。

db  grntestが利用するgroonga データベースです。指定されたデータベースが存在しない場合、grntestが新規に作成します。またgroonga サーバを自動的に起動する場合もこの引数で指定したデータベースが利用されます。接続するgroonga サーバを明示的に指定した場合に利用するデータベースは、接続先サーバが使用中のデータベースになることに注意してください。

  使い方

まず、シェル上(Windowsならコマンドプロンプト上)で:

grntest test.scr 任意のDB名

とタイプしてください。もしgrntestが正常に動作すれば、:

test-ユーザ名-数字.log

というファイルが作成されるはずです。作成されない場合、このドキュメントの「トラブルシューティング」の章を参照してください。

  スクリプトファイル

スクリプトファイルは、grntest命令を記述したテキストファイルです。 ";"セミコロンを利用して、一行に複数のgrntest命令を記述することができます。一行に複数のgrntest命令がある場合、各命令は並列に実行されます。 "#"で始まる行はコメントとして扱われます。

  grntest命令

現在サポートされているgrntest命令は以下の8つです。 do_local コマンドファイル [スレッド数] [繰り返し数] コマンドファイルをgrntest単体で実行します。スレッド数が指定されている場合、複数のスレッドで同じコマンドファイルを同時に実行します。繰り返し数が指定されてい場合、コマンドファイルの内容を繰り返し実行します。スレッド数、繰り返し数とも省略時は1です。1スレッドで複数回動作させたい場合は、do_local コマンドファイル 1 [繰り返し数]と明示的に指定してください。

do_gqpt コマンドファイル [スレッド数] [繰り返し数] コマンドファイルをgroongaサーバで実行します。スレッド数や繰り返し数の意味はdo_localの場合と同じです。

rep_local コマンドファイル [スレッド数] [繰り返し数] コマンドファイルをgrntest単体で実行し、より詳細な報告を行います。

rep_gqpt コマンドファイル [スレッド数] [繰り返し数] コマンドファイルをgroongaサーバで実行し、より詳細な報告を行います。 スレッド数や繰り返し数の意味はdo_localと 同じです。

out_local コマンドファイル 入力ファイル名 コマンドファイルをgrntest単体で実行し、各コマンドの実行結果をすべて”出力ファイル"に書きだします。この結果は、test_local,　test_gqtp命令で利用します。なおこの命令の「出力ファイル」とは、grntest実行時に自動的に作成されるログとは別のものです。grntestではコメントが利用できる以外、:

groonga < コマンドファイル > 出力ファイル

とした場合と同じです。

out_gqtp コマンドファイル 出力ファイル名 コマンドファイルをgroongaサーバで実行します。その他はout_local命令と同等です。

test_local コマンドファイル 入力ファイル名
    コマンドファイルをgrntest単体で実行し、各コマンドの実行結果を入力ファイルと比較します。処理時間など本質的要素以外に差分があった場合、差分を、入力ファイル.diffというファイルに書きだします。

  コマンドファイル

コマンドファイルは、groonga組み込みコマンドを1行に1つずつ記述したテキストファイルです。拡張子に制限はありません。groonga組み込みコマンドに関しては /reference/commands を参照してください。

  サンプル

スクリプトファイルのサンプルです。:

# sample script
rep_local test.ddl
do_local test.load;
do_gqtp test.select 10 10; do_local test.status 10

上記の意味は以下のとおりです。

1行目 コメント行。

2行目 test.dll というコマンドファイルをgroonga単体で実行し、詳細に報告する。

3行目 test.load というコマンドファイルをgroonga単体で実行する。(最後の";"セミコロンは複数のgrntest命令を記述する場合に必要ですが、この例のように1つのgrntest命令を実行する場合に付与しても問題ありません。)

4行目 test.select というコマンドファイルをgroongaサーバで10個のスレッドで同時に実行する。各スレッドはtest.selectの中身を10回繰り返す。また同時に、groonga単体でtest.statusというコマンドファイルを10個のスレッドで実行する。

  特殊命令

スクリプトファイルのコメント行には特殊コマンドを埋め込むことが可能です。現在サポートされている特殊命令は以下の二つです。

#SET_HOST <ip/hostname>
    -i, --hostオプションと同等の機能です。コマンドラインオプションに指定したIPアドレス/ホスト名と、SET_HOSTで指定したIPアドレス/ホスト名が異なる場合、またコマンドラインオプションを指定しなかった場合にもSET_HOSTが優先されます。SET_HOSTを利用した場合、サーバが自動的には起動されないのもコマンドラインオプションで指定した場合と同様です。

#SET_PORT <port number>
    -p, --port オプションと同等の機能です。コマンドラインオプションに指定したポート番号とSET_PORTで指定したポート番号が異なる場合、またコマンドラインオプションを指定しなかった場合にもSET_PORTが優先されます。

    特殊命令はスクリプトファイルの任意の場所に書き込むことができます。同一ファイル内に複数回特殊命令を記述した場合、「最後の」特殊命令が有効となります。

    例えば、

    $ ./grntest --port 20010 test.scr testdb

    とコマンド上でポートを指定した場合でも、もしtest.scrの中身が

    #SET_PORT 10900
    rep_local test.ddl
    do_local test.load;
    rep_gqtp test.select 10 10; rep_local test.status 10
    #SET_PORT 10400

    であれば、自動的に起動されるgroongaサーバはポート番号10400を利用します。

  grntest実行結果

grntestが正常に終了すると、(拡張子を除いた)スクリプト名-ユーザ名-実行開始時刻.logという形式のログファイルがカレントディレクトリに作られます。ログファイルは自動的にftp.groonga.org に送信されます。ログファイルは以下のようなjson形式のテキストです。

[{"script": "test.scr",
  "user": "homepage",
  "date": "2010-04-14 22:47:04",
  "CPU": Intel(R) Pentium(R) 4 CPU 2.80GHz",
  "BIT": 32,
  "CORE": 1,
  "RAM": "975MBytes",
  "HDD": "257662232KBytes",
  "OS": "Linux 2.4.20-24.7-i686",
  "HOST": "localhost",
  "PORT": "10041",
  "VERSION": "0.1.8-100-ga54c5f8"
},
{"jobs": "rep_local test.ddl",
"detail": [
[0, "table_create res_table --key_type ShortText", 1490, 3086, [0,1271252824.25846,0.00144
7]],
[0, "column_create res_table res_column --type Text", 3137, 5956, [0,1271252824.2601,0.002
741]],
[0, "column_create res_table user_column --type Text", 6020, 8935, [0,1271252824.26298,0.0
02841]],
[0, "column_create res_table mail_column --type Text", 8990, 11925, [0,1271252824.26595,0.
002861]],
[0, "column_create res_table time_column --type Time", 12008, 13192, [0,1271252824.26897,0
.001147]],
[0, "status", 13214, 13277, [0,1271252824.27018,3.0e-05]],
[0, "table_create thread_table --key_type ShortText", 13289, 14541, [0,1271252824.27025,0.
001213]],
[0, "column_create thread_table thread_title_column --type ShortText", 14570, 17380, [0,12
71252824.27153,0.002741]],
[0, "status", 17435, 17480, [0,1271252824.2744,2.7e-05]],
[0, "table_create lexicon_table --flags 129 --key_type ShortText --default_tokenizer Token
Bigram", 17491, 18970, [0,1271252824.27446,0.001431]],
[0, "column_create lexicon_table inv_res_column 514 res_table res_column ", 18998, 33248,
[0,1271252824.27596,0.01418]],
[0, "column_create lexicon_table inv_thread_column 514 thread_table thread_title_column ",
 33285, 48472, [0,1271252824.29025,0.015119]],
[0, "status", 48509, 48554, [0,1271252824.30547,2.7e-05]]],
"summary" :[{"job": "rep_local test.ddl", "latency": 48607, "self": 47719, "qps": 272.4281
73, "min": 45, "max": 15187, "queries": 13}]},
{"jobs": "do_local test.load; ",
"summary" :[{"job": "do_local test.load", "latency": 68693, "self": 19801, "qps": 1010.049
997, "min": 202, "max": 5453, "queries": 20}]},
{"jobs": "do_gqtp test.select 10 10; do_local test.status 10",
"summary" :[{"job": " do_local test.status 10", "latency": 805990, "self": 737014, "qps":
54.273053, "min": 24, "max": 218, "queries": 40},{"job": "do_gqtp test.select 10 10", "lat
ency": 831495, "self": 762519, "qps": 1967.164097, "min": 73, "max": 135631, "queries": 15
00}]},
{"total": 915408, "qps": 1718.359464, "queries": 1573}]

  制限事項

•   スクリプトファイルの一行には複数のgrntest命令を記述できますが、すべてのスレッド数の合計は最大64までに制限されます。

•   コマンドファイル中のgroongaコマンドの長さは最長5000000byteです。

  トラブルシューティング

もし、grntestが正常に動作しない場合、まず以下を確認してください。

•   インターネットに接続しているか？ --ftp オプションを指定すると、grntestは動作のたびにftp.groonga.orgと通信します。ftp.groonga.orgと通信可能でない場合、grntestは正常に動作しません。

•   groonga サーバが動作していないか？　grntestは、-i, --host オプションで明示的にサーバを指定しないかぎり、自動的にlocalhostのgroongaサーバを立ち上げます。すでにgroongaサーバが動作している場合、grntestは正常に動作しない可能性があります。

•   指定したDBが適切か？ grntestは、引数で指定したDBの中身はチェックしません。もし指定されたDBが存在しなければ自動的にDBを作成しますが、もしファイルとして存在する場合は中身に関わらず動作を続けてしまい、結果が異常になる可能性があります。

    以上の原因でなければ、問題はgrntestかgroongaにあります。ご報告をお願いします。

  groonga command

  名前

groonga - 列指向データベース機能を持つ全文検索エンジンソフトウェア

  書式

groonga [options] [dest] [command [args]]

  説明

groongaは列指向のデータベース機能を持つ高速でスケーラブルな全文検索エンジンです。 groongaのデータベースは、groongaコマンドかCライブラリインタフェースを通して操作することができます。このマニュアルページでは、groongaコマンドの使い方について説明します。

  オプション

-n  新たなデータベースを作成します。

-c  クライアントモードで実行します。

-s  サーバモードで実行します。

-d  デーモンモードで実行します。(forkする点がサーバモードと異なる)

-e, --encoding <encoding>
    データベースで使用する文字エンコーディング方式を指定します。新たなデータベースを作成する時のみ有効です。none, euc, utf8, sjis, latin, koi8rのいずれかが指定できます。

-l, --log-level <log level>
    ログレベルを指定します。0〜8までの数値が指定可能で、数が大きいほど多くのログが出力されます。

-a, --address <ip/hostname>
    Deprecated since version 1.2.2: Use --bind-address instead.

--bind-address <ip/hostname>
    New in version 1.2.2.

    サーバモードかデーモンモードで実行するとき、listenするアドレスを指定します。(デフォルトは hostname の返すホスト名)

-p, --port <port number>
    クライアント、サーバ、またはデーモンモードで使用するTCPポート番号。 (デフォルトは10041番)

-i, --server-id <ip/hostname>
    サーバモードかデーモンモードで実行するとき、サーバのIDとなるアドレスを指定します。(デフォルトは`hostname`の返すホスト名)

-h, --help
    ヘルプメッセージを出力します。

--document-root <path>
    httpサーバとしてgroongaを使用する場合に静的ページを格納するディレクトリを指定します。

    デフォルトでは、データベースを管理するための汎用的なページに対応するファイルが/usr/share/groonga/admin_html以下にインストールされます。このディレクトリをdocument-rootオプションの値に指定して起動した場合、ウェブブラウザでhttp://hostname:port/index.htmlにアクセスすると、ウェブベースのデータベース管理ツールを使用できます。

--protocol <protocol>
    http,gqtpのいずれかを指定します。(デフォルトはgqtp)

--log-path <path>
    ログを出力するファイルのパスを指定します。(デフォルトは/var/log/groonga/groonga.logです)

--query-log-path <path>
    クエリーログを出力するファイルのパスを指定します。(デフォルトでは出力されません)

-t, --max-threads <max threasd>
    最大で利用するスレッド数を指定します。(デフォルトはマシンのCPUコア数と同じ数です)

--pid-path <path>
    PIDを保存するパスを指定します。(デフォルトでは保存しません)

--config-path <path>
    設定ファイルのパスを指定します。設定ファイルは以下のようなフォーマットになります。:

    # '#'以降はコメント。
    ; ';'以降もコメント。
    # 'キー = 値'でオプションを指定。
    pid-file = /var/run/groonga.pid
    # '='の前後の空白はは無視される。↓は↑と同じ意味。
    pid-file=/var/run/groonga.pid
    # 'キー'は'--XXX'スタイルのオプション名と同じものが使える。
    # 例えば、'--pid-path'に対応するキーは'pid-path'。
    # ただし、キーが'config-path'のオプションは無視される。

--cache-limit <limit>
    キャッシュ数の最大値を指定します。(デフォルトは100です)

--default-match-escalation-threshold <threshold>
    検索の挙動をエスカレーションする閾値を指定します。(デフォルトは0です)

  引数

dest
    使用するデータベースのパス名を指定します。

    クライアントモードの場合は接続先のホスト名とポート番号を指定します(デフォルト値は'localhost:10041')。ポート番号を指定しない場合には、10041が指定されたものとします。

command [args]
    スタンドアロンおよびクライアントモードの場合は、実行するコマンドとその引数をコマンドライン引数に指定できます。コマンドライン引数にcommandを与えなかった場合は、標準入力から一行ずつEOFに達するまでコマンド文字列を読み取り、順次実行します。

  コマンド

groongaコマンドを通してデータベースを操作する命令をコマンドと呼びます。コマンドは主にC言語で記述され、groongaプロセスにロードすることによって使用できるようになります。 それぞれのコマンドは一意な名前と、0個以上の引数を持ちます。

引数は以下の2種類の方法のいずれかで指定することができます。:

形式1: コマンド名 値1 値2,..
形式2: コマンド名 --引数名1 値1 --引数名2 値2,..

形式1でコマンドを実行する場合は、定義された順番で値を指定しなければならず、途中の引数の値を省略することはできません。形式2でコマンドを実行する場合は、「--引数名」のように引数の名前を明示しなければならない代わりに、任意の順番で引数を指定することが可能で、途中の引数の指定を省略することもできます。

標準入力からコマンド文字列を与える場合は、コマンド名と引数名と値は、空白( )で区切ります。空白や、記号「"'()」のうちいずれかを含む値を指定したい場合は、シングルクォート(')かダブルクォート(")で値を囲みます。値として指定する文字列の中では、改行文字は'n'に置き換えて指定します。また、引用符に使用した文字を値の中で指定する場合には、その文字の前にバックスラッシュ('') を指定します。バックスラッシュ文字自身を値として指定する場合には、その前にバックスラッシュを指定します。

You can write command list with continuous line which is represented by '\' character.:

table_create --name Terms \
             --flags TABLE_PAT_KEY \
             --key_type ShortText \
             --default_tokenizer TokenBigram

  組み込みコマンド

以下のコマンドは組み込みコマンドとして予め定義されています。

status
    groongaプロセスの状態を表示します。

table_list
    DBに定義されているテーブルのリストを表示します。

column_list
    テーブルに定義されているカラムのリストを表示します。

table_create
    DBにテーブルを追加します。

column_create
    テーブルにカラムを追加します。

table_remove
    DBに定義されているテーブルを削除します。

column_remove
    テーブルに定義されているカラムを削除します。

view_add
    VIEW型のテーブルに要素となるテーブルを定義します。

load
    テーブルにレコードを挿入します。

select
    テーブルに含まれるレコードを検索して表示します。

define_selector
    検索条件をカスタマイズした新たな検索コマンドを定義します。

quit
    データベースとのセッションを終了します。

shutdown
    サーバ(デーモン)プロセスを停止します。

log_level
    ログ出力レベルを設定します。

log_put
    ログ出力を行います。

clearlock
    ロックを解除します。

  例

新しいデータベースを作成します。:

% groonga -n /tmp/hoge.db quit
%

作成済みのデータベースにテーブルを定義します。:

% groonga /tmp/hoge.db table_create Table 0 ShortText
[[0]]
%

サーバを起動します。:

% groonga -d /tmp/hoge.db
%

httpサーバとして起動します。:

% groonga -d -p 80 --protocol http --document-root /usr/share/groonga/admin_html /tmp/hoge.db
%

サーバに接続し、テーブル一覧を表示します。:

% groonga -c localhost table_list
[[0],[["id","name","path","flags","domain"],[256,"Table","/tmp/hoge.db.0000100",49152,14]]]
%

  groonga-httpd

  Summary

groonga-httpd is a program to communicate with a groonga server using the HTTP protocol. It functions as same as groonga-server-http. Although groonga-server-http has limited support for HTTP with a minimal built-in HTTP server, groonga-httpd has full support for HTTP with an embedded nginx. All standards-compliance and features provided by nginx is also available in groonga-httpd.

groonga-httpd has an Web-based administration tool implemented with HTML and JavaScript. You can access to it from http://hostname:port/.

  Synopsis

groonga-httpd [nginx options]

  Usage

  Set up

First, you'll need to edit the groonga-httpd configuration file to specify a database. Edit /etc/groonga/httpd/groonga-httpd.conf to enable the groonga_database directive like this:

# Match this to the file owner of groonga database files if groonga-httpd is
# run as root.
#user groonga;
...
http {
  ...
  # Don't change the location; currently only /d/ is supported.
  location /d/ {
    groonga on; # <= This means to turn on groonga-httpd.
    # Specify an actual database and enable this.
    groonga_database /var/lib/groonga/db/db;
  }
  ...
}

Then, run groonga-httpd. Note that the control immediately returns back to the console because groonga-httpd runs as a daemon process by default.:

% groonga-httpd

  Request queries

To check, request a simple query (/reference/commands/status).

Execution example:

% curl http://localhost:10041/d/status
[
  [
    0,
    1337566253.89858,
    0.000355720520019531
  ],
  {
    "uptime": 0,
    "max_command_version": 2,
    "n_queries": 0,
    "cache_hit_rate": 0.0,
    "version": "2.1.0",
    "alloc_count": 152,
    "command_version": 1,
    "starttime": 1356678595,
    "default_command_version": 1
  }
]

  Browse the administration tool

Also, you can browse Web-based administration tool at http://localhost:10041/.

  Shut down

Finally, to terminate the running groonga-httpd daemon, run this:

% groonga-httpd -s stop

  Configuration directives

This section decribes only important directives. They are groonga-httpd specific directives and performance related directives.

The following directives can be used in the groonga-httpd configuration file. By default, it's located at /etc/groonga/httpd/groonga-httpd.conf.

  Groonga-httpd specific directives

The following directives aren't provided by nginx. They are provided by groonga-httpd to configure groonga-httpd specific configurations.

  groonga

Synopsis:

groonga on | off;

Default
    groonga off;

Context
    location

    Specifies whether groonga is enabled in the location block. The default is off. You need to specify on to enable groonga.

    Examples:

    location /d/ {
      groonga on;  # Enables groonga under /d/... path
    }
    location /d/ {
      groonga off; # Disables groonga under /d/... path
    }

  groonga_database

Synopsis:

groonga_database /path/to/groonga/database;

Default
    groonga_database /usr/local/var/lib/groonga/db/db;

Context
    http, server, location

    Specifies the path to a groonga database. This is the required directive.

  groonga_base_path

Synopsis:

groonga_base_path /d/;

Default
    The same value as location name.

Context
    location

    Specifies the base path in URI. groonga uses /d/command?parameter1=value1&... path to run command. The form of path in used in groonga-httpd but groonga-httpd also supports /other-prefix/command?parameter1=value1&... form. To support the form, groonga-httpd removes the base path from the head of request URI and prepend /d/ to the processed request URI. By the path conversion, users can use custom path prefix and groonga can always uses /d/command?parameter1=value1&... form.

    Nomally, this directive isn't needed. It is needed for per command configuration.

    Here is an example configuration to add authorization to /reference/commands/shutdown command:

    groonga_database /var/lib/groonga/db/db;
    location /d/shutdown {
      groonga on;
      # groonga_base_path is needed.
      # Because /d/shutdown is handled as the base path.
      # Without this configuration, /d/shutdown/shutdown path is required
      # to run shutdown command.
      groonga_base_path /d/;
      auth_basic           "manager is required!";
      auth_basic_user_file "/etc/managers.htpasswd";
    }
    location /d/ {
      groonga on;
      # groonga_base_path doesn't needed.
      # Because location name is the base path.
    }

  Performance related directives

The following directives are related to the performance of groonga-httpd.

  worker_processes

For optimum performance, set this to be equal to the number of CPUs or cores. In many cases, groonga queries may be CPU-intensive work, so to fully utilize multi-CPU/core systems, it's essential to set this accordingly.

This isn't a groonga-httpd specific directive, but an nginx's one. For details, see http://wiki.nginx.org/CoreModule#worker_processes.

By default, this is set to 1. It is nginx's default.

  Available nginx modules

All standard HTTP modules is available. HttpRewriteModule is disabled when you don't have PCRE (Perl Compatible Regular Expressions). For the list of standard HTTP modules, see http://wiki.nginx.org/Modules.

  groonga HTTPサーバー

  名前

groonga HTTPサーバー

  書式

groonga -d --protocol http DB_PATH

  説明

groongaサーバを起動する時に--protocolオプションにhttpを指定すると、httpで通信可能になります。また、--document-root によって静的ページのパスを指定すると、httpリクエストに指定されたURIに対応する、パス配下に置かれたファイルを出力します。

groongaにはHTML + JavaScriptで実装された管理ツールが標準で付属しています。--document-rootを指定しない場合は管理ツールがインストールされているパスが指定されたとみなされますので、ウェブブラウザでhttp://hostname:port/にアクセスすると、管理ツールを利用できます。

  コマンド

httpを指定して起動したgroongaサーバに対しても、他のモードで起動したgroongaと同じコマンドが使用できます。

コマンドは、複数の引数をとります。引数にはそれぞれ名前があります。また、特殊な引数である「output_type」と「command_version」があります。

スタンドアロンやクライアントモードでは、コマンドは以下のような形式で指定します。 形式1: コマンド名 値1 値2,..

形式2: コマンド名 --引数名1 値1 --引数名2 値2,..

形式1と形式2は混在させることができます。これらの形式では、output_typeという引数名を用いてoutput_typeを指定します。

httpでgroongaサーバと通信する際には、以下のような形式でコマンドを指定します。:

形式: /d/コマンド名.output_type?引数名1=値1&引数名2=値2&...

ただし、コマンド名、引数名、値はURLエンコードが必要です。

GETメソッドのみが使用可能です。

output_typeにはjson, tsv, xmlが指定可能です。

command_versionはコマンドの仕様の互換性を指定します。詳細は /reference/command/command_version を参照してください。

  返値

output_typeの指定に従って、コマンドの実行結果を出力します。

  groonga-suggest-create-dataset

  NAME

groonga-suggest-create-dataset - Defines schema for a suggestion dataset

  SYNOPSTIS

groonga-suggest-create-dataset [options] DATABASE DATASET

  DESCTIPION

groonga-suggest-create-dataset creates a dataset for /suggest. A database has many datasets. This command just defines schema for a suggestion dataset.

  OPTIONS

None.

  EXIT STATUS

TODO

  FILES

TODO

  EXAMPLE

TODO

  SEE ALSO

/suggest

  Output

Groonga supports the following output format types:

•   JSON

•   XML

•   TSV (Tab Separated Values)

•   MessagePack

    JSON is the default output format.

  Usage

Groonga has the following query interfaces:

•   command line

•   HTTP

    They provides different ways to change output format type.

  Command line

You can use command line query interface by groonga DB_PATH or groonga -c. Those groonga commands shows > `` prompt. In this query interface, you can specify output format type by ``output_type option.

If you don't specify output_type option, you will get a result in JSON format:

> status
[[0,1327721628.10738,0.000131845474243164],{"alloc_count":142,"starttime":1327721626,"uptime":2,"version":"1.2.9-92-gb87d9f8","n_queries":0,"cache_hit_rate":0.0,"command_version":1,"default_command_version":1,"max_command_version":2}]

You can specify json as output_type value to get a result in JSON format explicitly:

> status --output_type json
[[0,1327721639.08321,7.93933868408203e-05],{"alloc_count":144,"starttime":1327721626,"uptime":13,"version":"1.2.9-92-gb87d9f8","n_queries":0,"cache_hit_rate":0.0,"command_version":1,"default_command_version":1,"max_command_version":2}]

You need to specify xml as output_type value to get a result in XML format:

> status --output_type xml
<?xml version="1.0" encoding="utf-8"?>
<RESULT CODE="0" UP="1327721649.61095" ELAPSED="0.000126361846923828">
<RESULT>
<TEXT>alloc_count</TEXT>
<INT>146</INT>
<TEXT>starttime</TEXT>
<INT>1327721626</INT>
<TEXT>uptime</TEXT>
<INT>23</INT>
<TEXT>version</TEXT>
<TEXT>1.2.9-92-gb87d9f8</TEXT>
<TEXT>n_queries</TEXT>
<INT>0</INT>
<TEXT>cache_hit_rate</TEXT>
<FLOAT>0.0</FLOAT>
<TEXT>command_version</TEXT>
<INT>1</INT>
<TEXT>default_command_version</TEXT>
<INT>1</INT>
<TEXT>max_command_version</TEXT>
<INT>2</INT></RESULT>
</RESULT>

You need to specify tsv as output_type value to get a result in TSV format:

> status --output_type tsv
0     1327721664.82675        0.000113964080810547
"alloc_count" 146
"starttime"   1327721626
"uptime"      38
"version"     "1.2.9-92-gb87d9f8"
"n_queries"   0
"cache_hit_rate"      0.0
"command_version"     1
"default_command_version"     1
"max_command_version" 2
END

You need to specify msgpack as output_type value to get a result in MessagePack format:

> status --output_type msgpack
(... omitted because MessagePack is binary data format. ...)

  HTTP

You can use HTTP query interface by groonga --protocol http -s DB_PATH. Groonga HTTP server starts on port 10041 by default. In this query interface, you can specify output format type by extension.

If you don't specify extension, you will get a result in JSON format:

% curl http://localhost:10041/d/status
[[0,1327809294.54311,0.00082087516784668],{"alloc_count":155,"starttime":1327809282,"uptime":12,"version":"1.2.9-92-gb87d9f8","n_queries":0,"cache_hit_rate":0.0,"command_version":1,"default_command_version":1,"max_command_version":2}]

You can specify json as extension to get a result in JSON format explicitly:

% curl http://localhost:10041/d/status.json
[[0,1327809319.01929,9.5367431640625e-05],{"alloc_count":157,"starttime":1327809282,"uptime":37,"version":"1.2.9-92-gb87d9f8","n_queries":0,"cache_hit_rate":0.0,"command_version":1,"default_command_version":1,"max_command_version":2}]

You need to specify xml as extension to get a result in XML format:

% curl http://localhost:10041/d/status.xml
<?xml version="1.0" encoding="utf-8"?>
<RESULT CODE="0" UP="1327809339.5782" ELAPSED="9.56058502197266e-05">
<RESULT>
<TEXT>alloc_count</TEXT>
<INT>159</INT>
<TEXT>starttime</TEXT>
<INT>1327809282</INT>
<TEXT>uptime</TEXT>
<INT>57</INT>
<TEXT>version</TEXT>
<TEXT>1.2.9-92-gb87d9f8</TEXT>
<TEXT>n_queries</TEXT>
<INT>0</INT>
<TEXT>cache_hit_rate</TEXT>
<FLOAT>0.0</FLOAT>
<TEXT>command_version</TEXT>
<INT>1</INT>
<TEXT>default_command_version</TEXT>
<INT>1</INT>
<TEXT>max_command_version</TEXT>
<INT>2</INT></RESULT>
</RESULT>

You need to specify tsv as extension to get a result in TSV format:

% curl http://localhost:10041/d/status.tsv
0     1327809366.84187        8.44001770019531e-05
"alloc_count" 159
"starttime"   1327809282
"uptime"      84
"version"     "1.2.9-92-gb87d9f8"
"n_queries"   0
"cache_hit_rate"      0.0
"command_version"     1
"default_command_version"     1
"max_command_version" 2
END

You need to specify msgpack as extension to get a result in MessagePack format:

% curl http://localhost:10041/d/status.msgpack
(... omitted because MessagePack is binary data format. ...)

  Command

Command is the most important processing unit in query API. You request a processing to groonga by a command.

This section describes about command and built-in commands.

  コマンドバージョン

  概要

groonga1.1からコマンドバージョンという概念が導入されます。コマンドバージョンは、selectやloadなどのgroongaのコマンドの仕様の互換性を表します。groongaパッケージのバージョンが新しくなったとしても、同一のコマンドバージョンが使用可能であるなら、すべてのコマンドについて互換性が保証されます。コマンドバージョンが異なれば、同じ名前のコマンドであっても、動作に互換性がない可能性があります。

あるバージョンのgroongaは、二つのコマンドバージョンを同時にサポートするようになります。 使用するコマンドバージョンは、groongaを起動する際のコマンドラインオプションないしコンフィグファイルにdefault-commnad-versionパラメータを与えることによって指定できます。また、個々のコマンドを実行する際に、command_versionパラメータを与えることによっても指定することができます。

コマンドバージョンは1からはじまり、更新されるたびに1ずつ大きくなります。現状のgroongaのコマンドの仕様はcommand-version 1という扱いになります。次回提供するgroongaは、command-version 1とcommand-version 2の二つをサポートすることになります。

  バージョンの位置づけ

あるバージョンのgroongaにおいてサポートされるコマンドバージョンは、develop, stable,deprecatedのいずれかの位置づけとなります。

develop
    まだ開発中であり、仕様が変更される可能性があります。

stable
    使用可能であり仕様も安定しています。その時点で使用することが推奨されます。

deprecated
    使用可能であり仕様も安定していますが、廃止予定であり使用が推奨されません。

    あるバージョンのgroongaがサポートする二つのコマンドバージョンのうち、いずれか一つが必ずstableの位置づけとなります。残りの一つは、developないしdeprecatedとなります。

    たとえば下記のようにgroongaのサポートするコマンドバージョンは推移します。:

    groonga1.1: command-version1=stable     command-version2=develop
    groonga1.2: command-version1=deprecated command-version2=stable
    groonga1.3: command-version2=stable     command-version3=develop
    groonga1.4: command-version2=deprecated command-version3=stable
    groonga1.5: command-version3=stable     command-version4=develop

    あるコマンドバージョンははじめにdevelop扱いとしてリリースされ、やがてstableに移行します。 その後二世代経過するとそのコマンドバージョンはdeprecated扱いとなります。さらに次のコマンドバージョンがリリースされると、deprecatedだったコマンドバージョンはサポート対象外となります。

    default-commnad-versionパラメータやcommand_versionパラメータを指定せずにgroongaコマンドを実行した際には、その時点でstableであるコマンドバージョンが指定されたものとみなします。

    groongaプロセス起動時に、default-command-versionパラメータにstable扱いでないコマンドバージョンを指定した場合には、警告メッセージがログファイルに出力されます。また、サポート範囲外のコマンドバージョンを指定した場合にはエラーとなり、プロセスは速やかに停止します。

  コマンドバージョンの指定方法

コマンドバージョンの指定方法はgroonga実行モジュールの引数として指定する方法と各コマンドの引数として指定する方法があります。

  default-command-versionパラメータ

groonga実行モジュールの引数としてdefault-command-versionパラメータを指定できます。 (configファイルの中に指定することも可能です)

実行例:

groonga --default-command-version 1

そのプロセスで実行するすべてのコマンドについて、デフォルトのコマンドバージョンとして指定されたバージョンを使用します。指定されたコマンドバージョンがstableであった場合にはなんのメッセージも表示されずそのまま起動します。指定されたコマンドバージョンがdevelopあるいはdeprecatedであった場合には、groonga.logファイルに警告メッセージを出力します。指定されたコマンドバージョンがサポート対象外であった場合には標準エラー出力にエラーメッセージを出力し、プロセスは速やかに終了します。

  command_versionパラメータ

select,loadなどのすべてのgroongaコマンドにcommand_versionが指定できます。

実行例:

select --command_version 1 --table tablename

指定されたコマンドバージョンでコマンドを実行します。指定されたコマンドバージョンがサポート対象外であった場合にはエラーが返されます。command-versionが指定されなかった場合は、当該プロセス起動時にdefault-command-versionに指定した値が指定されたものとみなします。

  Output format

  Summary

Commands output their result as JSON, MessagePack, XML or TSV format.

JSON and MessagePack output have the same structure. XML and TSV are their original structure.

JSON or MessagePack is recommend format. XML is useful for visual result check. TSV is just for special use. Normally you doesn't need to use TSV.

  JSON and MessagePack

This secsion describes the structure of command result on JSON and MessagePack format. JSON is used to show structure because MessagePack is binary format. Binary format isn't proper for documenataion.

JSON and MessagePack uses the following structure:

[HEADER, BODY]

For example:

[
  [
    0,
    1337566253.89858,
    0.000355720520019531
  ],
  [
    [
      [
        1
      ],
      [
        [
          "_id",
          "UInt32"
        ],
        [
          "_key",
          "ShortText"
        ],
        [
          "content",
          "Text"
        ],
        [
          "n_likes",
          "UInt32"
        ]
      ],
      [
        2,
        "Groonga",
        "I started to use groonga. It's very fast!",
        10
      ]
    ]
  ]
]

In the example, the following part is HEADER:

[
  0,
  1337566253.89858,
  0.000355720520019531
]

The following part is BODY:

[
  [
    [
      1
    ],
    [
      [
        "_id",
        "UInt32"
      ],
      [
        "_key",
        "ShortText"
      ],
      [
        "content",
        "Text"
      ],
      [
        "n_likes",
        "UInt32"
      ]
    ],
    [
      2,
      "Groonga",
      "I started to use groonga. It's very fast!",
      10
    ]
  ]
]

  HEADER

HEADER is an array. The content of HEADER has some patterns.

  Success case

HEADER has three elements on success:

[0, UNIX_TIME_WHEN_COMMAND_IS_STARTED, ELAPSED_TIME]

The first element is always 0.

UNIX_TIME_WHEN_COMMAND_IS_STARTED is the number of seconds since 1970-01-01 00:00:00 UTC when the command is started processing. ELAPSED_TIME is the elapsed time for processing the command in seconds. Both UNIX_TIME_WHEN_COMMAND_IS_STARTED and ELAPSED_TIME are float value. The precision of them are nanosecond.

  Error case

HEADER has four or five elements on error:

[
  RETURN_CODE,
  UNIX_TIME_WHEN_COMMAND_IS_STARTED,
  ELAPSED_TIME,
  ERROR_MESSAGE,
  ERROR_LOCATION
]

ERROR_LOCATION may not be included in HEADER but other four elements are always included.

RETURN_CODE is non 0 value. See return_code about available return codes.

UNIX_TIME_WHEN_COMMAND_IS_STARTED and ELAPSED_TIME are the same as success case.

ERROR_MESSAGE is an error message in string.

ERROR_LOCATION is optional. If error location is collected, ERROR_LOCATION is included. ERROR_LOCATION is an array. ERROR_LOCATION has one ore two elements:

[
  LOCATION_IN_GROONGA,
  LOCATION_IN_INPUT
]

LOCATION_IN_GROONGA is the source location that error is occurred in groonga. It is useful for groonga developers but not useful for users. LOCATION_IN_GROONGA is an array. LOCATION_IN_GROONGA has three elements:

[
  FUNCTION_NAME,
  SOURCE_FILE_NAME,
  LINE_NUMBER
]

FUNCTION_NAME is the name of function that error is occurred.

SOURCE_FILE_NAME is the name of groonga's source file that error is occurred.

LINE_NUMBER is the line number of SOURCE_FILE_NAME that error is occurred.

LOCATION_IN_INPUT is optional. LOCATION_IN_INPUT is included when the location that error is occurred in input file is collected. Input file can be specified by --file command line option for groonga command. LOCATION_IN_GROONGA is an array. LOCATION_IN_GROONGA has three elements:

[
  INPUT_FILE_NAME,
  LINE_NUMBER,
  LINE_CONTENT
]

INPUT_FILE_NAME is the input file name that error is occurred.

LINE_NUMBER is the line number of INPUT_FILE_NAME that error is occurred.

LINE_CONTENT is the content at LINE_NUMBER in INPUT_FILE_NAME.

  BODY

BODY content depends on the executed command. It may be omitted.

BODY may be an error message on error case.

  XML

TODO

  TSV

TODO

  See also

•   return_code describes about return code.

  Return code

  Summary

Return code is used to show whether a processing is succeeded or not. If the processing is not succeeded, return code shows error type.

Return code is used in C API and query API. You can check return code via grn_ctx_t::rc in C API. You can check return code by looking the header element in query API. See output_format about the header element in query API.

  List

Here is a list of return codes. GRN_SUCCESS (= 0) means that the processing is succeeded. Return codes that have negative value show error type. GRN_END_OF_DATA is a special return code. It is used only C API. It is not showen in query API.

•   0: GRN_SUCCESS

•   1: GRN_END_OF_DATA

•   -1: GRN_UNKNOWN_ERROR

•   -2: GRN_OPERATION_NOT_PERMITTED

•   -3: GRN_NO_SUCH_FILE_OR_DIRECTORY

•   -4: GRN_NO_SUCH_PROCESS

•   -5: GRN_INTERRUPTED_FUNCTION_CALL

•   -6: GRN_INPUT_OUTPUT_ERROR

•   -7: GRN_NO_SUCH_DEVICE_OR_ADDRESS

•   -8: GRN_ARG_LIST_TOO_LONG

•   -9: GRN_EXEC_FORMAT_ERROR

•   -10: GRN_BAD_FILE_DESCRIPTOR

•   -11: GRN_NO_CHILD_PROCESSES

•   -12: GRN_RESOURCE_TEMPORARILY_UNAVAILABLE

•   -13: GRN_NOT_ENOUGH_SPACE

•   -14: GRN_PERMISSION_DENIED

•   -15: GRN_BAD_ADDRESS

•   -16: GRN_RESOURCE_BUSY

•   -17: GRN_FILE_EXISTS

•   -18: GRN_IMPROPER_LINK

•   -19: GRN_NO_SUCH_DEVICE

•   -20: GRN_NOT_A_DIRECTORY

•   -21: GRN_IS_A_DIRECTORY

•   -22: GRN_INVALID_ARGUMENT

•   -23: GRN_TOO_MANY_OPEN_FILES_IN_SYSTEM

•   -24: GRN_TOO_MANY_OPEN_FILES

•   -25: GRN_INAPPROPRIATE_I_O_CONTROL_OPERATION

•   -26: GRN_FILE_TOO_LARGE

•   -27: GRN_NO_SPACE_LEFT_ON_DEVICE

•   -28: GRN_INVALID_SEEK

•   -29: GRN_READ_ONLY_FILE_SYSTEM

•   -30: GRN_TOO_MANY_LINKS

•   -31: GRN_BROKEN_PIPE

•   -32: GRN_DOMAIN_ERROR

•   -33: GRN_RESULT_TOO_LARGE

•   -34: GRN_RESOURCE_DEADLOCK_AVOIDED

•   -35: GRN_NO_MEMORY_AVAILABLE

•   -36: GRN_FILENAME_TOO_LONG

•   -37: GRN_NO_LOCKS_AVAILABLE

•   -38: GRN_FUNCTION_NOT_IMPLEMENTED

•   -39: GRN_DIRECTORY_NOT_EMPTY

•   -40: GRN_ILLEGAL_BYTE_SEQUENCE

•   -41: GRN_SOCKET_NOT_INITIALIZED

•   -42: GRN_OPERATION_WOULD_BLOCK

•   -43: GRN_ADDRESS_IS_NOT_AVAILABLE

•   -44: GRN_NETWORK_IS_DOWN

•   -45: GRN_NO_BUFFER

•   -46: GRN_SOCKET_IS_ALREADY_CONNECTED

•   -47: GRN_SOCKET_IS_NOT_CONNECTED

•   -48: GRN_SOCKET_IS_ALREADY_SHUTDOWNED

•   -49: GRN_OPERATION_TIMEOUT

•   -50: GRN_CONNECTION_REFUSED

•   -51: GRN_RANGE_ERROR

•   -52: GRN_TOKENIZER_ERROR

•   -53: GRN_FILE_CORRUPT

•   -54: GRN_INVALID_FORMAT

•   -55: GRN_OBJECT_CORRUPT

•   -56: GRN_TOO_MANY_SYMBOLIC_LINKS

•   -57: GRN_NOT_SOCKET

•   -58: GRN_OPERATION_NOT_SUPPORTED

•   -59: GRN_ADDRESS_IS_IN_USE

•   -60: GRN_ZLIB_ERROR

•   -61: GRN_LZO_ERROR

•   -62: GRN_STACK_OVER_FLOW

•   -63: GRN_SYNTAX_ERROR

•   -64: GRN_RETRY_MAX

•   -65: GRN_INCOMPATIBLE_FILE_FORMAT

•   -66: GRN_UPDATE_NOT_ALLOWED

•   -67: GRN_TOO_SMALL_OFFSET

•   -68: GRN_TOO_LARGE_OFFSET

•   -69: GRN_TOO_SMALL_LIMIT

•   -70: GRN_CAS_ERROR

•   -71: GRN_UNSUPPORTED_COMMAND_VERSION

  See also

•   output_format shows where return code is appeared in query API response.

•   /spec/gqtp: GQTP protocol also uses return code as status but it uses 2byte unsigned integer. So return codes that have negative value are statuses that have positive value in GQTP protocol. You can convert status value in GQTP protocol to return code by handling it as 2byte signed integer.

  cache_limit

  名前

cache_limit - cacheサイズの設定・取得

  書式

cache_limit max

  説明

groonga組込コマンドの一つであるcache_limitについて説明します。組込コマンドは、groonga実行ファイルの引数、標準入力、またはソケット経由でgroongaサーバにリクエストを送信することによって実行します。

cache_limitは、クエリキャッシュの最大件数を取得したり設定したりします。

  引数

max クエリキャッシュの最大件数を整数で指定します。 maxが指定されなかった場合には、クエリキャッシュの最大件数は変更せず、 現在の設定値のみが返されます。

  返値

  json

[以前の設定値]

以前の設定値 すでに設定されていたクエリキャッシュの最大件数を返す。

  例

cache_limit 4
[100]

  check

  名前

check - オブジェクトの状態表示

  書式

check obj

  説明

groonga組込コマンドの一つであるcheckについて説明します。組込コマンドは、groonga実行ファイルの引数、標準入力、またはソケット経由でgroongaサーバにリクエストを送信することによって実行します。

checkコマンドは、groongaプロセス内の指定したオブジェクトの状態を表示します。主にデータベースが壊れた場合など異常時の問題解決のために使用することを想定しています。デバッグ用のため、返値のフォーマットが安定しているということは保証されません。（フォーマットが変更される可能性が高い）

  引数

obj 状態を表示するオブジェクトの名前を指定します。

  返値

  json形式

チェックするオブジェクトにより返される値が変わります。

インデックスカラムの場合:

下記のような配列が出力されます。
  [インデックスの状態, バッファの状態1, バッファの状態2, ...]

インデックスの状態 には下記の項目がハッシュ形式で出力されます。 flags 指定されているフラグ値です。16進数で表現されています。

max sid セグメントのうち最も大きなIDです。

number of garbage segments ゴミセグメントの数です。

number of array segments 配列セグメントの数です。

max id of array segment 配列セグメントのうち最も大きなIDです。

number of buffer segments バッファセグメントの数です。

max id of buffer segment バッファセグメントのうち最も大きなIDです。

max id of physical segment in use 使用中の論理セグメントのうち最も大きなIDです。

number of unmanaged segments 管理されていないセグメントの数です。

total chunk size チャンクサイズの合計です。

max id of chunk segments in use 使用中のチャンクセグメントのうち最も大きなIDです。

number of garbage chunk 各チャンク毎のゴミの数です。

バッファの状態 には下記の項目がハッシュ形式で出力されます。 buffer id バッファIDです。

chunk size チャンクのサイズです。

buffer term バッファ内にある語の一覧です。各語の状態は以下のような配列となっています。 [語, バッファに登録されている語のID, 用語集に登録されている語のID, バッファ内でのサイズ, チャンク内でのサイズ]

buffer free バッファの空き容量です。

size in buffer バッファの使用量です。

nterms バッファ内にある語の数です。

nterms with chunk バッファ内にある語のうち、チャンクを使っている語の数です。

  例

テーブルTermsのインデックスカラムnameの状態を表示します。:

check Terms.name
[{"flags":"00008202",
  "max sid":1,
  "number of garbage segments":0,
  "number of array segments":1,
  "max id of array segment":1,
  "number of buffer segments":110,
  "max id of buffer segment":111,
  "max id of physical segment in use":111,
  "number of unmanaged segments":4294967185,
  "total chunk size":7470239,
  "max id of chunk segments in use":127,
  "number of garbage chunk":[0,0,0,0,0,0,0,0,2,2,0,0,0,0,0]},
 {"buffer id":0,
  "chunk size":94392,
  "buffer term":["596","59777","6",...],
  "buffer free":152944,
  "size in buffer":7361,
  "nterms":237,
  "nterms with chunk":216,
  "buffer id":1,
  "chunk size":71236,
  "buffer term":[["に述",18149,18149,2,25,6,6],
                 ["に追",4505,4505,76,485,136,174],
                 ["に退",26568,26568,2,9,2,2],
                 ...],
  "buffer free":120000,
  "size in buffer":11155,
  "nterms":121,
  "nterms with chunk":116},
  {"buffer id":1,
   ...},
  ...]

  clearlock

  名前

clearlock - オブジェクトにセットされたロックを解除する

  書式

clearlock objname

  説明

groonga組込コマンドの一つであるclearlockについて説明します。組込コマンドは、groonga実行ファイルの引数、標準入力、またはソケット経由でgroongaサーバにリクエストを送信することによって実行します。

clearlockは、対象となるオブジェクト(データベース,テーブル,インデックス等)を指定し、オブジェクトにかけられたロックを再帰的に解除します。

  引数

objname 対象となるオブジェクト名を指定します。空の場合、開いているdbオブジェクトが対象となります。

  返値

  json形式

[成功かどうかのフラグ]

成功かどうかのフラグ エラーが生じなかった場合にはtrue、エラーが生じた場合にはfalseを返す。

  例

開いているデータベースのロックをすべて解除する:

clearlock
[true]

テーブル名 Entry のカラム body のロックを解除する:

clearlock Entry.body
[true]

  関連項目

load

  column_create

  名前

column_create - カラムの追加

  書式

column_create table name flags type [source]

  説明

groonga組込コマンドの一つであるcolumn_createについて説明します。組込コマンドは、groonga実行ファイルの引数、標準入力、またはソケット経由でgroongaサーバにリクエストを送信することによって実行します。

column_createは、使用しているデータベースのテーブルに対してカラムを追加します。

  引数

table カラムを追加するテーブルの名前を指定します。

name 作成するカラムの名前を指定します。カラム名は、テーブルの中で一意でなければなりません。

ピリオド('.'), コロン(':')を含む名前のカラムは作成できません。また、アンダースコア('_')で始まる名前は予約済みであり、使用できません。

flags カラムの属性を表す以下の数値か、パイプ('|')で組み合わせたシンボル名を指定します。

0, COLUMN_SCALAR
    単一の値が格納できるカラムを作成します。

1, COLUMN_VECTOR
    複数の値の配列を格納できるカラムを作成します。

2, COLUMN_INDEX
    インデックス型のカラムを作成します。

    インデックス型のカラムについては、flagsの値に以下の値を加えることによって、追加の属 性を指定することができます。

128, WITH_SECTION
    段落情報を格納するインデックスを作成します。

256, WITH_WEIGHT
    ウェイト情報を格納するインデックスを作成します。

512, WITH_POSITION
    位置情報を格納するインデックス(完全転置インデックス)を作成します。

    type 値の型を指定します。groongaの組込型か、同一データベースに定義済みのユーザ定義型、定義済みのテーブルを指定することができます。

    source インデックス型のカラムを作成した場合は、インデックス対象となるカラムをsource引数に指定します。

  返値

  json形式

[成功かどうかのフラグ]

成功かどうかのフラグ エラーが生じなかった場合にはtrue、エラーが生じた場合にはfalseを返す。

  例

テーブルEntryに、ShortText型の値を格納するカラム、bodyを作成します。:

column_create Entry body --type ShortText
[true]

テーブルTermに、Entryテーブルのbodyカラムの値を対象とする完全転置インデックス型カラム、entry_bodyを作成します。:

column_create Term entry_body COLUMN_INDEX|WITH_POSITION Entry body
[true]

  column_list

  名前

column_list - テーブルに定義されているカラムのリスト表示

  書式

column_list table

  説明

groonga組込コマンドの一つであるcolumn_listについて説明します。組込コマンドは、groonga実行ファイルの引数、標準入力、またはソケット経由でgroongaサーバにリクエストを送信することによって実行します。

column_listはテーブルに定義されているカラムをリスト表示します。

  引数

table
    カラム情報を出力するテーブルの名前を指定します。

  返値

  json形式

カラム名一覧を以下の形式で返却します。:

[[[カラム情報名1,カラム情報型1],...], カラム情報1,...]

カラム情報名n カラム情報n には複数の情報が含まれますが、そこに入る情報がどんな内容かを示す名前を出力します。 情報名は以下の通りです。

id カラムオブジェクトに割り当てられたID

name カラム名

path カラム値を格納するファイル名

type スカラ型、ベクタ型、インデックス型の種別

flags カラムのflags属性

domain カラムの値の属する型

range テーブルのkeyの型

source インデックスカラムのとき、インデックス対象カラム名の配列

カラム情報型n カラム情報の型を出力します。

カラム情報n カラム情報名n で示された情報の配列を出力します。 情報の順序は カラム情報名n の順序と同じです。

  例

column_list Entry
[[["id", "UInt32"],
  ["name","ShortText"],
  ["path","ShortText"],
  ["type","ShortText"],
  ["flags","ShortText"],
  ["domain", "ShortText"],
  ["range", "ShortText"],
  ["source","ShortText"]],
 [258,
  "Entry.body",
  "test.db.0000102",
  "var",
  "COLUMN_SCALAR|COMPRESS_NONE|PERSISTENT",
  "Entry",
  "ShortText",
  []]]

注: 実際は改行が入りません。

  column_remove

  名前

column_remove - テーブルに定義されているカラムの削除

  書式

column_remove table name

  説明

groonga組込コマンドの一つであるcolumn_removeについて説明します。組込コマンドは、groonga実行ファイルの引数、標準入力、またはソケット経由でgroongaサーバにリクエストを送信することによって実行します。

column_removeはテーブルに定義されているカラムを削除します。 また、付随するインデックスも削除されます。[#]_

  引数

table
    削除対象のカラムが定義されているテーブルの名前を指定します。

name
    削除対象のカラム名を指定します。

  返値

  json形式

[成功かどうかのフラグ]

成功かどうかのフラグ エラーが生じなかった場合にはtrue、エラーが生じた場合にはfalseを返す。

  例

column_remove Entry body
[true]
脚注

[1] マルチセクションインデックスの一部である場合も、インデックスが削除されます。

  define_selector

  名前

define_selector - 検索コマンドを定義

  書式

define_selector name table [match_columns [query [filter [scorer [sortby
                [output_columns [offset [limit [drilldown [drilldown_sortby
                [drilldown_output_columns [drilldown_offset [drilldown_limit]]]]]]]]]]]]]

  説明

groonga組込コマンドの一つであるdefine_selectorについて説明します。組込コマンドは、groonga実行ファイルの引数、標準入力、またはソケット経由でgroongaサーバにリクエストを送信することによって実行します。

define_selectorは、検索条件をカスタマイズした新たな検索コマンドを定義します。

  引数

name 定義するselectorコマンドの名前を指定します。

table 検索対象のテーブルを指定します。

match_columns 追加するselectorコマンドのmatch_columns引数のデフォルト値を指定します。

query 追加するselectorコマンドのquery引数のデフォルト値を指定します。

filter 追加するselectorコマンドのfilter引数のデフォルト値を指定します。

scorer 追加するselectorコマンドのscorer引数のデフォルト値を指定します。

sortby 追加するselectorコマンドのsortby引数のデフォルト値を指定します。

output_columns 追加するselectorコマンドのoutput_columns引数のデフォルト値を指定します。

offset 追加するselectorコマンドのoffset引数のデフォルト値を指定します。

limit 追加するselectorコマンドのlimit引数のデフォルト値を指定します。

drilldown 追加するselectorコマンドのdrilldown引数のデフォルト値を指定します。

drilldown_sortby 追加するselectorコマンドのdrilldown_sortby引数のデフォルト値を指定します。

drilldown_output_columns 追加するselectorコマンドのdrilldown_output_columns引数のデフォルト値を指定します。

drilldown_offset 追加するselectorコマンドのdrilldown_offset引数のデフォルト値を指定します。

drilldown_limit 追加するselectorコマンドのdrilldown_limit引数のデフォルト値を指定します。

  返値

  json形式

[成功かどうかのフラグ]

成功かどうかのフラグ エラーが生じなかった場合にはtrue、エラーが生じた場合にはfalseを返す。

  例

テーブルEntryの全レコード・全カラムの値を出力するselectorコマンドを定義します。:

define_selector entry_selector Entry
[true]

  関連項目

/reference/grn_expr

  defrag

  名前

defrag - オブジェクトにセットされたロックを解除する

  書式

defrag objname threshold

  説明

groonga組込コマンドの一つであるdefragについて説明します。組込コマンドは、groonga実行ファイルの引数、標準入力、またはソケット経由でgroongaサーバにリクエストを送信することによって実行します。

defragは、対象となるオブジェクト(データベースか可変長サイズカラム)を指定し、オブジェクトのフラグメンテーションを解消します。

  引数

objname 対象となるオブジェクト名を指定します。空の場合、開いているdbオブジェクトが対象となります。

  返値

  json形式

[フラグメンテーション解消を実行したセグメントの数]

フラグメンテーション解消を実行したセグメントの数 フラグメンテーション解消を実行したセグメントの数を返す。

  例

開いているデータベースのフラグメンテーションを解消する:

defrag
[300]

テーブル名 Entry のカラム body のフラグメンテーションを解消する:

defrag Entry.body
[30]

  delete

  名前

delete - 一件のレコードの削除

  書式

delete table [key [id [filter]]]

  説明

groonga組込コマンドの一つであるdeleteについて説明します。組込コマンドは、groonga実行ファイルの引数、標準入力、またはソケット経由でgroongaサーバにリクエストを送信することによって実行します。

deleteは、使用しているデータベースのテーブルに1件のレコードを削除します。

  引数

table レコードを削除しようとするテーブルの名前を指定します。

key 削除するレコードの主キー値を指定します。主キーなしのテーブルの場合はこのパラメータを指定しても無視されます(idパラメータを代わりに指定します)。

id レコードIDによってレコードを指定します。idパラメータを指定する場合は、keyパラメータを指定してはいけません。

filter script形式のgrn_expr文字列によってレコードを指定します。filterパラメータを指定する場合は、id及びkeyパラメータを指定してはいけません。

返値 ---

  json形式

[成功かどうかのフラグ]

成功かどうかのフラグ エラーが生じなかった場合にはtrue、エラーが生じた場合にはfalseを返す。

  例

テーブルEntryからレコードを削除します。:

delete Entry abandon
[true]

  関連項目

load

  dump

  名前

dump - データベースのスキーマとデータを出力する

  書式

dump [tables]

  説明

groonga組込コマンドの一つであるdumpについて説明します。組込コマンドは、groonga実行ファイルの引数、標準入力、またはソケット経由でgroongaサーバにリクエストを送信することによって実行します。

dumpはデータベースのスキーマとデータを後から読み込めるフォーマットで出力します。dumpの結果は大きくなるため、主にコマンドラインから使うことを想定しています。データベースのバックアップが主な利用方法です。

dumpが出力するフォーマットは直接groongaが解釈できるフォーマットです。そのため、以下のようにしてデータベースをコピーすることができます。:

% groonga original/db dump > dump.grn
% mkdir backup
% groonga -n backup/db < dump.grn

  引数

tables 出力対象のテーブルを「,」（カンマ）区切りで指定します。存在しないテーブルを指定した場合は無視されます。

  返値

データベースのスキーマとデータをgroongaの組み込みコマンド呼び出し形式で出力します。output_type指定は無視されます。

  例

データベース内のすべてのデータを出力:

> dump
table_create LocalNames 48 ShortText
table_create Entries 48 ShortText
column_create Entries local_name 0 LocalNames
column_create LocalNames Entries_local_name 2 Entries local_name
...
load --table LocalNames
[
["_key"],
["Items"],
["BLT"],
...
]
...

データベース内のスキーマと特定のテーブルのデータのみ出力:

> dump --tables Users,Sites
table_create Users TABLE_HASH_KEY ShortText
column_create Users name COLUMN_SCALAR ShortText
table_create Comments TABLE_PAT_KEY ShortText
column_create Comments text COLUMN_SCALAR ShortText
table_create Sites TABLE_NO_KEY
column_create Sites url COLUMN_SCALAR ShortText
load --table Users
[
["_key"],
["mori"],
["yu"],
...
]
load --table Sites
[
["_id","url"],
[1,"http://groonga.org/"],
[2,"http://qwik.jp/senna/"],
...
]

  load

  名前

load - データのロード

  書式

load values table [columns [ifexists [input_type]]]

  説明

groonga組込コマンドの一つであるloadについて説明します。組込コマンドは、groonga実行ファイルの引数、標準入力、またはソケット経由でgroongaサーバにリクエストを送信することによって実行します。

loadは、使用しているデータベースのテーブルにレコードを登録し、カラムの値を更新します。

  引数

values input_typeに指定する形式で登録するレコードの値を表現した文字列を渡します。

input_typeがjsonである場合には、以下のいずれかの形式が使用できます。

形式1 [[カラム名1, カラム名2,..], [カラム値1, カラム値2,..], [カラム値1, カラム値2,..],..]

形式2 [{カラム名1: カラム値1, カラム名2: カラム値2}, {カラム名1: カラム値1, カラム名2: カラム値2},..]

    形式1の[カラム名1, カラム名2,..]の要素はcolumns引数が省略された場合のみ有効です。

    対象のテーブルが主キーを持つテーブルであった場合は、カラム名の中に'_key'(主キーを示す疑似カラム名)が含まれていなければなりません。

    values引数が省略された場合には、括弧の対応が取れるまで標準入力からvaluesの値を読み取ります。引数として値を指定する場合は、文字列のエスケープが必要ですが、標準入力から与える文字列はエスケープする必要がありません。

    続きの文字列については、空白文字(' ')をエスケープする必要はありません。

    table レコードを追加しようとするテーブルの名前を指定します。

    columns テーブルに登録するレコードに値を設定するカラム名のリストを、カンマ区切りで指定します。

    ifexists 指定した主キーに対応するレコードが既にテーブルに登録済みであった場合に実行するscript形式のgrn_expr文字列を指定します。ifexistsにgrn_exprが指定された場合は、式の値が真である場合に限り、その他のカラムの値が更新されます。(デフォルトはtrue)

    input_type 入力形式を指定します。JSONのみに対応しています。

  返値

  JSON形式

[登録件数]

登録件数 テーブルに登録されたレコードの件数が返されます。

  例

テーブルEntryにレコードを登録します。:

load --table Entry --input_type json --values [{\"_key\":\"abandon\",\"body\":\"放棄する\"}]
[1]

標準入力からvaluesの値を与えます。:

load --table Entry --input_type json
[
{"_key": "abbreviate", "body": "短縮する"}
]
[1]

  関連項目

/reference/grn_expr

  log_level

  名前

log_level - ログ出力レベルの設定

  書式

log_level level

  説明

groonga組込コマンドの一つであるlog_levelについて説明します。組込コマンドは、groonga実行ファイルの引数、標準入力、またはソケット経由でgroongaサーバにリクエストを送信することによって実行します。

log_levelは、ログ出力レベルを設定します。

  引数

level 設定するログ出力レベルの値を以下のいずれかで指定します。 EMERG ALERT CRIT error warning notice info debug

  返値

  json形式

[成功かどうかのフラグ]

成功かどうかのフラグ エラーが生じなかった場合にはtrue、エラーが生じた場合にはfalseを返す。

  例

log_level warning
[true]

  関連項目

log_put log_reopen

  log_put

  名前

log_put - ログ出力

  書式

log_put level message

  説明

groonga組込コマンドの一つであるlog_putについて説明します。組込コマンドは、groonga実行ファイルの引数、標準入力、またはソケット経由でgroongaサーバにリクエストを送信することによって実行します。

log_putは、ログにmessageを出力します。

  引数

level 設定するログ出力レベルの値を以下のいずれかで指定します。 EMERG ALERT CRIT error warning notice info debug

message 出力する文字列を指定します。

  返値

  json形式

[成功かどうかのフラグ]

成功かどうかのフラグ エラーが生じなかった場合にはtrue、エラーが生じた場合にはfalseを返す。

  例

log_put ERROR ****MESSAGE****
[true]

  関連項目

log_level log_reopen

  log_reopen

  名前

log_reopen - ログファイルの再読み込み

  書式

log_reopen

  説明

groonga組込コマンドの一つであるlog_reopenについて説明します。組込コマンドは、groonga実行ファイルの引数、標準入力、またはソケット経由でgroongaサーバにリクエストを送信することによって実行します。

log_reopenは、ログファイルを再読み込みします。

現在、デフォルトのログ関数を用いている場合のみに対応しています。

  引数

ありません。

  返値

  json形式

[成功かどうかのフラグ]

成功かどうかのフラグ エラーが生じなかった場合にはtrue、エラーが生じた場合にはfalseを返す。

  例

log_reopen
[true]

  log_reopenを用いたログのローテーション

1.  ログファイルをmvなどで移動する。 ログはmvで移動された先のファイルに書き込まれる。

2.  log_reopenコマンドを実行する。

3.  既存のログファイル名と同じファイル名で、新たなログファイルが作成される。 今後のログは新たなログファイルに書き込まれる。

  関連項目

log_level log_put

  normalize

Caution
    normalize command is the experimental feature. This command may be changed in the future.

  Summary

normalize command normalizes text by the specified normalizer.

There is no need to create table to use normalize command. It is usefull for you to check the results of normalizer.

  Syntax

normalize commands takes two parameters - normalizer and string. Both of them are required.

normalize normalizer string

  Usage

Here is a simple example of normalize command.

Execution example:

normalize NormalizerAuto "aBcDe 123"
# [[0, 1337566253.89858, 0.000355720520019531], "abcde 123"]

  Parameters

This section describes parameters of normalizer.

  Required parameter

There are required parameters, normalizer and string.

  normalizer

It specifies the name of normalizer. Currently, normalize command accepts NormalizerAuto or NormalizerNFKC51 as built-in normalizer. If you want to try another normalizer, you need to register additional normalizer plugin by register command.

  string

It specifies any string which you want to normalize.

  Return value

[HEADER, normalized]

HEADER The format of HEADER is [0, UNIX_TIME_WHEN_COMMAND_IS_STARTED, ELAPSED_TIME]. See /reference/command/output_format about HEADER.

normalized normalized is the normalized text by the specified normalizer.

  See also

•   /reference/normalizers

  quit

  名前

quit - セッション終了

  書式

quit

  説明

groonga組込コマンドの一つであるquitについて説明します。組込コマンドは、groonga実行ファイルの引数、標準入力、またはソケット経由でgroongaサーバにリクエストを送信することによって実行します。

quitは、groongaプロセスとのセッションを終了します。クライアントプロセスならばgroongaプロセスとの接続を切ります。

  引数

ありません。

  返値

ありません。

  例

quit

  register

  Summary

register command registers a plugin. You need to register a plugin before you use a plugin.

You need just one register command for a plugin in the same database because registered plugin information is written into the database. When you restart your groonga process, groonga process loads all registered plugins without register command.

Note
    Registered plugins can't be removed for now.

  Syntax

register has a parameter path. It is required parameter:

register path

  Usage

Here is a sample that registers QueryExpanderTSV query expander that is included in ${PREFIX}/lib/groonga/plugins/query_expanders/tsv.so.

Execution example:

register query_expanders/tsv
# [[0, 1337566253.89858, 0.000355720520019531], true]

You can omit ${PREFIX}/lib/groonga/plugins/ and suffix (.so). They are completed automatically.

You can specify absolute path such as register /usr/lib/groonga/plugins/query_expanders/tsv.so.

  Return value

register returns true as body on success such as:

[HEADER, true]

If register fails, error details are in HEADER.

See /reference/command/output_format for HEADER.

  select

  Summary

select searches records that are matched to specified conditions from a table and then outputs them.

select is the most important command in groonga. You need to understand select to use the full power of groonga.

  Syntax

select has many parameters. The required parameter is only table and others are optional:

select table
       [match_columns=null]
       [query=null]
       [filter=null]
       [scorer=null]
       [sortby=null]
       [output_columns="_id, _key, *"]
       [offset=0]
       [limit=10]
       [drilldown=null]
       [drilldown_sortby=null]
       [drilldown_output_columns=null]
       [drilldown_offset=0]
       [drilldown_limit=10]
       [cache=yes]
       [match_escalation_threshold=0]
       [query_expansion=null]
       [query_flags=ALLOW_PRAGMA|ALLOW_COLUMN|ALLOW_UPDATE|ALLOW_LEADING_NOT|NONE]

  Usage

Let's learn about select usage with examples. This section shows many popular usages.

Here are a schema definition and sample data to show usage.

Execution example:

table_create Entries TABLE_HASH_KEY ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Entries content COLUMN_SCALAR Text
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Entries n_likes COLUMN_SCALAR UInt32
# [[0, 1337566253.89858, 0.000355720520019531], true]
table_create Terms TABLE_PAT_KEY|KEY_NORMALIZE ShortText --default_tokenizer TokenBigram
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Terms entries_key_index COLUMN_INDEX|WITH_POSITION Entries _key
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Terms entries_content_index COLUMN_INDEX|WITH_POSITION Entries content
# [[0, 1337566253.89858, 0.000355720520019531], true]
load --table Entries
[
{"_key":    "The first post!",
 "content": "Welcome! This is my first post!",
 "n_likes": 5},
{"_key":    "Groonga",
 "content": "I started to use groonga. It's very fast!",
 "n_likes": 10},
{"_key":    "Mroonga",
 "content": "I also started to use mroonga. It's also very fast! Really fast!",
 "n_likes": 15},
{"_key":    "Good-bye Senna",
 "content": "I migrated all Senna system!",
 "n_likes": 3},
{"_key":    "Good-bye Tritonn",
 "content": "I also migrated all Tritonn system!",
 "n_likes": 3}
]
# [[0, 1337566253.89858, 0.000355720520019531], 5]

There is a table, Entries, for blog entries. An entry has title, content and the number of likes for the entry. Title is key of Entries. Content is value of Entries.content column. The number of likes is value of Entries.n_likes column.

Entries._key column and Entries.content column are indexed using TokenBigram tokenizer. So both Entries._key and Entries.content are fulltext search ready.

OK. The schema and data for examples are ready.

  Simple usage

Here is the most simple usage with the above schema and data. It outputs all records in Entries table.

Execution example:

select Entries
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         5
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         1,
#         "The first post!",
#         "Welcome! This is my first post!",
#         5
#       ],
#       [
#         2,
#         "Groonga",
#         "I started to use groonga. It's very fast!",
#         10
#       ],
#       [
#         3,
#         "Mroonga",
#         "I also started to use mroonga. It's also very fast! Really fast!",
#         15
#       ],
#       [
#         4,
#         "Good-bye Senna",
#         "I migrated all Senna system!",
#         3
#       ],
#       [
#         5,
#         "Good-bye Tritonn",
#         "I also migrated all Tritonn system!",
#         3
#       ]
#     ]
#   ]
# ]

Why does the command output all records? There are two reasons. The first reason is that the command doesn't specify any search conditions. No search condition means all records are matched. The second reason is that the number of all records is 5. select command outputs 10 records at a maximum by default. There are only 5 records. It is less than 10. So the command outputs all records.

  Search conditions

Search conditions are specified by query or filter. You can also specify both query and filter. It means that selected records must be matched against both query and filter.

  Search condition: query

query is designed for search box in Web page. Imagine a search box in google.com. You specify search conditions for query as space separated keywords. For example, search engine means a matched record should contain two words, search and engine.

Normally, query parameter is used for specifying fulltext search conditions. It can be used for non fulltext search conditions but filter is used for the propose.

query parameter is used with match_columns parameter when query parameter is used for specifying fulltext search conditions. match_columns specifies which columnes and indexes are matched against query.

Here is a simple query usage example.

Execution example:

select Entries --match_columns content --query fast
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         2,
#         "Groonga",
#         "I started to use groonga. It's very fast!",
#         10
#       ],
#       [
#         3,
#         "Mroonga",
#         "I also started to use mroonga. It's also very fast! Really fast!",
#         15
#       ]
#     ]
#   ]
# ]

The select command searches records that contain a word fast in content column value from Entries table.

query has query syntax but its deatils aren't described here. See /reference/grn_expr/query_syntax for datails.

  Search condition: filter

filter is designed for complex search conditions. You specify search conditions for filter as ECMAScript like syntax.

Here is a simple filter usage example.

Execution example:

select Entries --filter 'content @ "fast" && _key == "Groonga"'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         2,
#         "Groonga",
#         "I started to use groonga. It's very fast!",
#         10
#       ]
#     ]
#   ]
# ]

The select command searches records that contain a word fast in content column value and has Groonga as _key from Entries table. There are three operators in the command, @, && and ==. @ is fulltext search operator. && and == are the same as ECMAScript. && is logical AND operator and == is equality operator.

filter has more operators and syntax like grouping by (...) its deatils aren't described here. See /reference/grn_expr/script_syntax for datails.

  Paging

You can specify range of outputted records by offset and limit. Here is an example to output only the 2nd record.

Execution example:

select Entries --offset 1 --limit 1
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         5
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         2,
#         "Groonga",
#         "I started to use groonga. It's very fast!",
#         10
#       ]
#     ]
#   ]
# ]

offset is zero-origin. --offset 1 means output range is started from the 2nd record.

limit specifies the max number of output records. --limit 1 means the number of output records is 1 at a maximium. If no records are matched, select command outputs no records.

  The total number of records

You can use --limit 0 to retrieve the total number of recrods without any contents of records.

Execution example:

select Entries --limit 0
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         5
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ]
#     ]
#   ]
# ]

--limit 0 is also useful for retrieving only the number of matched records.

  Parameters

This section describes all parameters. Parameters are categorized.

  Required parameter

There is a required parameter, table.

  table

It specifies a table to be searched. table must be specified.

If nonexistent table is specified, an error is returned.

Execution example:

select Nonexistent
# [
#   [
#     -22,
#     1337566253.89858,
#     0.000355720520019531,
#     "invalid table name: <Nonexistent>",
#     [
#       [
#         "grn_select",
#         "proc.c",
#         542
#       ]
#     ]
#   ]
# ]

  Search related parameters

There are search related parameters. Typically, match_columns and query parameters are used for implementing a search box. filter parameters is used for implementing complex search feature.

If both query and filter are specified, selected records must be matched against both query and filter. If both query and filter aren't specified, all records are selected.

  match_columns

It specifies the default target column for fulltext search by query parameter value. A target column for fulltext search can be specified in query parameter. The difference between match_columns and query is whether weight is supported or not. match_columns supports weight but query doesn't.

Weight is relative importance of target column. A higher weight target column gets more hit score rather than a lower weight target column when a record is matched by fulltext search. The default weight is 1.

Here is a simple match_columns usage example.

Execution example:

select Entries --match_columns content --query fast --output_columns '_key, _score'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "_score",
#           "Int32"
#         ]
#       ],
#       [
#         "Groonga",
#         1
#       ],
#       [
#         "Mroonga",
#         2
#       ]
#     ]
#   ]
# ]

--match_columns content means the default target column for fulltext search is content column and its weight is 1. --output_columns '_key, _score' means that the select command outputs _key value and _score value for matched records.

Pay attention to _score value. _score value is the number of matched counts against query parameter value. In the example, query parameter value is fast. The fact that _score value is 1 means that fast appers in content column only once. The fact that _score value is 2 means that fast appears in content column twice.

To specify weight, column * weight syntax is used. Here is a weight usage example.

Execution example:

select Entries --match_columns 'content * 2' --query fast --output_columns '_key, _score'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "_score",
#           "Int32"
#         ]
#       ],
#       [
#         "Groonga",
#         2
#       ],
#       [
#         "Mroonga",
#         4
#       ]
#     ]
#   ]
# ]

--match_columns 'content * 2' means the default target column for fulltext search is content column and its weight is 2.

Pay attention to _score value. _score value is doubled because weight is 2.

You can specify one or more columns as the default target columns for fulltext search. If one or more columns are specified, fulltext search is done for all columns and scores are accumulated. If one of the columns is matched against query parameter value, the record is treated as matched.

To specify one or more columns, column1 * weight1 || column2 * weight2 || ... syntax is used. * weight can be omitted. If it is omitted, 1 is used for weight. Here is a one or more columns usage example.

Execution example:

select Entries --match_columns '_key * 10 || content' --query groonga --output_columns '_key, _score'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "_score",
#           "Int32"
#         ]
#       ],
#       [
#         "Groonga",
#         11
#       ]
#     ]
#   ]
# ]

--match_columns '_key * 10 || content' means the default target columns for fulltext search are _key and content columns and _key column's weight is 10 and content column's weight is 1. This weight allocation means _key column value is more important rather than content column value. In this example, title of blog entry is more important rather thatn content of blog entry.

  query

It specifies the query text. Normally, it is used for fulltext search with match_columns parameter. query parameter is designed for a fulltext search form in a Web page. A query text should be formatted in /reference/grn_expr/query_syntax. The syntax is similar to common search form like Google's search form. For example, word1 word2 means that groonga searches records that contain both word1 and word2. word1 OR word2 means that groogna searches records that contain either word1 or word2.

Here is a simple logical and search example.

Execution example:

select Entries --match_columns content --query "fast groonga"
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         2,
#         "Groonga",
#         "I started to use groonga. It's very fast!",
#         10
#       ]
#     ]
#   ]
# ]

The select command searches records that contain two words fast and groonga in content column value from Entries table.

Here is a simple logical or search example.

Execution example:

select Entries --match_columns content --query "groonga OR mroonga"
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         2,
#         "Groonga",
#         "I started to use groonga. It's very fast!",
#         10
#       ],
#       [
#         3,
#         "Mroonga",
#         "I also started to use mroonga. It's also very fast! Really fast!",
#         15
#       ]
#     ]
#   ]
# ]

The select command searches records that contain one of two words groonga or mroonga in content column value from Entries table.

See /reference/grn_expr/query_syntax for other syntax.

It can be used for not only fulltext search but also other conditions. For example, column:value means the value of column column is equal to value. column:<value means the value of column column is less than value.

Here is a simple equality operator search example.

Execution example:

select Entries --query _key:Groonga
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         2,
#         "Groonga",
#         "I started to use groonga. It's very fast!",
#         10
#       ]
#     ]
#   ]
# ]

The select command searches records that _key column value is Groonga from Entries table.

Here is a simple less than operator search example.

Execution example:

select Entries --query n_likes:<11
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         4
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         1,
#         "The first post!",
#         "Welcome! This is my first post!",
#         5
#       ],
#       [
#         2,
#         "Groonga",
#         "I started to use groonga. It's very fast!",
#         10
#       ],
#       [
#         4,
#         "Good-bye Senna",
#         "I migrated all Senna system!",
#         3
#       ],
#       [
#         5,
#         "Good-bye Tritonn",
#         "I also migrated all Tritonn system!",
#         3
#       ]
#     ]
#   ]
# ]

The select command searches records that n_likes column value is less than 11 from Entries table.

See /reference/grn_expr/query_syntax for other operations.

  filter

It specifies the filter text. Normally, it is used for complex search conditions. filter can be used with query parameter. If both filter and query are specified, there are conbined with logical and. It means that matched records should be matched against both filter and query.

filter parameter is designed for complex conditions. A filter text should be formated in /reference/grn_expr/script_syntax. The syntax is similar to ECMAScript. For example, column == "value" means that the value of column column is equal to "value". column < value means that the value of column column is less than value.

Here is a simple equality operator search example.

Execution example:

select Entries --filter '_key == "Groonga"'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         2,
#         "Groonga",
#         "I started to use groonga. It's very fast!",
#         10
#       ]
#     ]
#   ]
# ]

The select command searches records that _key column value is Groonga from Entries table.

Here is a simple less than operator search example.

Execution example:

select Entries --filter 'n_likes < 11'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         4
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         1,
#         "The first post!",
#         "Welcome! This is my first post!",
#         5
#       ],
#       [
#         2,
#         "Groonga",
#         "I started to use groonga. It's very fast!",
#         10
#       ],
#       [
#         4,
#         "Good-bye Senna",
#         "I migrated all Senna system!",
#         3
#       ],
#       [
#         5,
#         "Good-bye Tritonn",
#         "I also migrated all Tritonn system!",
#         3
#       ]
#     ]
#   ]
# ]

The select command searches records that n_likes column value is less than 11 from Entries table.

See /reference/grn_expr/script_syntax for other operators.

  Advanced search parameters

  match_escalation_threshold

It specifies threshold to determine whether search storategy escalation is used or not. The threshold is compared against the number of matched records. If the number of matched records is equal to or less than the threshold, the search storategy escalation is used. See /spec/search about the search storategy escalation.

The default threshold is 0. It means that search storategy escalation is used only when no records are matched.

The default threshold can be customized by one of the followings.

•   --with-match-escalation-threshold option of configure

•   --match-escalation-threshold option of groogna command

•   match-escalation-threshold configuration item in configuration file

    Here is a simple match_escalation_threshold usage example. The first select doesn't have match_escalation_threshold parameter. The second select has match_escalation_threshold parameter.

    Execution example:

    select Entries --match_columns content --query groo
    # [
    #   [
    #     0,
    #     1337566253.89858,
    #     0.000355720520019531
    #   ],
    #   [
    #     [
    #       [
    #         1
    #       ],
    #       [
    #         [
    #           "_id",
    #           "UInt32"
    #         ],
    #         [
    #           "_key",
    #           "ShortText"
    #         ],
    #         [
    #           "content",
    #           "Text"
    #         ],
    #         [
    #           "n_likes",
    #           "UInt32"
    #         ]
    #       ],
    #       [
    #         2,
    #         "Groonga",
    #         "I started to use groonga. It's very fast!",
    #         10
    #       ]
    #     ]
    #   ]
    # ]
    select Entries --match_columns content --query groo --match_escalation_threshold -1
    # [
    #   [
    #     0,
    #     1337566253.89858,
    #     0.000355720520019531
    #   ],
    #   [
    #     [
    #       [
    #         0
    #       ],
    #       [
    #         [
    #           "_id",
    #           "UInt32"
    #         ],
    #         [
    #           "_key",
    #           "ShortText"
    #         ],
    #         [
    #           "content",
    #           "Text"
    #         ],
    #         [
    #           "n_likes",
    #           "UInt32"
    #         ]
    #       ]
    #     ]
    #   ]
    # ]

    The first select command searches records that contain a word groo in content column value from Entries table. But no records are matched because the TokenBigram tokenizer tokenizes groonga to groonga not gr|ro|oo|on|ng|ga. (The TokenBigramSplitSymbolAlpha tokenizer tokenizes groonga to gr|ro|oo|on|ng|ga. See /reference/tokenizers for details.) It means that groonga is indexed but groo isn't indexed. So no records are matched against groo by exact match. In the case, the search storategy escalation is used because the number of matched records (0) is equal to match_escalation_threshold (0). One record is matched against groo by unsplit search.

    The second select command also searches records that contain a word groo in content column value from Entries table. And it also doesn't found matched records. In this case, the search storategy escalation is not used because the number of matched records (0) is larger than match_escalation_threshold (-1). So no more searches aren't executed. And no records are matched.

  query_expansion

It's for query expansion. Query expansion substitutes specific words to another words in query. Nomally, it's used for synonym search.

It specifies a column that is used to substitute query parameter value. The format of this parameter value is "${TABLE}.${COLUMN}". For example, "Terms.synonym" specifies synonym column in Terms table.

Table for query expansion is called "substitution table". Substitution table's key must be ShortText. So array table (TABLE_NO_KEY) can't be used for query expansion. Because array table doesn't have key.

Column for query expansion is called "substitution column". Substitution column's value type must be ShortText. Column type must be vector (COLUMN_VECTOR).

Query expansion substitutes key of substitution table in query with values in substitution column. If a word in query is a key of substitution table, the word is substituted with substitution column value that is associated with the key. Substition isn't performed recursively. It means that substitution target words in substituted query aren't substituted.

Here is a sample substitution table to show a simple query_expansion usage example.

Execution example:

table_create Thesaurus TABLE_PAT_KEY|KEY_NORMALIZE ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Thesaurus synonym COLUMN_VECTOR ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
load --table Thesaurus
[
{"_key": "mroonga", "synonym": ["mroonga", "tritonn", "groonga mysql"]},
{"_key": "groonga", "synonym": ["groonga", "senna"]}
]
# [[0, 1337566253.89858, 0.000355720520019531], 2]

Thesaurus substitution table has two synonyms, "mroonga" and "groonga". If an user searches with "mroonga", groonga searches with "((mroonga) OR (tritonn) OR (groonga mysql))". If an user searches with "groonga", groonga searchs with "((groonga) OR (senna))". Nomrally, it's good idea that substitution table has KEY_NORMALIZE flag. If the flag is used, substitute target word is matched in case insensitive manner.

Note that those synonym values include the key value such as "mroonga" and "groonga". It's recommended that you include the key value. If you don't include key value, substituted value doesn't include the original substitute target value. Normally, including the original value is better search result. If you have a word that you don't want to be searched, you should not include the original word. For example, you can implement "stop words" by an empty vector value.

Here is a simple query_expansion usage example.

Execution example:

select Entries --match_columns content --query "mroonga"
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         3,
#         "Mroonga",
#         "I also started to use mroonga. It's also very fast! Really fast!",
#         15
#       ]
#     ]
#   ]
# ]
select Entries --match_columns content --query "mroonga" --query_expansion Thesaurus.synonym
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         3,
#         "Mroonga",
#         "I also started to use mroonga. It's also very fast! Really fast!",
#         15
#       ],
#       [
#         5,
#         "Good-bye Tritonn",
#         "I also migrated all Tritonn system!",
#         3
#       ]
#     ]
#   ]
# ]
select Entries --match_columns content --query "((mroonga) OR (tritonn) OR (groonga mysql))"
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         3,
#         "Mroonga",
#         "I also started to use mroonga. It's also very fast! Really fast!",
#         15
#       ],
#       [
#         5,
#         "Good-bye Tritonn",
#         "I also migrated all Tritonn system!",
#         3
#       ]
#     ]
#   ]
# ]

The first select command doesn't use query expansion. So a record that has "tritonn" isn't found. The second select command uses query expansion. So a record that has "tritonn" is found. The third select command doesn't use query expansion but it is same as the second select command. The third one uses expanded query.

Each substitute value can contain any /reference/grn_expr/query_syntax syntax such as (...) and OR. You can use complex substitution by using those syntax.

Here is a complex substitution usage example that uses query syntax.

Execution example:

load --table Thesaurus
[
{"_key": "popular", "synonym": ["popular", "n_likes:>=10"]}
]
# [[0, 1337566253.89858, 0.000355720520019531], 1]
select Entries --match_columns content --query "popular" --query_expansion Thesaurus.synonym
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         2,
#         "Groonga",
#         "I started to use groonga. It's very fast!",
#         10
#       ],
#       [
#         3,
#         "Mroonga",
#         "I also started to use mroonga. It's also very fast! Really fast!",
#         15
#       ]
#     ]
#   ]
# ]

The load command registers a new synonym "popular". It is substituted with ((popular) OR (n_likes:>=10)). The substituted query means that "popular" is containing the word "popular" or 10 or more liked entries.

The select command outputs records that n_likes column value is equal to or more than 10 from Entries table.

  query_flags

It customs query parameter syntax. You cannot update column value by query parameter by default. But if you specify ALLOW_COLUMN|ALLOW_UPDATE as query_flags, you can update column value by query.

Here are available values:

•   ALLOW_PRAGMA

•   ALLOW_COLUMN

•   ALLOW_UPDATE

•   ALLOW_LEADING_NOT

•   NONE

    ALLOW_PRAGMA enables pragma at the head of query. This is not implemented yet.

    ALLOW_COLUMN enables search againt columns that are not included in match_columns. To specify column, there are COLUMN:... syntaxes.

    ALLOW_UPDATE enables column update by query with COLUMN:=NEW_VALUE syntax. ALLOW_COLUMN is also required to update column because the column update syntax specifies column.

    ALLOW_LEADING_NOT enables leading NOT condition with -WORD syntax. The query searches records that doesn't match WORD. Leading NOT condition query is heavy query in many cases because it matches many records. So this flag is disabled by default. Be careful about it when you use the flag.

    NONE is just ignores. You can use NONE for specifying no flags.

    They can be combined by separated | such as ALLOW_COLUMN|ALLOW_UPDATE.

    The default value is ALLOW_PRAGMA|ALLOW_COLUMN.

    Here is a usage example of ALLOW_COLUMN.

    Execution example:

    select Entries --query content:@mroonga --query_flags ALLOW_COLUMN
    # [
    #   [
    #     0,
    #     1337566253.89858,
    #     0.000355720520019531
    #   ],
    #   [
    #     [
    #       [
    #         1
    #       ],
    #       [
    #         [
    #           "_id",
    #           "UInt32"
    #         ],
    #         [
    #           "_key",
    #           "ShortText"
    #         ],
    #         [
    #           "content",
    #           "Text"
    #         ],
    #         [
    #           "n_likes",
    #           "UInt32"
    #         ]
    #       ],
    #       [
    #         3,
    #         "Mroonga",
    #         "I also started to use mroonga. It's also very fast! Really fast!",
    #         15
    #       ]
    #     ]
    #   ]
    # ]

    The select command searches records that contain mroonga in content column value from Entries table.

    Here is a usage example of ALLOW_UPDATE.

    Execution example:

    table_create Users TABLE_HASH_KEY ShortText
    # [[0, 1337566253.89858, 0.000355720520019531], true]
    column_create Users age COLUMN_SCALAR UInt32
    # [[0, 1337566253.89858, 0.000355720520019531], true]
    load --table Users
    [
    {"_key": "alice", "age": 18},
    {"_key": "bob",   "age": 20}
    ]
    # [[0, 1337566253.89858, 0.000355720520019531], 2]
    select Users --query age:=19 --query_flags ALLOW_COLUMN|ALLOW_UPDATE
    # [
    #   [
    #     0,
    #     1337566253.89858,
    #     0.000355720520019531
    #   ],
    #   [
    #     [
    #       [
    #         2
    #       ],
    #       [
    #         [
    #           "_id",
    #           "UInt32"
    #         ],
    #         [
    #           "_key",
    #           "ShortText"
    #         ],
    #         [
    #           "age",
    #           "UInt32"
    #         ]
    #       ],
    #       [
    #         1,
    #         "alice",
    #         19
    #       ],
    #       [
    #         2,
    #         "bob",
    #         19
    #       ]
    #     ]
    #   ]
    # ]
    select Users
    # [
    #   [
    #     0,
    #     1337566253.89858,
    #     0.000355720520019531
    #   ],
    #   [
    #     [
    #       [
    #         2
    #       ],
    #       [
    #         [
    #           "_id",
    #           "UInt32"
    #         ],
    #         [
    #           "_key",
    #           "ShortText"
    #         ],
    #         [
    #           "age",
    #           "UInt32"
    #         ]
    #       ],
    #       [
    #         1,
    #         "alice",
    #         19
    #       ],
    #       [
    #         2,
    #         "bob",
    #         19
    #       ]
    #     ]
    #   ]
    # ]

    The first select command sets age column value of all records to 19. The second select command outputs updated age column values.

    Here is a usage example of ALLOW_LEADING_NOT.

    Execution example:

    select Entries --match_columns content --query -mroonga --query_flags ALLOW_LEADING_NOT
    # [
    #   [
    #     0,
    #     1337566253.89858,
    #     0.000355720520019531
    #   ],
    #   [
    #     [
    #       [
    #         4
    #       ],
    #       [
    #         [
    #           "_id",
    #           "UInt32"
    #         ],
    #         [
    #           "_key",
    #           "ShortText"
    #         ],
    #         [
    #           "content",
    #           "Text"
    #         ],
    #         [
    #           "n_likes",
    #           "UInt32"
    #         ]
    #       ],
    #       [
    #         1,
    #         "The first post!",
    #         "Welcome! This is my first post!",
    #         5
    #       ],
    #       [
    #         2,
    #         "Groonga",
    #         "I started to use groonga. It's very fast!",
    #         10
    #       ],
    #       [
    #         4,
    #         "Good-bye Senna",
    #         "I migrated all Senna system!",
    #         3
    #       ],
    #       [
    #         5,
    #         "Good-bye Tritonn",
    #         "I also migrated all Tritonn system!",
    #         3
    #       ]
    #     ]
    #   ]
    # ]

    The select command searches records that don't contain mroonga in content column value from Entries table.

    Here is a usage example of NONE.

    Execution example:

    select Entries --match_columns content --query 'mroonga OR _key:Groonga' --query_flags NONE
    # [
    #   [
    #     0,
    #     1337566253.89858,
    #     0.000355720520019531
    #   ],
    #   [
    #     [
    #       [
    #         1
    #       ],
    #       [
    #         [
    #           "_id",
    #           "UInt32"
    #         ],
    #         [
    #           "_key",
    #           "ShortText"
    #         ],
    #         [
    #           "content",
    #           "Text"
    #         ],
    #         [
    #           "n_likes",
    #           "UInt32"
    #         ]
    #       ],
    #       [
    #         3,
    #         "Mroonga",
    #         "I also started to use mroonga. It's also very fast! Really fast!",
    #         15
    #       ]
    #     ]
    #   ]
    # ]

    The select command searches records that contain one of two words mroonga or _key:Groonga in content from Entries table. Note that _key:Groonga doesn't mean that the value of _key column is equal to Groonga. Because ALLOW_COLUMN flag is not specified.

    See also /reference/grn_expr/query_syntax.

  Output related parameters

  output_columns

It specifies output columns separated by ,.

Here is a simple output_columns usage example.

Execution example:

select Entries --output_columns '_id, _key' --limit 1
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         5
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ]
#       ],
#       [
#         1,
#         "The first post!"
#       ]
#     ]
#   ]
# ]

The select command just outputs _id and _key column values.

* is a special value. It means that all columns that are not /reference/pseudo_column.

Here is a * usage example.

Execution example:

select Entries --output_columns '_key, *' --limit 1
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         5
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         "The first post!",
#         "Welcome! This is my first post!",
#         5
#       ]
#     ]
#   ]
# ]

The select command outputs _key pseudo column, content column and n_likes column values but doesn't output _id pseudo column value.

The default value is _id, _key, *. It means that all column values except _score are outputted.

  sortby

It specifies sort keys separated by ,. Each sort key is column name.

Here is a simple sortby usage example.

Execution example:

select Entries --sortby 'n_likes, _id'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         5
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         4,
#         "Good-bye Senna",
#         "I migrated all Senna system!",
#         3
#       ],
#       [
#         5,
#         "Good-bye Tritonn",
#         "I also migrated all Tritonn system!",
#         3
#       ],
#       [
#         1,
#         "The first post!",
#         "Welcome! This is my first post!",
#         5
#       ],
#       [
#         2,
#         "Groonga",
#         "I started to use groonga. It's very fast!",
#         10
#       ],
#       [
#         3,
#         "Mroonga",
#         "I also started to use mroonga. It's also very fast! Really fast!",
#         15
#       ]
#     ]
#   ]
# ]

The select command sorts by n_likes column value in ascending order. For records that has the same n_likes are sorted by _id in ascending order. "Good-bye Senna" and "Good-bye Tritonn" are the case.

If you want to sort in descending order, add - before column name.

Here is a descending order sortby usage example.

Execution example:

select Entries --sortby '-n_likes, _id'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         5
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         3,
#         "Mroonga",
#         "I also started to use mroonga. It's also very fast! Really fast!",
#         15
#       ],
#       [
#         2,
#         "Groonga",
#         "I started to use groonga. It's very fast!",
#         10
#       ],
#       [
#         1,
#         "The first post!",
#         "Welcome! This is my first post!",
#         5
#       ],
#       [
#         4,
#         "Good-bye Senna",
#         "I migrated all Senna system!",
#         3
#       ],
#       [
#         5,
#         "Good-bye Tritonn",
#         "I also migrated all Tritonn system!",
#         3
#       ]
#     ]
#   ]
# ]

The select command sorts by n_likes column value in descending order. But ascending order is used for sorting by _id.

You can use _score pseudo column in sortby if you use query or filter parameter.

Execution example:

select Entries --match_columns content --query fast --sortby -_score --output_columns '_key, _score'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "_score",
#           "Int32"
#         ]
#       ],
#       [
#         "Mroonga",
#         2
#       ],
#       [
#         "Groonga",
#         1
#       ]
#     ]
#   ]
# ]

The select command sorts matched records by hit score in descending order and outputs record key and hit score.

If you use _score without query nor filter parameters, it's just ignored but get a warning in log file.

  offset

It specifies offset to determine output records range. Offset is zero-origin. --offset 1 means output range is started from the 2nd record.

Execution example:

select Entries --sortby _id --offset 3 --output_columns _key
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         5
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ]
#       ],
#       [
#         "Good-bye Senna"
#       ],
#       [
#         "Good-bye Tritonn"
#       ]
#     ]
#   ]
# ]

The select command outputs from the 4th record.

You can specify negative value. It means that the number of matched records + offset. If you have 3 matched records and specify --offset -2, you get records from the 1st (3 + -2 = 1) record to the 3rd record.

Execution example:

select Entries --sortby _id --offset -2 --output_columns _key
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         5
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ]
#       ],
#       [
#         "Good-bye Senna"
#       ],
#       [
#         "Good-bye Tritonn"
#       ]
#     ]
#   ]
# ]

The select command outputs from the 4th record because the total number of records is 5.

The default value is 0.

  limit

It specifies the max number of output records. If the number of matched records is less than limit, all records are outputted.

Here is a simple limit usage example.

Execution example:

select Entries --sortby _id --offset 2 --limit 3 --output_columns _key
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         5
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ]
#       ],
#       [
#         "Mroonga"
#       ],
#       [
#         "Good-bye Senna"
#       ],
#       [
#         "Good-bye Tritonn"
#       ]
#     ]
#   ]
# ]

The select command outputs the 3rd, the 4th and the 5th records.

You can specify negative value. It means that the number of matched records + limit + 1. For example, --limit -1 outputs all records. It's very useful value to show all records.

Here is a simple negative limit value usage example.

Execution example:

select Entries --limit -1
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         5
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         1,
#         "The first post!",
#         "Welcome! This is my first post!",
#         5
#       ],
#       [
#         2,
#         "Groonga",
#         "I started to use groonga. It's very fast!",
#         10
#       ],
#       [
#         3,
#         "Mroonga",
#         "I also started to use mroonga. It's also very fast! Really fast!",
#         15
#       ],
#       [
#         4,
#         "Good-bye Senna",
#         "I migrated all Senna system!",
#         3
#       ],
#       [
#         5,
#         "Good-bye Tritonn",
#         "I also migrated all Tritonn system!",
#         3
#       ]
#     ]
#   ]
# ]

The select command outputs all records.

The default value is 10.

  scorer

TODO: write in English and add example.

検索条件にマッチする全てのレコードに対して適用するgrn_exprをscript形式で指定します。

scorerは、検索処理が完了し、ソート処理が実行される前に呼び出されます。従って、各レコードのスコアを操作する式を指定しておけば、検索結果のソート順序をカスタマイズできるようになります。

  Facet related parameters

  drilldown

TODO: write in English and add example.

グループ化のキーとなるカラム名のリストをカンマ(',')区切りで指定します。検索条件にマッチした各レコードを出力したのちに、drilldownに指定されたカラムの値が同一であるレコードをとりまとめて、それぞれについて結果レコードを出力します。

  drilldown_sortby

TODO: write in English and add example.

drilldown条件に指定されたカラムの値毎にとりまとめられたレコードについて、ソートキーとなるカラム名のリストをカンマ(',')区切りで指定します。sortbyパラメータと同様に昇降順を指定できます。

  drilldown_output_columns

TODO: write in English and add example.

drilldown条件に指定されたカラムの値毎にとりまとめられたレコードについて、出力するカラム名のリストをカンマ(',')区切りで指定します。

  drilldown_offset

TODO: write in English and add example.

drilldown条件に指定されたカラムの値毎にとりまとめられたレコードについて、出力対象となる最初のレコードの番号を0ベースで指定します。デフォルト値は0です。drilldown_offsetに負の値を指定した場合は、ヒットした件数 + drilldown_offsetによって算出される値が指定されたものとみなされます。

  drilldown_limit

TODO: write in English and add example.

drilldown条件に指定されたカラムの値毎にとりまとめられたレコードについて、出力を行うレコードの件数を指定します。デフォルト値は10です。実際には、drilldown_offset + drilldown_limit がヒットした件数を超えない範囲でレコードが出力されます。drilldown_limitに負の値を指定した場合は、ヒットした件数 + drilldown_limit + 1 によって算出される値が指定されたものとみなされます。

  Cache related parameter

  cache

TODO: write in English and add example.

クエリキャッシュに関する動作を設定します。

no 検索結果をクエリキャッシュに残しません。キャッシュして再利用される可能性が低いクエリに対して用います。キャッシュ容量は有限です。有効なキャッシュが多くヒットするために、このパラメータは有効です。

  返値

TODO: write in English and add example.

以下のようなjson形式で値が返却されます。

[[リターンコード, 処理開始時間, 処理時間], [検索結果, ドリルダウン結果]]

リターンコード grn_rcに対応する数値が返されます。0(GRN_SUCCESS)以外の場合は、続いてエラー内容を示す 文字列が返されます。

処理開始時間 処理を開始した時間について、1970年1月1日0時0分0秒を起点とした秒数を小数で返します。

処理時間 処理にかかった秒数を返します。

検索結果 drilldown条件が実行される前の検索結果が以下のように出力されます。:

[[検索件数], [[カラム名1,カラム型1],..], 検索結果1,..]

検索件数 検索件数が出力されます。

カラム名n output_columnsに指定された条件に従って、対象となるカラム名が出力されます。

カラム型n output_columnsに指定された条件に従って、対象となるカラム型が出力されます。

検索結果n output_columns, offset, limitによって指定された条件に従って各レコードの値が出力されます。

drilldown結果 drilldown処理の結果が以下のように出力されます。:

[[[件数], [[カラム名1,カラム型1],..], 検索結果1,..],..]

件数 drilldownに指定されたカラムの値の異なり数が出力されます。

カラム名n drilldown_output_columnsに指定された条件に従って、対象となるカラム名が出力されます。

カラム型n drilldown_output_columnsに指定された条件に従って、対象となるカラム型が出力されます。

ドリルダウン結果n drilldown_output_columns, drilldown_offset, drilldown_limitによって指定された条件に従って各レコードの値が出力されます。

  See also

•   /reference/grn_expr/query_syntax

•   /reference/grn_expr/script_syntax

  shutdown

  名前

shutdown - サーバプロセスの停止

  書式

shutdown

  説明

groonga組込コマンドの一つであるshutdownについて説明します。組込コマンドは、groonga実行ファイルの引数、標準入力、またはソケット経由でgroongaサーバにリクエストを送信することによって実行します。

shutdownは、接続しているgroongaサーバプロセスを停止します。

  引数

ありません。

  返値

ありません。

  例

shutdown

  status

  名前

status - groongaプロセスの状態表示

  書式

status

  説明

groonga組込コマンドの一つであるstatusについて説明します。組込コマンドは、groonga実行ファイルの引数、標準入力、またはソケット経由でgroongaサーバにリクエストを送信することによって実行します。

statusコマンドは、groongaプロセスの状態を表示します。主にgroongaサーバプロセスに対して使用することを想定しています。

  引数

ありません。

  返値

  json形式

下記の項目がハッシュ形式で出力されます。

alloc_count groongaプロセスの内部でアロケートされ、まだ解放されてないメモリブロックの数を示します。groongaをbuildする際に、configureオプションで --enable-exact-alloc-countが指定されていたならば、正確な値を返します。それ以外の場合は不正確な値を返す場合があります。

starttime groongaプロセスが起動した時刻のtvsec値を返します。

uptime groongaプロセスが起動してから経過した秒数を返します。

  例

Execution example:

status
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   {
#     "uptime": 6,
#     "max_command_version": 2,
#     "n_queries": 30,
#     "cache_hit_rate": 0.0,
#     "version": "2.1.0",
#     "alloc_count": 280,
#     "command_version": 1,
#     "starttime": 1356678580,
#     "default_command_version": 1
#   }
# ]

  suggest

Note
    The suggest feature specification isn't stable. The specification may be changed.

  NAME

suggest - returns completion, correction and/or suggestion for a query.

  SYNOPSIS

suggest types table column query [sortby [output_columns [offset [limit [frequency_threshold [conditional_probability_threshold [prefix_search]]]]]]]

  DESCRIPTION

The suggest command returns completion, correction and/or suggestion for a specified query.

See /suggest/introduction about completion, correction and suggestion.

  OPTIONS

types
    It specifies what types are returned by the suggest command.

    Here are available types:

complete
    The suggest command does completion.

correct
    The suggest command does correction.

suggest
    The suggest command does suggestion.

    You can specify one or more types separated by |. Here are examples: It returns correction:

    correct

    It returns correction and suggestion:

    correct|suggest

    It returns complete, correction and suggestion:

    complete|correct|suggest

table
    It specifies table name that has item_${DATA_SET_NAME} format. For example, item_query is a table name if you created dataset by the following command:

    groonga-suggest-create-dataset /tmp/db-path query

column
    It specifies a column name that has furigana in Katakana in table table.

query
    It specifies query for completion, correction and/or suggestion.

sortby
    It specifies sort key.

Default:
    -_score

output_columns
    It specifies output columns.

Default:
    _key,_score

offset
    It specifies returned records offset.

Default:
    0

limit
    It specifies number of returned records.

Default:
    10

frequency_threshold
    It specifies threshold for item frequency. Returned records must have _score that is greater than or equal to frequency_threshold.

Default:
    100

    conditional_probability_threshold It specifies threshold for conditional probability. Conditional probability is used for learned data. It is probability of query submission when query is occurred. Returned records must have conditional probability that is greater than or equal to conditional_probability_threshold.

Default:
    0.2

prefix_search
    It specifies whether optional prefix search is used or not in completion.

    Here are available values:

yes Prefix search is always used.

no  Prefix search is never used.

auto
    Prefix search is used only when other search can't find any records.

Default:
    auto

similar_search
    It specifies whether optional similar search is used or not in correction.

    Here are available values:

yes Similar search is always used.

no  Similar search is never used.

auto
    Similar search is used only when other search can't find any records.

Default:
    auto

  RETURN VALUE

  JSON format

Here is a returned JSON format:

{"type1": [["candidate1", score of candidate1],
           ["candidate2", score of candidate2],
           ...],
 "type2": [["candidate1", score of candidate1],
           ["candidate2", score of candidate2],
           ...],
 ...}

type A type specified by types.

candidate A candidate for completion, correction or suggestion.

score of candidate A score of corresponding candidate. It means that higher score candidate is more likely candidate for completion, correction or suggestion. Returned candidates are sorted by score of candidate descending by default.

  EXAMPLE

Here are learned data for completion.

Execution example:

load --table event_query --each 'suggest_preparer(_id, type, item, sequence, time, pair_query)'
[
{"sequence": "1", "time": 1312950803.86057, "item": "e"},
{"sequence": "1", "time": 1312950803.96857, "item": "en"},
{"sequence": "1", "time": 1312950804.26057, "item": "eng"},
{"sequence": "1", "time": 1312950804.56057, "item": "engi"},
{"sequence": "1", "time": 1312950804.76057, "item": "engin"},
{"sequence": "1", "time": 1312950805.86057, "item": "engine", "type": "submit"}
]
# [[0, 1337566253.89858, 0.000355720520019531], 6]

Here are learned data for correction.

Execution example:

load --table event_query --each 'suggest_preparer(_id, type, item, sequence, time, pair_query)'
[
{"sequence": "2", "time": 1312950803.86057, "item": "s"},
{"sequence": "2", "time": 1312950803.96857, "item": "sa"},
{"sequence": "2", "time": 1312950804.26057, "item": "sae"},
{"sequence": "2", "time": 1312950804.56057, "item": "saer"},
{"sequence": "2", "time": 1312950804.76057, "item": "saerc"},
{"sequence": "2", "time": 1312950805.76057, "item": "saerch", "type": "submit"},
{"sequence": "2", "time": 1312950809.76057, "item": "serch"},
{"sequence": "2", "time": 1312950810.86057, "item": "search", "type": "submit"}
]
# [[0, 1337566253.89858, 0.000355720520019531], 8]

Here are learned data for suggestion.

Execution example:

load --table event_query --each 'suggest_preparer(_id, type, item, sequence, time, pair_query)'
[
{"sequence": "3", "time": 1312950803.86057, "item": "search engine", "type": "submit"},
{"sequence": "3", "time": 1312950808.86057, "item": "web search realtime", "type": "submit"}
]
# [[0, 1337566253.89858, 0.000355720520019531], 2]

Here is a completion example.

Execution example:

suggest --table item_query --column kana --types complete --frequency_threshold 1 --query en
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   {
#     "complete": [
#       [
#         1
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "_score",
#           "Int32"
#         ]
#       ],
#       [
#         "engine",
#         1
#       ]
#     ]
#   }
# ]

Here is a correction example.

Execution example:

suggest --table item_query --column kana --types correct --frequency_threshold 1 --query saerch
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   {
#     "correct": [
#       [
#         1
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "_score",
#           "Int32"
#         ]
#       ],
#       [
#         "search",
#         1
#       ]
#     ]
#   }
# ]

Here is a suggestion example.

Execution example:

suggest --table item_query --column kana --types suggest --frequency_threshold 1 --query search
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   {
#     "suggest": [
#       [
#         2
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "_score",
#           "Int32"
#         ]
#       ],
#       [
#         "search engine",
#         1
#       ],
#       [
#         "web search realtime",
#         1
#       ]
#     ]
#   }
# ]

Here is a mixed example.

Execution example:

suggest --table item_query --column kana --types complete|correct|suggest --frequency_threshold 1 --query search
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   {
#     "suggest": [
#       [
#         2
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "_score",
#           "Int32"
#         ]
#       ],
#       [
#         "search engine",
#         1
#       ],
#       [
#         "web search realtime",
#         1
#       ]
#     ],
#     "complete": [
#       [
#         2
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "_score",
#           "Int32"
#         ]
#       ],
#       [
#         "search",
#         2
#       ],
#       [
#         "search engine",
#         2
#       ]
#     ],
#     "correct": [
#       [
#         1
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "_score",
#           "Int32"
#         ]
#       ],
#       [
#         "search",
#         2
#       ]
#     ]
#   }
# ]

  SEE ALSO

•   /suggest

•   /reference/executables/groonga-suggest-create-dataset

  table_create

  Summary

table_create creates a new table in the current database. You need to create one or more tables to store and search data.

  Syntax

table_create has many parameters. The required parameter is only name and otehrs are optional:

table_create name
             [flags=TABLE_HASH_KEY]
             [key_type=null]
             [value_type=null]
             [default_tokenizer=null]
             [normalizer=null]

  Usage

table_create command creates a new persistent table. See /reference/tables for table details.

  Create data store table

You can use all table types for data store table. See /reference/tables for all table types.

Table type is specified as TABLE_${TYPE} to flags parameter.

Here is an example to create TABLE_NO_KEY table:

Execution example:

table_create Logs TABLE_NO_KEY
# [[0, 1337566253.89858, 0.000355720520019531], true]

The table_create command creates a table that is named Logs and is TABLE_NO_KEY type.

If your records aren't searched by key, TABLE_NO_KEY type table is suitable. Because TABLE_NO_KEY doesn't support key but it is fast and small table. Storing logs into groonga database is the case.

If your records are searched by key or referenced by one or more columns, TABLE_NO_KEY type isn't suitable. Lexicon for fulltext search is the case.

  Create lexicon table

You can use all table types except TABLE_NO_KEY for lexicon table. Lexicon table needs key support but TABLE_NO_KEY doesn't support key.

Here is an example to create TABLE_PAT_KEY table:

Execution example:

table_create Lexicon TABLE_PAT_KEY ShortText --default_tokenizer TokenBigram --normalizer NormalizerAuto
# [[0, 1337566253.89858, 0.000355720520019531], true]

The table_create command creates the following table:

•   The table is named Lexicon.

•   The table is TABLE_PAT_KEY type table.

•   The table's key is ShortText type.

•   The table uses TokenBigram tokenizer to extract tokens from a normalized text.

•   The table uses NormalizerAuto normalizer to normalize a text.

    TABLE_PAT_KEY is suitable table type for lexicon table. Lexicon table is used for fulltext search.

    In fulltext search, predictive search may be used for fuzzy search. Predictive search is supported by TABLE_PAT_KEY and TABLE_DAT_KEY.

    Lexicon table has many keys because a fulltext target text has many tokens. Table that has many keys should consider table size because large table requires large memory. Requiring large memory causes disk I/O. It blocks fast search. So table size is important for a table that has many keys. TABLE_PAT_KEY is less table size than TABLE_DAT_KEY.

    Because of the above reasons, TABLE_PAT_KEY is suitable table type for lexicon table.

  Create tag index table

You can use all table types except TABLE_NO_KEY for tag index table. Tag index table needs key support but TABLE_NO_KEY doesn't support key.

Here is an example to create TABLE_HASH_KEY table:

Execution example:

table_create Ages TABLE_DAT_KEY UInt32
# [[0, 1337566253.89858, 0.000355720520019531], true]

The table_create command creates a table that is named Tags, is TABLE_HASH_KEY type and has ShortText type key.

TABLE_HASH_KEY or TABLE_DAT_KEY are suitable table types for tag index table.

If you need only exact match tag search feature, TABLE_HASH_KEY is suitable. It is the common case.

If you also need predictive tag search feature (for example, searching "groonga" by "gr" keyword.), TABLE_DAT_KEY is suitable. TABLE_DAT_KEY is large table size but it is not important because the number of tags will not be large.

  Create range index table

You can use TABLE_PAT_KEY and TABLE_DAT_KEY table types for range index table. Range index table needs range search support but TABLE_NO_KEY and TABLE_HASH_KEY don't support it.

Here is an example to create TABLE_DAT_KEY table:

Execution example:

table_create Ages TABLE_DAT_KEY UInt32
# [[0, 1337566253.89858, 0.000355720520019531], true]

The table_create command creates a table that is named Ages, is TABLE_DAT_KEY type and has UInt32 type key.

TABLE_PAT_KEY and TABLE_DAT_KEY are suitable table types for range index table.

If you don't have many indexed items, TABLE_DAT_KEY is suitable. Index for age is the case in the above example. Index for age will have only 0-100 items because human doesn't live so long.

If you have many indexed items, TABLE_PAT_KEY is suitable. Because TABLE_PAT_KEY is smaller than TABLE_DAT_KEY.

  Parameters

This section describes all parameters.

  name

It specifies a table name to be created. name must be specified.

Here are available characters:

•   0 .. 9 (digit)

•   a .. z (alphabet, lower case)

•   A .. Z (alphabet, upper case)

•   # (hash)

•   @ (at mark)

•   - (hyphen)

•   _ (underscore) (NOTE: Underscore can't be used as the first character.)

    You need to create a name with one or more the above chracters. Note that you cannot use _ as the first charcter such as _name.

  flags

It specifies a table type and table customize options.

Here are available flags:
flags | description
TABLE_NO_KEY | Array table.
TABLE_HASH_HEY | Hash table.
TABLE_PAT_KEY | Patricia trie.
TABLE_DAT_KEY | Double Array trie.
KEY_WITH_SIS | Enable Semi Infinite String. Require TABLE_PAT_KEY.

Note
    Since groonga 2.1.0 KEY_NORMALIZE flag is deprecated. Use normalizer option with NormalizerAuto instead.

You must specify one of TABLE_${TYPE} flags. You cannot specify two or more TABLE_${TYPE} flags. For example, TABLE_NO_KEY|TABLE_HASH_KEY is invalid.

You can combine flags with | (vertical bar) such as TABLE_PAT_KEY|KEY_WITH_SIS.

See /reference/tables for difference between table types.

The default flags are TABLE_HASH_KEY.

  key_type

It specifies key type.

If you specify TABLE_HASH_KEY, TABLE_PAT_KEY or TABLE_DAT_KEY as flags parameter, you need to specify key_type option.

See /reference/types for all types.

The default value is none.

  value_type

It specifies value type.

You can use value when you specify TABLE_NO_KEY, TABLE_HASH_KEY or TABLE_PAT_KEY as flags parameter. Value type must be a fixed size type. For example, UInt32 can be used but ShortText cannot be used. Use columns instead of value.

The default value is none.

  default_tokenizer

It specifies the default tokenizer that is used on searching and data loading.

You cannot use default_tokenizer with TABLE_NO_KEY because TABLE_NO_KEY cannot be used for index.

You must specify default_tokenizer for a table that is used for fulltext search index.

See /reference/tokenizers for all tokenizers

The default value is none.

  normalizer

It specifies a normalizer that is used to normalize key.

You cannot use normalizer with TABLE_NO_KEY because TABLE_NO_KEY doesn't support key.

See /reference/normalizers for all normalizsers.

The default value is none.

  Return value

table_create returns true as body on success such as:

[HEADER, true]

If table_create fails, error details are in HEADER.

See /reference/command/output_format for HEADER.

  See also

•   /reference/tables

•   /reference/commands/column_create

•   /reference/tokenizers

•   /reference/normalizers

•   /reference/command/output_format

  table_list

  名前

table_list - DBに定義されているテーブルをリスト表示

  書式

table_list

  説明

groonga組込コマンドの一つであるtable_listについて説明します。組込コマンドは、groonga実行ファイルの引数、標準入力、またはソケット経由でgroongaサーバにリクエストを送信することによって実行します。

table_listは、DBに定義されているテーブルのリストを表示します。

  引数

ありません。

  返値

  json形式

テーブル名一覧が以下の形式で返却されます。:

[[[テーブル情報名1,テーブル情報型1],...], テーブル情報1,...]

テーブル情報名n テーブル情報n には複数の情報が含まれますが、そこに入る情報がどんな内容かを示す名前を出力します。 情報名は以下の通りです。

id テーブルオブジェクトに割り当てられたID

name テーブル名

path テーブルのレコードを格納するファイル名

flags テーブルのflags属性

domain 主キー値の属する型

range valueが属する型

テーブル情報型n テーブル情報の型を出力します。

テーブル情報n テーブル情報名n で示された情報の配列を出力します。 情報の順序は テーブル情報名n の順序と同じです。

Execution example:

table_list
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         "id",
#         "UInt32"
#       ],
#       [
#         "name",
#         "ShortText"
#       ],
#       [
#         "path",
#         "ShortText"
#       ],
#       [
#         "flags",
#         "ShortText"
#       ],
#       [
#         "domain",
#         "ShortText"
#       ],
#       [
#         "range",
#         "ShortText"
#       ],
#       [
#         "default_tokenizer",
#         "ShortText"
#       ],
#       [
#         "normalizer",
#         "ShortText"
#       ]
#     ],
#     [
#       259,
#       "Ages",
#       "/tmp/groonga-databases/commands_table_create.0000103",
#       "TABLE_DAT_KEY|PERSISTENT",
#       "UInt32",
#       null,
#       null,
#       null
#     ],
#     [
#       257,
#       "Lexicon",
#       "/tmp/groonga-databases/commands_table_create.0000101",
#       "TABLE_PAT_KEY|PERSISTENT",
#       "ShortText",
#       null,
#       "TokenBigram",
#       "NormalizerAuto"
#     ],
#     [
#       256,
#       "Logs",
#       "/tmp/groonga-databases/commands_table_create.0000100",
#       "TABLE_NO_KEY|PERSISTENT",
#       null,
#       null,
#       null,
#       null
#     ],
#     [
#       258,
#       "Tags",
#       "/tmp/groonga-databases/commands_table_create.0000102",
#       "TABLE_HASH_KEY|PERSISTENT",
#       "ShortText",
#       null,
#       null,
#       null
#     ]
#   ]
# ]

  table_remove

  名前

table_remove - テーブルの削除

  書式

table_remove name

  説明

groonga組込コマンドの一つであるtable_removeについて説明します。組込コマンドは、groonga実行ファイルの引数、標準入力、またはソケット経由でgroongaサーバにリクエストを送信することによって実行します。

table_removeはテーブルと定義されているカラムを削除します。カラムに付随するインデックスも再帰的に削除されます。

  引数

name
    削除対象のカラムが定義されているテーブルの名前を指定します。

  返値

  json形式

[成功かどうかのフラグ]

成功かどうかのフラグ エラーが生じなかった場合にはtrue、エラーが生じた場合にはfalseを返す。

  例

table_remove Entry
[true]

  データ型

  名前

groonga データ型

  説明

groonga は、格納するデータの型を区別します。

groongaのデータベースでは、テーブルの主キーや、カラムの値はいずれも何らかの型に属します。また通常は、一つのテーブルの中の全てのレコードについて、カラムの値は共通となります。

主キーの型とカラムの型には、groongaで予め定義済みの型か、ユーザが定義する型、またはユーザが定義したテーブルを指定することができます。

主キーの型に他のテーブルを指定する場合は、そのテーブルは、主キーの型となるテーブルのサブセットとなります。

カラムの型に他のテーブルを指定する場合は、そのカラムは、カラムの型となるテーブルの参照キーとなります。

  組込型

以下の型が組込型としてあらかじめ定義されています。

Object 任意のテーブルに属する全てのレコードです。 [1]

Bool ブーリアン型やブール型などと呼ばれる型であり、真偽値を表します。取り得る値はtrueとfalseです。（デフォルト値: false）

/reference/commands/load コマンドで値を格納するときは、false、0、空文字列のいずれかを指定するとfalseになり、それ以外を指定するとtrueになります。

Int8 8bit符号付き整数であり、-128以上127以下の整数を表します。（デフォルト値: 0）

UInt8 8bit符号なし整数であり、0以上255以下の整数を表します。（デフォルト値: 0）

Int16 16bit符号付き整数であり、-32,768以上32,767以下の整数を表します。（デフォルト値: 0）

UInt16 16bit符号なし整数であり、0以上65,535以下の整数を表します。（デフォルト値: 0）

Int32 32bit符号付き整数であり、-2,147,483,648以上2,147,483,647以下の整数を表します。（デフォルト値: 0）

UInt32 32bit符号なし整数であり、0以上4,294,967,295以下の整数を表します。（デフォルト値: 0）

Int64 64bit符号付き整数であり、-9,223,372,036,854,775,808以上9,223,372,036,854,775,807以下の整数を表します。（デフォルト値: 0）

UInt64 64bit符号なし整数であり、0以上18,446,744,073,709,551,615以下の整数を表します。（デフォルト値: 0）

Float IEEE 754形式の倍精度浮動小数点数であり、実数を表します。（デフォルト値: 0.0）

IEEE 754形式の詳細については、 IEEE 754 - Wikipedia や IEEE 754: Standard for Binary Floating-Point を参照してください。

Time 日時を表す型であり、1970年1月1日0時0分0秒からの経過時間を、マイクロ秒単位で64bit符号付き整数により表現します。（デフォルト値: 0）

/reference/commands/load コマンドで値を格納するときは、1970年1月1日0時0分0秒からの経過秒数を指定します。秒単位より詳細な日時を指定するには、小数を使います。

ShortText 4,095バイト以下の文字列を表します。（デフォルト値: ""）

Text 65,535バイト以下の文字列を表します。（デフォルト値: ""）

LongText 2,147,483,647バイト以下の文字列を表します。（デフォルト値: ""）

TokyoGeoPoint 旧日本測地系による経緯度であり、経度と緯度をミリ秒単位で表現した整数の組により表現します。（デフォルト値: 0x0）

度分秒形式でx度y分z秒となる経度・緯度は、(((x * 60) + y) * 60 + z) * 1000という計算式でミリ秒単位へと変換されます。 /reference/commands/load コマンドで値を格納するときは、"ミリ秒単位の経度xミリ秒単位の緯度" もしくは "経度の小数表記x緯度の小数表記" という文字列表現を使って指定します。経度と緯度の区切りとしては、'x' のほかに ',' を使うことができます。

測地系の詳細については、 測地系 - Wikipedia を参照してください。

WGS84GeoPoint 世界測地系（World Geodetic System, WGS 84）による経緯度であり、経度と緯度をミリ秒単位で表現した整数の組により表現します。（デフォルト値: 0x0）

度分秒形式からミリ秒形式への変換方法や /reference/commands/load コマンドにおける指定方法はTokyoGeoPointと同じです。

  型に関する制限事項

  テーブルの主キーに指定できない型

Text型とLongText型については、テーブルの主キーに指定することはできません。

  ベクターとして格納できない型

groongaのカラムは、ある型のベクターを保存することができます。しかし、ShortText, Text, LongTextの３つの型についてはベクターとして保存したり出力したりすることはできますが、検索条件やドリルダウン条件に指定することができません。

テーブル型は、ベクターとして格納することができます。よって、ShortTextのベクターを検索条件やドリルダウン条件に使用したい場合には、主キーがShortText型のテーブルを別途作成し、そのテーブルを型として利用します。 脚注

[1] Object型はv1.2でサポートされます。

  Tables

  Summary

Table in groonga manages relation between ID and key. Groonga provides four table types. They are TABLE_NO_KEY, TABLE_HASH_KEY, TABLE_PAT_KEY and TABLE_DAT_KEY.

All tables except TABLE_NO_KEY provides both fast ID search by key and fast key search by ID. TABLE_NO_KEY doesn't support key. TABLE_NO_KEY only manages ID. So TABLE_NO_KEY doesn't provides ID search and key search.

  Characteristics

Here is a chracteristic table of all tables in groonga. (TABLE_ prefix is omitted in the table.)
 | NO_KEY | HASH_KEY | PAT_KEY | DAT_KEY
Data structure | Array | Hash table | Patricia trie | Double array trie
ID support | o | o | o | o
Key support | x | o | o | o
Value support | o | o | o | x
Key -> ID speed o: fast x: slow | - | oo | x | o
Update speed o: fast x: slow | ooo | o | o | x
Size o: small x: large | ooo | o | oo | x
Key update | - | x | x | o
Common prefix search | - | x | o | o
Predictive search | - | x | o | o
Range search | - | x | o | o

  TABLE_NO_KEY

TABLE_NO_KEY is very fast and very small but it doesn't support key. TABLE_NO_KEY is a only table that doesn't support key.

You cannot use TABLE_NO_KEY for lexicon for fulltext search because lexicon stores tokens as key. TABLE_NO_KEY is useful for no key records such as log.

  TABLE_HASH_KEY

TABLE_HASH_KEY is fast but it doesn't support advanced search functions such as common prefix search and predictive search.

TABLE_HASH_KEY is useful for index for exact search such as tag search.

  TABLE_PAT_KEY

TABLE_PAT_KEY is small and supports advanced search functions.

TABLE_PAT_KEY is useful for lexicon for fulltext search and index for range search.

  TABLE_DAT_KEY

TABLE_DAT_KEY is fast and supports key update but it is large. It is not suitable for storing many records. TABLE_DAT_KEY is a only table that supports key update.

TABLE_DAT_KEY is used in groonga database. Groonga database needs to convert object name such as ShortText, TokenBigram and table names to object ID. And groonga database needs to rename object name. Those features are implemented by TABLE_DAT_KEY. The number of objects is small. So large data size demerit of TABLE_DAT_KEY can be ignored.

  Record ID

Record ID is assigned automatically. You cannot assign record ID.

Record ID of deleted record may be reused.

Valid record ID range is between 1 and 268435455. (1 and 268435455 are valid IDs.)

  Persistent table and temporary table

Table is persistent table or temporary table.

  Persistent table

Persistent table is named and registered to database. Records in persistent table aren't deleted after closing table or database.

Persistent table can be created by /reference/commands/table_create command.

  Temporary table

Temporary table is anonymous. Records in temporary table are deleted after closing table. Temporary table is used to store search result, sort result, group (drilldown) result and so on. TABLE_HASH_KEY is used for search result and group result. TABLE_NO_KEY is used for sort result.

  Limitations

The max number of records is 268435455. You cannot add 268435456 or more records in a table.

The max number of a key size is 4096byte. You cannot use 4097byte or larger key. You can use column instead of key for 4097byte or larger size data. Text and LargeText types supports 4097byte or larger size data.

The max number of total key size is 4GiB. You need to split a table, split a database (sharding) or reduce each key size to handle 4GiB or more larger total key size.

  See also

•   /reference/commands/table_create

  Normalizers

  Summary

Groonga has normalizer module that normalizes text. It is used when tokenizing text and storing table key. For example, A and a are processed as the same character after normalization.

Normalizer module can be added as a plugin. You can customize text normalization by registering your normalizer plugins to groonga.

A normalizer module is attached to a table. A table can have zero or one normalizer module. You can attach a normalizer module to a table by table-create-normalizer option in /reference/commands/table_create.

Here is an example table_create that uses NormalizerAuto normalizer module:

Execution example:

table_create Dictionary TABLE_HASH_KEY ShortText --normalizer NormalizerAuto
# [[0, 1337566253.89858, 0.000355720520019531], true]

Note
    Groonga 2.0.9 or earlier doesn't have --normalizer option in table_create. KEY_NORMALIZE flag was used instead.

    You can open an old database by groonga 2.1.0 or later. An old database means that the database is created by groonga 2.0.9 or earlier. But you cannot open the opened old database by groonga 2.0.9 or earlier. Once you open the old database by groonga 2.1.0 or later, KEY_NORMALIZE flag information in the old database is converted to normalizer information. So groogna 2.0.9 or earlier cannot find KEY_NORMALIZE flag information in the opened old database.

Keys of a table that has a normalizer module are normalized:

Execution example:

load --table Dictionary
[
{"_key": "Apple"},
{"_key": "black"},
{"_key": "COLOR"}
]
# [[0, 1337566253.89858, 0.000355720520019531], 3]
select Dictionary
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         3
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ]
#       ],
#       [
#         1,
#         "apple"
#       ],
#       [
#         2,
#         "black"
#       ],
#       [
#         3,
#         "color"
#       ]
#     ]
#   ]
# ]

NormalizerAuto normalizer normalizes a text as a downcased text. For example, "Apple" is normalized to "apple", "black" is normalized to "blank" and "COLOR" is normalized to "color".

If a table is a lexicon for fulltext search, tokenized tokens are normalized. Because tokens are stored as table keys. Table keys are normalized as described above.

  Built-in normalizers

Here is a list of built-in normalizers:

•   NormalizerAuto

•   NormalizerNFKC51

  NormalizerAuto

Normally you should use NormalizerAuto normalizer. NormalizerAuto was the normalizer for groonga 2.0.9 or earlier. KEY_NORMALIZE flag in table_create on groonga 2.0.9 or earlier equals to --normalizer NormalizerAuto option in table_create on groonga 2.1.0 or later.

NormalizerAuto supports all encoding. It uses Unicode NFKC (Normalization Form Compatibility Composition) for UTF-8 encoding text. It uses encoding specific original normalization for other encodings. The results of those original normalization are similar to NFKC.

For example, half-width katakana (such as U+FF76 HALFWIDTH KATAKANA LETTER KA) + half-width katakana voiced sound mark (U+FF9E HALFWIDTH KATAKANA VOICED SOUND MARK) is normalized to full-width katakana with voiced sound mark (U+30AC KATAKANA LETTER GA). The former is two chracters but the latter is one character.

Here is an example that uses NormalizerAuto normalizer:

Execution example:

table_create NormalLexicon TABLE_HASH_KEY ShortText --normalizer NormalizerAuto
# [[0, 1337566253.89858, 0.000355720520019531], true]

  NormalizerNFKC51

NormalizerNFKC51 normalizes texts by Unicode NFKC (Normalization Form Compatibility Composition) for Unicode version 5.1. It supports only UTF-8 encoding.

Normally you don't need to use NormalizerNFKC51 explicitly. You can use NormalizerAuto instead.

Here is an example that uses NormalizerNFKC51 normalizer:

Execution example:

table_create NFKC51Lexicon TABLE_HASH_KEY ShortText --normalizer NormalizerNFKC51
# [[0, 1337566253.89858, 0.000355720520019531], true]

  Additional normalizers

Here is a list of additional normalizers provided by groonga-normalizer-mysql plugins:

•   NormalizerMySQLGeneralCI

    groonga-normalizer-mysql is a groonga plugin. It provides MySQL compatible normalizers to groonga. NormalizerMySQLGeneralCI corresponds to utf8mb4_general_ci.

    You need to register normalizers/mysql plugin in advance.

    Execution example:

    register normalizers/mysql
    # [[0, 1337566253.89858, 0.000355720520019531], true]

    Here is an example that uses NormalizerMySQLGeneralCI normalizer:

    Execution example:

    table_create MySQLGeneralLexicon TABLE_HASH_KEY ShortText --normalizer NormalizerMySQLGeneralCI
    # [[0, 1337566253.89858, 0.000355720520019531], true]

  See also

•   /reference/commands/table_create

  Tokenizers

TODO: Write me.

  Query expanders

  QueryExpanderTSV

  Summary

QueryExpanderTSV is a query expander plugin that reads synonyms from TSV (Tab Separated Values) file. This plugin provides poor feature than the embedded query expansion feature. For example, it doesn't support word normalization. But it may be easy to use because you can manage your synonyms by TSV file. You can edit your synonyms by spreadsheet application such as Excel. With the embedded query expansion feature, you manage your synonyms by groonga's table.

  Install

You need to register query_expanders/tsv as a plugin before you use QueryExpanderTSV:

register query_expanders/tsv

  Usage

You just add --query_expansion QueryExpanderTSV parameter to select command:

select --query "QUERY" --query_expansion QueryExpanderTSV

If QUERY has registered synonyms, they are expanded. For example, there are the following synonyms.
word | synonym 1 | synonym 2
groonga | groonga | Senna
mroonga | mroonga | groonga MySQL

The table means that synonym 1 and synonym 2 are synonyms of word. For example, groonga and Senna are synonyms of groonga. And mroonga and groonga MySQL are synonyms of mroonga.

Here is an example of query expnasion that uses groonga as query:

select --query "groonga" --query_expansion QueryExpanderTSV

The above command equals to the following command:

select --query "groonga OR Senna" --query_expansion QueryExpanderTSV

Here is another example of query expnasion that uses mroonga search as query:

select --query "mroonga search" --query_expansion QueryExpanderTSV

The above command equals to the following command:

select --query "(mroonga OR (groonga MySQL)) search" --query_expansion QueryExpanderTSV

It is important that registered words (groonga and mroonga) are only expanded to synonyms and not registered words (search) are not expanded. Query expansion isn't occurred recursively. groonga is appeared in (mroonga OR (groonga MySQL)) as query expansion result but it isn't expanded.

Normally, you need to include word itself into synonyms. For example, groonga and mroonga are included in synonyms of themselves. If you want to ignore word itself, you don't include word itself into synonyms. For example, if you want to use query expansion as spelling correction, you should use the following synonyms.
word | synonym
gronga | groonga

gronga in word has a typo. A o is missing. groonga in synonym is the correct word.

Here is an example of using query expnasion as spelling correction:

select --query "gronga" --query_expansion QueryExpanderTSV

The above command equals to the following command:

select --query "groonga" --query_expansion QueryExpanderTSV

The former command has a typo in --query value but the latter command doesn't have any typos.

  TSV File

Synonyms are defined in TSV format file. This section describes about it.

  Location

The file name should be synonyms.tsv and it is located at configuration directory. For example, /etc/groonga/synonyms.tsv is a TSV file location. The location is decided at build time.

You can change the location by environment variable GRN_QUERY_EXPANDER_TSV_SYNONYMS_FILE at run time:

% env GRN_QUERY_EXPANDER_TSV_SYNONYMS_FILE=/tmp/synonyms.tsv groonga

With the above command, /tmp/synonyms.tsv file is used.

  Format

You can define zero or more synonyms in a TSV file. You define a word and synonyms pair by a line. word is expanded to synonyms in --query value. Synonyms are combined by OR. For example, groonga and Senna synonyms are expanded as groonga OR Senna.

The first column is word and the rest columns are synonyms of the word. Here is a sample line for word is groonga and synonyms are groonga and Senna. (TAB) means a tab character (U+0009):

groonga(TAB)groonga(TAB)Senna

Comment line is supported. Lines that start with # are ignored. Here is an example for comment line. groonga line is ignored as comment line:

#groonga(TAB)groonga(TAB)Senna
mroonga(TAB)mroonga(TAB)groonga MySQL

  Limitation

You need to restart groonga to reload your synonyms. TSV file is loaded only at the plugin load time.

  See also

•   query-expansion

  疑似カラム (pseudo_column)

  名前

疑似カラム

  説明

groongaのデータベースで作成したテーブルには、いくつかのカラムが自動的に定義されます。

これらのカラムはいずれもアンダースコア('_')で始まる名前が付与されます。定義される疑似カラムは、テーブルの種類によって異なります。

_id レコードに付与される一意な番号です。全てのテーブルに定義されます。値の範囲は1〜1073741824の整数で、通常はレコードを追加した順に1ずつ加算されます。_idの値は不変で、レコードが存在する限り変更することはできません。ただし、削除されたレコードの_idの値は再利用されます。

_key レコードの主キー値を表します。主キーを持つテーブルのみに定義されます。主キー値はテーブルの中で一意であり、変更することはできません。

_value レコードの値を表します。value_typeを指定したテーブルのみに定義されます。自由に変更可能です。

_score 各レコードのスコア値を表します。検索結果として生成されたテーブルのみに定義されます。

検索処理を実行する過程で値が設定されますが、自由に変更可能です。

_nsubrecs 主キーの値が同一であったレコードの件数を表します。検索結果として生成されたテーブルのみに定義されます。グループ化(drilldown)処理を実行すると、グループ化前のテーブルにおいて、グループ化キーの値が同一であったレコードの件数が、グループ化処理の結果を格納するテーブルの_nsubrecsに記録されます。

  grn_expr

Grn_expr is an object that searches records with specified conditions and manipulates a database. It's pronounced as gurun expression.

Conditions for searching records from a database can be represented by conbining condition expressions such as equal condition expression and less than condition expression with set operations such as AND, OR and NOT. Grn_expr executes those conditions to search records. You can also use advanced searches such as similar search and near search by grn_expr. You can also use flexible full text search. For example, you can control hit scores for specified words and improve recall by re-searching with high-recall algolithm dinamically. To determine whether re-searching or not, the number of matched rescords is used.

There are three ways to create grn_expr:

•   Parsing /reference/grn_expr/query_syntax string.

•   Parsing /reference/grn_expr/script_syntax string.

•   Calling grn_expr related APIs.

    /reference/grn_expr/query_syntax is for common search form in Internet search site. It's simple and easy to use but it has a limitation. You can not use all condition expressions and set operations in /reference/grn_expr/query_syntax. You can use /reference/grn_expr/query_syntax with query option in /reference/commands/select.

    /reference/grn_expr/script_syntax is ECMAScript like syntax. You can use all condition expresssions and set operations in /reference/grn_expr/script_syntax. You can use /reference/grn_expr/script_syntax with filter option and scorer option in /reference/commands/select.

    You can use groonga as a library and create a grn_expr by calling grn_expr related APIs. You can use full features with calling APIs like /reference/grn_expr/script_syntax. Calling APIs is useful creating a custom syntax to create grn_expr. They are used in rroonga that is Ruby bindings of groonga. Rroonga can create a grn_expr by Ruby's syntax instead of parsing string.

  Query syntax

Query syntax is a syntax to specify search condition for common Web search form. It is similar to the syntax of Google's search form. For example, word1 word2 means that groonga searches records that contain both word1 and word2. word1 OR word2 means that groogna searches records that contain either word1 or word2.

Query syntax consists of conditional expression, combind expression and assignment expression. Nomrally assignment expression can be ignored. Because assignment expression is disabled in --query option of /reference/commands/select. You can use it if you use groonga as library and customize query syntax parser options.

Conditinal expression specifies an condition. Combinded expression consists of one or more conditional expression, combined expression or assignment expression. Assignment expression can assigns a column to a value.

  Sample data

Here are a schema definition and sample data to show usage.

Execution example:

table_create Entries TABLE_PAT_KEY ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Entries content COLUMN_SCALAR Text
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Entries n_likes COLUMN_SCALAR UInt32
# [[0, 1337566253.89858, 0.000355720520019531], true]
table_create Terms TABLE_PAT_KEY|KEY_NORMALIZE ShortText --default_tokenizer TokenBigram
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Terms entries_key_index COLUMN_INDEX|WITH_POSITION Entries _key
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Terms entries_content_index COLUMN_INDEX|WITH_POSITION Entries content
# [[0, 1337566253.89858, 0.000355720520019531], true]
load --table Entries
[
{"_key":    "The first post!",
 "content": "Welcome! This is my first post!",
 "n_likes": 5},
{"_key":    "Groonga",
 "content": "I started to use groonga. It's very fast!",
 "n_likes": 10},
{"_key":    "Mroonga",
 "content": "I also started to use mroonga. It's also very fast! Really fast!",
 "n_likes": 15},
{"_key":    "Good-bye Senna",
 "content": "I migrated all Senna system!",
 "n_likes": 3},
{"_key":    "Good-bye Tritonn",
 "content": "I also migrated all Tritonn system!",
 "n_likes": 3}
]
# [[0, 1337566253.89858, 0.000355720520019531], 5]

There is a table, Entries, for blog entries. An entry has title, content and the number of likes for the entry. Title is key of Entries. Content is value of Entries.content column. The number of likes is value of Entries.n_likes column.

Entries._key column and Entries.content column are indexed using TokenBigram tokenizer. So both Entries._key and Entries.content are fulltext search ready.

OK. The schema and data for examples are ready.

  Escape

There are special characters in query syntax. To use a special character as itself, it should be escaped by prepending \. For example, " is a special character. It is escaped as \".

Here is a special character list:

•   [space] (escaped as [backquote][space]) (You should substitute [space] with a white space character that is 0x20 in ASCII and [backquote] with \\.)

•   " (escaped as \")

•   ' (escaped as \')

•   ( (escaped as \()

•   ) (escaped as \))

•   \ (escaped as \\)

    You can use quote instead of escape. Quote syntax is "..." or '...'. You need escape " as \" in "..." quote syntax. You need escape ' as \' in '...' quote syntax. For example, Alice's brother (Bob) can be quoted "Alice's brother (Bob)" or 'Alice\'s brother (Bob)'.

  Conditional expression

Here is available conditional expression list.

  Full text search condition

Its syntax is keyword.

Full text search condition specifies a full text search condition against the default match columns. Match columns are full text search target columns.

You should specify the default match columns for full text search. They can be specified by --match_columns option of /reference/commands/select. If you don't specify the default match columns, this conditional expression fails.

This conditional expression does full text search with keyword. keyword should not contain any spaces. If keyword contains a space such as search keyword, it means two full text search conditions; search and keyword. If you want to specifies a keyword that contains one or more spaces, you can use phrase search condition that is described below.

Here is a simple exmaple.

Execution example:

select Entries --match_columns content --query fast
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         2,
#         "Groonga",
#         "I started to use groonga. It's very fast!",
#         10
#       ],
#       [
#         3,
#         "Mroonga",
#         "I also started to use mroonga. It's also very fast! Really fast!",
#         15
#       ]
#     ]
#   ]
# ]

The expression matches records that contain a word fast in content column value.

content column is the default match column.

  Phrase search condition

Its syntax is "search keyword".

Phrase search condition specifies a phrase search condition against the default match columns.

You should specify the default match columns for full text search. They can be specified by --match_columns option of /reference/commands/select. If you don't specify the default match columns, this conditional expression fails.

This conditional expression does phrase search with search keyword. Phrase search searches records that contain search and keyword and those terms are appeared in the same order and adjacent. Thus, Put a search keyword in the form is matched but Search by the keyword and There is a keyword. Search by it! aren't matched.

Here is a simple exmaple.

Execution example:

select Entries --match_columns content --query '"I started"'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         2,
#         "Groonga",
#         "I started to use groonga. It's very fast!",
#         10
#       ]
#     ]
#   ]
# ]

The expression matches records that contain a phrase I started in content column value. I also started isn't matched because I and started aren't adjacent.

content column is the default match column.

  Full text search condition (with explicit match column)

Its syntax is column:@keyword.

It's similar to full text search condition but it doesn't require the default match columns. You need to specify match column for the full text search condition by column: instead of --match_columns option of /reference/commands/select.

This condtional expression is useful when you want to use two or more full text search against different columns. The default match columns specified by --match_columns option can't be specified multiple times. You need to specify the second match column by this conditional expression.

The different between full text search condition and full text search condition (with explicit match column) is whether advanced match columns are supported or not. Full text search condition supports advanced match columns but full text search condition (with explicit match column) isn't supported. Advanced match columns has the following features:

•   Weight is supported.

•   Using multiple columns are supported.

•   Using index column as a match column is supported.

    See description of --match_columns option of /reference/commands/select about them.

    Here is a simple exmaple.

    Execution example:

    select Entries --query content:@fast
    # [
    #   [
    #     0,
    #     1337566253.89858,
    #     0.000355720520019531
    #   ],
    #   [
    #     [
    #       [
    #         2
    #       ],
    #       [
    #         [
    #           "_id",
    #           "UInt32"
    #         ],
    #         [
    #           "_key",
    #           "ShortText"
    #         ],
    #         [
    #           "content",
    #           "Text"
    #         ],
    #         [
    #           "n_likes",
    #           "UInt32"
    #         ]
    #       ],
    #       [
    #         2,
    #         "Groonga",
    #         "I started to use groonga. It's very fast!",
    #         10
    #       ],
    #       [
    #         3,
    #         "Mroonga",
    #         "I also started to use mroonga. It's also very fast! Really fast!",
    #         15
    #       ]
    #     ]
    #   ]
    # ]

    The expression matches records that contain a word fast in content column value.

  Phrase search condition (with explicit match column)

Its syntax is column:@"search keyword".

It's similar to phrase search condition but it doesn't require the default match columns. You need to specify match column for the phrase search condition by column: instead of --match_columns option of /reference/commands/select.

The different between phrase search condition and phrase search condition (with explicit match column) is similar to between full text search condition and full text search condition (with explicit match column). Phrase search condition supports advanced match columns but phrase search condition (with explicit match column) isn't supported. See description of full text search condition (with explicit match column) about advanced match columns.

Here is a simple exmaple.

Execution example:

select Entries --query 'content:@"I started"'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         2,
#         "Groonga",
#         "I started to use groonga. It's very fast!",
#         10
#       ]
#     ]
#   ]
# ]

The expression matches records that contain a phrase I started in content column value. I also started isn't matched because I and started aren't adjacent.

  Prefix search condition

Its syntax is column:^value or value*.

This conditional expression does prefix search with value. Prefix search searches records that contain a word that starts with value.

You can use fast prefix search against a column. The column must be indexed and index table must be patricia trie table (TABLE_PAT_KEY) or double array trie table (TABLE_DAT_KEY). You can also use fast prefix search against _key pseudo column of patricia trie table or double array trie table. You don't need to index _key.

Prefix search can be used with other table types but it causes all records scan. It's not problem for small records but it spends more time for large records.

It doesn't require the default match columns such as full text search condition and phrase search condition.

Here is a simple exmaple.

Execution example:

select Entries --query '_key:^Goo'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         5,
#         "Good-bye Tritonn",
#         "I also migrated all Tritonn system!",
#         3
#       ],
#       [
#         4,
#         "Good-bye Senna",
#         "I migrated all Senna system!",
#         3
#       ]
#     ]
#   ]
# ]

The expression matches records that contain a word that starts with Goo in _key pseudo column value. Good-bye Senna and Good-bye Tritonn are matched with the expression.

  Suffix search condition

Its syntax is column:$value.

This conditional expression does suffix search with value. Suffix search searches records that contain a word that ends with value.

You can use fast suffix search against a column. The column must be indexed and index table must be patricia trie table (TABLE_PAT_KEY) with KEY_WITH_SIS flag. You can also use fast suffix search against _key pseudo column of patricia trie table (TABLE_PAT_KEY) with KEY_WITH_SIS flag. You don't need to index _key. We recommended that you use index column based fast suffix search instead of _key based fast suffix search. _key based fast suffix search returns automatically registered substrings. (TODO: write document about suffix search and link to it from here.)

Note
    Fast suffix search can be used only for non-ASCII characters such as hiragana in Japanese. You cannot use fast suffix search for ASCII character.

Suffix search can be used with other table types or patricia trie table without KEY_WITH_SIS flag but it causes all records scan. It's not problem for small records but it spends more time for large records.

It doesn't require the default match columns such as full text search condition and phrase search condition.

Here is a simple exmaple. It uses fast suffix search for hiragana in Japanese that is one of non-ASCII characters.

Execution example:

table_create Titles TABLE_NO_KEY
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Titles content COLUMN_SCALAR ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
table_create SuffixSearchTerms TABLE_PAT_KEY|KEY_WITH_SIS ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create SuffixSearchTerms index COLUMN_INDEX Titles content
# [[0, 1337566253.89858, 0.000355720520019531], true]
load --table Titles
[
{"content": "ぐるんが"},
{"content": "むるんが"},
{"content": "せな"},
{"content": "とりとん"}
]
# [[0, 1337566253.89858, 0.000355720520019531], 4]
select Titles --query 'content:$んが'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "content",
#           "ShortText"
#         ]
#       ],
#       [
#         2,
#         "むるんが"
#       ],
#       [
#         1,
#         "ぐるんが"
#       ]
#     ]
#   ]
# ]

The expression matches records that have value that ends with んが in content column value. ぐるんが and むるんが are matched with the expression.

  Equal condition

Its syntax is column:value.

It matches records that column value is equal to value.

It doesn't require the default match columns such as full text search condition and phrase search condition.

Here is a simple exmaple.

Execution example:

select Entries --query _key:Groonga
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         2,
#         "Groonga",
#         "I started to use groonga. It's very fast!",
#         10
#       ]
#     ]
#   ]
# ]

The expression matches records that _key column value is equal to Groonga.

  Not equal condition

Its syntax is column:!value.

It matches records that column value isn't equal to value.

It doesn't require the default match columns such as full text search condition and phrase search condition.

Here is a simple exmaple.

Execution example:

select Entries --query _key:!Groonga
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         4
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         4,
#         "Good-bye Senna",
#         "I migrated all Senna system!",
#         3
#       ],
#       [
#         5,
#         "Good-bye Tritonn",
#         "I also migrated all Tritonn system!",
#         3
#       ],
#       [
#         3,
#         "Mroonga",
#         "I also started to use mroonga. It's also very fast! Really fast!",
#         15
#       ],
#       [
#         1,
#         "The first post!",
#         "Welcome! This is my first post!",
#         5
#       ]
#     ]
#   ]
# ]

The expression matches records that _key column value is not equal to Groonga.

  Less than condition

Its syntax is column:<value.

It matches records that column value is less than value.

If column type is numerical type such as Int32, column value and value are compared as number. If column type is text type such as ShortText, column value and value are compared as bit sequence.

It doesn't require the default match columns such as full text search condition and phrase search condition.

Here is a simple exmaple.

Execution example:

select Entries --query n_likes:<10
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         3
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         4,
#         "Good-bye Senna",
#         "I migrated all Senna system!",
#         3
#       ],
#       [
#         5,
#         "Good-bye Tritonn",
#         "I also migrated all Tritonn system!",
#         3
#       ],
#       [
#         1,
#         "The first post!",
#         "Welcome! This is my first post!",
#         5
#       ]
#     ]
#   ]
# ]

The expression matches records that n_likes column value is less than 10.

  Greater than condition

Its syntax is column:>value.

It matches records that column value is greater than value.

If column type is numerical type such as Int32, column value and value are compared as number. If column type is text type such as ShortText, column value and value are compared as bit sequence.

It doesn't require the default match columns such as full text search condition and phrase search condition.

Here is a simple exmaple.

Execution example:

select Entries --query n_likes:>10
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         3,
#         "Mroonga",
#         "I also started to use mroonga. It's also very fast! Really fast!",
#         15
#       ]
#     ]
#   ]
# ]

The expression matches records that n_likes column value is greater than 10.

  Less than or equal to condition

Its syntax is column:<=value.

It matches records that column value is less than or equal to value.

If column type is numerical type such as Int32, column value and value are compared as number. If column type is text type such as ShortText, column value and value are compared as bit sequence.

It doesn't require the default match columns such as full text search condition and phrase search condition.

Here is a simple exmaple.

Execution example:

select Entries --query n_likes:<=10
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         4
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         4,
#         "Good-bye Senna",
#         "I migrated all Senna system!",
#         3
#       ],
#       [
#         5,
#         "Good-bye Tritonn",
#         "I also migrated all Tritonn system!",
#         3
#       ],
#       [
#         2,
#         "Groonga",
#         "I started to use groonga. It's very fast!",
#         10
#       ],
#       [
#         1,
#         "The first post!",
#         "Welcome! This is my first post!",
#         5
#       ]
#     ]
#   ]
# ]

The expression matches records that n_likes column value is less than or equal to 10.

  Greater than or equal to condition

Its syntax is column:>=value.

It matches records that column value is greater than or equal to value.

If column type is numerical type such as Int32, column value and value are compared as number. If column type is text type such as ShortText, column value and value are compared as bit sequence.

It doesn't require the default match columns such as full text search condition and phrase search condition.

Here is a simple exmaple.

Execution example:

select Entries --query n_likes:>=10
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         2,
#         "Groonga",
#         "I started to use groonga. It's very fast!",
#         10
#       ],
#       [
#         3,
#         "Mroonga",
#         "I also started to use mroonga. It's also very fast! Really fast!",
#         15
#       ]
#     ]
#   ]
# ]

The expression matches records that n_likes column value is greater than or equal to 10.

  Combined expression

Here is available combined expression list.

  Logical OR

Its syntax is a OR b.

a and b are conditional expressions, conbinded expressions or assignment expressions.

If at least one of a and b are matched, a OR b is matched.

Here is a simple exmaple.

Execution example:

select Entries --query 'n_likes:>10 OR content:@senna'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         3,
#         "Mroonga",
#         "I also started to use mroonga. It's also very fast! Really fast!",
#         15
#       ],
#       [
#         4,
#         "Good-bye Senna",
#         "I migrated all Senna system!",
#         3
#       ]
#     ]
#   ]
# ]

The expression matches records that n_likes column value is greater than 10 or contain a word senna in content column value.

  Logical AND

Its syntax is a + b or just a b.

a and b are conditional expressions, conbinded expressions or assignment expressions.

If both a and b are matched, a + b is matched.

You can specify + the first expression such as +a. The + is just ignored.

Here is a simple exmaple.

Execution example:

select Entries --query 'n_likes:>=10 + content:@groonga'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         2,
#         "Groonga",
#         "I started to use groonga. It's very fast!",
#         10
#       ]
#     ]
#   ]
# ]

The expression matches records that n_likes column value is greater than or equal to 10 and contain a word groonga in content column value.

  Logical NOT

Its syntax is a - b.

a and b are conditional expressions, conbinded expressions or assignment expressions.

If a is matched and b is not matched, a - b is matched.

You can not specify - the first expression such as -a. It's syntax error.

Here is a simple exmaple.

Execution example:

select Entries --query 'n_likes:>=10 - content:@groonga'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         3,
#         "Mroonga",
#         "I also started to use mroonga. It's also very fast! Really fast!",
#         15
#       ]
#     ]
#   ]
# ]

The expression matches records that n_likes column value is greater than or equal to 10 and don't contain a word groonga in content column value.

  Grouping

Its syntax is (...). ... is space separated expression list.

(...) groups one ore more expressions and they can be processed as an expression. a b OR c means that a and b are matched or c is matched. a (b OR c) means that a and one of b and c are matched.

Here is a simple exmaple.

Execution example:

select Entries --query 'n_likes:<5 content:@senna OR content:@fast'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         3
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         4,
#         "Good-bye Senna",
#         "I migrated all Senna system!",
#         3
#       ],
#       [
#         2,
#         "Groonga",
#         "I started to use groonga. It's very fast!",
#         10
#       ],
#       [
#         3,
#         "Mroonga",
#         "I also started to use mroonga. It's also very fast! Really fast!",
#         15
#       ]
#     ]
#   ]
# ]
select Entries --query 'n_likes:<5 (content:@senna OR content:@fast)'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         4,
#         "Good-bye Senna",
#         "I migrated all Senna system!",
#         3
#       ]
#     ]
#   ]
# ]

The first expression doesn't use grouping. It matches records that n_likes:<5 and content:@senna are matched or content:@fast is matched.

The second expression uses grouping. It matches records that n_likes:<5 and one of content:@senna or content:@fast are matched.

  Assignment expression

This section is for advanced users. Because assignment expression is disabled in --query option of /reference/commands/select by default. You need to specify ALLOW_COLUMN|ALLOW_UPDATE as --query_flags option value to enable assignment expression.

Assignment expression in query syntax has some limitations. So you should use /reference/grn_expr/script_syntax instead of query syntax for assignment.

There is only one syntax for assignment expression. It's column:=value.

value is assigend to column. value is always processed as string in query syntax. value is casted to the type of column automatically. It causes some limitations. For example, you cannot use boolean literal such as true and false for Bool type column. You need to use empty string for false but query syntax doesn't support column:= syntax.

See /reference/cast about cast.

  Script syntax

Script syntax is a syntax to specify complex search condition. It is similar to ECMAScript. For example, _key == "book" means that groonga searches records that _key value is "book". All values are string in query_syntax but its own type in script syntax. For example, "book" is string, 1 is integer, TokenBigram is the object whose name is TokenBigram and so on.

Script syntax doesn't support full ECMAScript syntax. For example, script syntax doesn't support statement such as if control statement, for iteration statement and variable definition statement. Function definion is not supported too. But script syntax addes the original additional operators. They are described after ECMAScript syntax is described.

  Sample data

Here are a schema definition and sample data to show usage.

Execution example:

table_create Entries TABLE_PAT_KEY ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Entries content COLUMN_SCALAR Text
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Entries n_likes COLUMN_SCALAR UInt32
# [[0, 1337566253.89858, 0.000355720520019531], true]
table_create Terms TABLE_PAT_KEY|KEY_NORMALIZE ShortText --default_tokenizer TokenBigram
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Terms entries_key_index COLUMN_INDEX|WITH_POSITION Entries _key
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Terms entries_content_index COLUMN_INDEX|WITH_POSITION Entries content
# [[0, 1337566253.89858, 0.000355720520019531], true]
load --table Entries
[
{"_key":    "The first post!",
 "content": "Welcome! This is my first post!",
 "n_likes": 5},
{"_key":    "Groonga",
 "content": "I started to use groonga. It's very fast!",
 "n_likes": 10},
{"_key":    "Mroonga",
 "content": "I also started to use mroonga. It's also very fast! Really fast!",
 "n_likes": 15},
{"_key":    "Good-bye Senna",
 "content": "I migrated all Senna system!",
 "n_likes": 3},
{"_key":    "Good-bye Tritonn",
 "content": "I also migrated all Tritonn system!",
 "n_likes": 3}
]
# [[0, 1337566253.89858, 0.000355720520019531], 5]

There is a table, Entries, for blog entries. An entry has title, content and the number of likes for the entry. Title is key of Entries. Content is value of Entries.content column. The number of likes is value of Entries.n_likes column.

Entries._key column and Entries.content column are indexed using TokenBigram tokenizer. So both Entries._key and Entries.content are fulltext search ready.

OK. The schema and data for examples are ready.

  Literals

  Integer

Integer literal is sequence of 0 to 9 such as 1234567890. + or - can be prepended as sign such as +29 and -29. Integer literal must be decimal. Octal notation, hex and so on can't be used.

The maximum value of integer literal is 9223372036854775807 (= 2 ** 63 - 1). The minimum value of integer literal is -9223372036854775808 (= -(2 ** 63)).

  Float

Float literal is sequence of 0 to 9, . and 0 to 9 such as 3.14. + or - can be prepended as sign such as +3.14 and -3.14. ${RADIX}e${EXPORNENTIAL} and ${RADIX}E${EXPORNENTIAL} formats are also supported. For example, 314e-2 is the same as 3.14.

  String

String literal is "...". You need to escape " in literal by prepending \\'' such as ``\". For example, "Say \"Hello!\"." is a literal for Say "Hello!". string.

String encoding must be the same as encoding of database. The default encoding is UTF-8. It can be changed by --with-default-encoding configure option, --encodiong /reference/executables/groonga option and so on.

  Boolean

Boolean literal is true and false. true means true and false means false.

  Null

Null literal is null. Groonga doesn't support null value but null literal is supported.

  Time

Note
    This is the groonga original notation.

Time literal doesn't exit. There are string time notation, integer time notation and float time notation.

String time notation is "YYYY/MM/DD hh:mm:ss.uuuuuu" or "YYYY-MM-DD hh:mm:ss.uuuuuu". YYYY is year, MM is month, DD is day, hh is hour, mm is minute, ss is second and uuuuuu is micro second. It is local time. For example, "2012/07/23 02:41:10.436218" is 2012-07-23T02:41:10.436218 in ISO 8601 format.

Integer time notation is the number of seconds that have elapsed since midnight UTC, January 1, 1970. It is also known as POSIX time. For example, 1343011270 is 2012-07-23T02:41:10Z in ISO 8601 format.

Float time notation is the number of seconds and micro seconds that have elapsed since midnight UTC, January 1, 1970. For example, 1343011270.436218 is 2012-07-23T02:41:10.436218Z in ISO 8601 format.

  Geo point

Note
    This is the groonga original notation.

Geo point literal doesn't exist. There is string geo point notation.

String geo point notation has the following patterns:

•   "LATITUDE_IN_MSECxLONGITUDE_IN_MSEC"

•   "LATITUDE_IN_MSEC,LONGITUDE_IN_MSEC"

•   "LATITUDE_IN_DEGREExLONGITUDE_IN_DEGREE"

•   "LATITUDE_IN_DEGREE,LONGITUDE_IN_DEGREE"

    x and , can be used for separator. Latitude and longitude can be represented in milliseconds or degree.

  Array

Array literal is [element1, element2, ...].

  Object literal

Object literal is {name1: value1, name2: value2, ...}. Groonga doesn't support object literal yet.

  Control syntaxes

Script syntax doesn't support statement. So you cannot use control statement such as if. You can only use A ? B : C expression as control syntax.

A ? B : C returns B if A is true, C otherwise.

Here is a simple exmaple.

Execution example:

select Entries --filter 'n_likes == (_id == 1 ? 5 : 3)'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         3
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         4,
#         "Good-bye Senna",
#         "I migrated all Senna system!",
#         3
#       ],
#       [
#         5,
#         "Good-bye Tritonn",
#         "I also migrated all Tritonn system!",
#         3
#       ],
#       [
#         1,
#         "The first post!",
#         "Welcome! This is my first post!",
#         5
#       ]
#     ]
#   ]
# ]

The expression matches records that _id column value is equal to 1 and n_likes column value is equal to 5 or _id column value is not equal to 1 and n_likes column value is equal to 3.

  Grouping

Its syntax is (...). ... is comma separated expression list.

(...) groups one ore more expressions and they can be processed as an expression. a && b || c means that a and b are matched or c is matched. a && (b || c) means that a and one of b and c are matched.

Here is a simple exmaple.

Execution example:

select Entries --filter 'n_likes < 5 && content @ "senna" || content @ "fast"'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         3
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         4,
#         "Good-bye Senna",
#         "I migrated all Senna system!",
#         3
#       ],
#       [
#         2,
#         "Groonga",
#         "I started to use groonga. It's very fast!",
#         10
#       ],
#       [
#         3,
#         "Mroonga",
#         "I also started to use mroonga. It's also very fast! Really fast!",
#         15
#       ]
#     ]
#   ]
# ]
select Entries --filter 'n_likes < 5 && (content @ "senna" || content @ "fast")'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         4,
#         "Good-bye Senna",
#         "I migrated all Senna system!",
#         3
#       ]
#     ]
#   ]
# ]

The first expression doesn't use grouping. It matches records that n_likes < 5 and content @ "senna" are matched or content @ "fast" is matched.

The second expression uses grouping. It matches records that n_likes < 5 and one of content @ "senna" or content @ "fast" are matched.

  Function call

Its syntax is name(arugment1, argument2, ...).

name(argument1, argument2, ...) calls a function that is named name with arguments argument1, argument2 and ....

See /reference/function for available functin list.

Here is a simple exmaple.

Execution example:

select Entries --filter 'edit_distance(_key, "Groonga") <= 1'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         2,
#         "Groonga",
#         "I started to use groonga. It's very fast!",
#         10
#       ],
#       [
#         3,
#         "Mroonga",
#         "I also started to use mroonga. It's also very fast! Really fast!",
#         15
#       ]
#     ]
#   ]
# ]

The expression uses /reference/functions/edit_distance. It matches records that _key column value is similar to "Groonga". Similality of "Groonga" is computed as edit distance. If edit distance is less than or equal to 1, the value is treated as similar. In this case, "Groonga" and "Mroonga" are treated as similar.

  Basic operators

Groonga supports operators defined in ECMAScript.

  Arithmetic operators

Here are arithmetic operators.

  Addition operator

Its syntax is number1 + number2.

The operator adds number1 and number2 and returns the result.

Here is a simple example.

Execution example:

select Entries --filter 'n_likes == 10 + 5'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         3,
#         "Mroonga",
#         "I also started to use mroonga. It's also very fast! Really fast!",
#         15
#       ]
#     ]
#   ]
# ]

The expression matches records that n_likes column value is equal to 15 (= 10 + 5).

  Subtraction operator

Its syntax is number1 - number2.

The operator subtracts number2 from number1 and returns the result.

Here is a simple example.

Execution example:

select Entries --filter 'n_likes == 20 - 5'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         3,
#         "Mroonga",
#         "I also started to use mroonga. It's also very fast! Really fast!",
#         15
#       ]
#     ]
#   ]
# ]

The expression matches records that n_likes column value is equal to 15 (= 20 - 5).

  Multiplication operator

Its syntax is number1 * number2.

The operator multiplies number1 and number2 and returns the result.

Here is a simple example.

Execution example:

select Entries --filter 'n_likes == 3 * 5'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         3,
#         "Mroonga",
#         "I also started to use mroonga. It's also very fast! Really fast!",
#         15
#       ]
#     ]
#   ]
# ]

The expression matches records that n_likes column value is equal to 15 (= 3 * 5).

  Division operator

Its syntax is number1 / number2 and number1 % number2.

The operator divides number2 by number1. / returns the quotient of result. % returns the remainder of result.

Here is simple examples.

Execution example:

select Entries --filter 'n_likes == 26 / 7'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         4,
#         "Good-bye Senna",
#         "I migrated all Senna system!",
#         3
#       ],
#       [
#         5,
#         "Good-bye Tritonn",
#         "I also migrated all Tritonn system!",
#         3
#       ]
#     ]
#   ]
# ]

The expression matches records that n_likes column value is equal to 3 (= 26 / 7).

Execution example:

select Entries --filter 'n_likes == 26 % 7'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         1,
#         "The first post!",
#         "Welcome! This is my first post!",
#         5
#       ]
#     ]
#   ]
# ]

The expression matches records that n_likes column value is equal to 5 (= 26 % 7).

  Logical operators

Here are logical operators.

  Logical NOT operator

Its syntax is !condition.

The operator inverts boolean value of condition.

Here is a simple example.

Execution example:

select Entries --filter '!(n_likes == 5)'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         4
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         4,
#         "Good-bye Senna",
#         "I migrated all Senna system!",
#         3
#       ],
#       [
#         5,
#         "Good-bye Tritonn",
#         "I also migrated all Tritonn system!",
#         3
#       ],
#       [
#         2,
#         "Groonga",
#         "I started to use groonga. It's very fast!",
#         10
#       ],
#       [
#         3,
#         "Mroonga",
#         "I also started to use mroonga. It's also very fast! Really fast!",
#         15
#       ]
#     ]
#   ]
# ]

The expression matches records that n_likes column value is not equal to 5.

  Logical AND operator

Its syntax is condition1 && condition2.

The operator returns true if both of condition1 and condition2 are true, false otherwise.

Here is a simple example.

Execution example:

select Entries --filter 'content @ "fast" && n_likes >= 10'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         2,
#         "Groonga",
#         "I started to use groonga. It's very fast!",
#         10
#       ],
#       [
#         3,
#         "Mroonga",
#         "I also started to use mroonga. It's also very fast! Really fast!",
#         15
#       ]
#     ]
#   ]
# ]

The expression matches records that content column value has the word fast and n_likes column value is greater or equal to 10.

  Logical OR operator

Its syntax is condition1 || condition2.

The operator returns true if either condition1 or condition2 is true, false otherwise.

Here is a simple example.

Execution example:

select Entries --filter 'n_likes == 5 || n_likes == 10'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         1,
#         "The first post!",
#         "Welcome! This is my first post!",
#         5
#       ],
#       [
#         2,
#         "Groonga",
#         "I started to use groonga. It's very fast!",
#         10
#       ]
#     ]
#   ]
# ]

The expression matches records that n_likes column value is equal to 5 or 10.

  Logical AND NOT operator

Its syntax is condition1 &! condition2.

The operator returns true if condition1 is true but condition2 is false, false otherwise. It returns difference set.

Here is a simple example.

Execution example:

select Entries --filter 'content @ "fast" &! content @ "mroonga"'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         2,
#         "Groonga",
#         "I started to use groonga. It's very fast!",
#         10
#       ]
#     ]
#   ]
# ]

The expression matches records that content column value has the word fast but doesn't have the word mroonga.

  Bitwise operators

Here are bitwise operators.

  Bitwise NOT operator

Its syntax is ~number.

The operator returns bitwise NOT of number.

Here is a simple example.

Execution example:

select Entries --filter '~n_likes == -6'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         1,
#         "The first post!",
#         "Welcome! This is my first post!",
#         5
#       ]
#     ]
#   ]
# ]

The expression matches records that n_likes column value is equal to 5 because bitwise NOT of 5 is equal to -6.

  Bitwise AND operator

Its syntax is number1 & number2.

The operator returns bitwise AND between number1 and number2.

Here is a simple example.

Execution example:

select Entries --filter '(n_likes & 1) == 1'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         4
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         4,
#         "Good-bye Senna",
#         "I migrated all Senna system!",
#         3
#       ],
#       [
#         5,
#         "Good-bye Tritonn",
#         "I also migrated all Tritonn system!",
#         3
#       ],
#       [
#         3,
#         "Mroonga",
#         "I also started to use mroonga. It's also very fast! Really fast!",
#         15
#       ],
#       [
#         1,
#         "The first post!",
#         "Welcome! This is my first post!",
#         5
#       ]
#     ]
#   ]
# ]

The expression matches records that n_likes column value is even number because bitwise AND between an even number and 1 is equal to 1 and bitwise AND between an odd number and 1 is equal to 0.

  Bitwise OR operator

Its syntax is number1 | number2.

The operator returns bitwise OR between number1 and number2.

Here is a simple example.

Execution example:

select Entries --filter 'n_likes == (1 | 4)'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         1,
#         "The first post!",
#         "Welcome! This is my first post!",
#         5
#       ]
#     ]
#   ]
# ]

The expression matches records that n_likes column value is equal to 5 (= 1 | 4).

  Bitwise XOR operator

Its syntax is number1 ^ number2.

The operator returns bitwise XOR between number1 and number2.

Here is a simple example.

Execution example:

select Entries --filter 'n_likes == (10 ^ 15)'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         1,
#         "The first post!",
#         "Welcome! This is my first post!",
#         5
#       ]
#     ]
#   ]
# ]

The expression matches records that n_likes column value is equal to 5 (= 10 ^ 15).

  Shift operators

Here are shift operators.

  Left shift operator

Its syntax is number1 << number2.

The operator performs a bitwise left shift operation on number1 by number2.

Here is a simple example.

Execution example:

select Entries --filter 'n_likes == (5 << 1)'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         2,
#         "Groonga",
#         "I started to use groonga. It's very fast!",
#         10
#       ]
#     ]
#   ]
# ]

The expression matches records that n_likes column value is equal to 10 (= 5 << 1).

  Signed right shift operator

Its syntax is number1 >> number2.

The operator shifts bits of number1 to right by number2. The sign of the result is the same as number1.

Here is a simple example.

Execution example:

select Entries --filter 'n_likes == -(-10 >> 1)'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         1,
#         "The first post!",
#         "Welcome! This is my first post!",
#         5
#       ]
#     ]
#   ]
# ]

The expression matches records that n_likes column value is equal to 5 (= -(-10 >> 1) = -(-5)).

  Unsigned right shift operator

Its syntax is number1 >>> number2.

The operator shifts bits of number1 to right by number2. The leftmost number2 bits are filled by 0.

Here is a simple example.

Execution example:

select Entries --filter 'n_likes == (2147483648 - (-10 >>> 1))'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         1,
#         "The first post!",
#         "Welcome! This is my first post!",
#         5
#       ]
#     ]
#   ]
# ]

The expression matches records that n_likes column value is equal to 5 (= 2147483648 - (-10 >>> 1) = 2147483648 - 2147483643).

  Comparison operators

Here are comparison operators.

  Equal operator

Its syntax is object1 == object2.

The operator returns true if object1 equals to object2, false otherwise.

Here is a simple example.

Execution example:

select Entries --filter 'n_likes == 5'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         1,
#         "The first post!",
#         "Welcome! This is my first post!",
#         5
#       ]
#     ]
#   ]
# ]

The expression matches records that n_likes column value is equal to 5.

  Not equal operator

Its syntax is object1 != object2.

The operator returns true if object1 does not equal to object2, false otherwise.

Here is a simple example.

Execution example:

select Entries --filter 'n_likes != 5'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         4
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "_key",
#           "ShortText"
#         ],
#         [
#           "content",
#           "Text"
#         ],
#         [
#           "n_likes",
#           "UInt32"
#         ]
#       ],
#       [
#         4,
#         "Good-bye Senna",
#         "I migrated all Senna system!",
#         3
#       ],
#       [
#         5,
#         "Good-bye Tritonn",
#         "I also migrated all Tritonn system!",
#         3
#       ],
#       [
#         2,
#         "Groonga",
#         "I started to use groonga. It's very fast!",
#         10
#       ],
#       [
#         3,
#         "Mroonga",
#         "I also started to use mroonga. It's also very fast! Really fast!",
#         15
#       ]
#     ]
#   ]
# ]

The expression matches records that n_likes column value is not equal to 5.

  Less than operator

TODO: ...

  Less than or equal to operator

TODO: ...

  Greater than operator

TODO: ...

  Greater than or equal to operator

TODO: ...

  Assignment operators

TODO: ...

  Original operators

Script syntax adds the original binary opearators to ECMAScript syntax. They operate search specific operations. They are starts with @ or *.

  Match operator

Its syntax is column @ value.

The operator searches value by inverted index of column. Normally, full text search is operated but tag search can be operated. Because tag search is also implemented by inverted index.

query_syntax uses this operator by default.

Here is a simple exmaple.

Execution example:

select Entries --filter 'content @ "fast"' --output_columns content
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "content",
#           "Text"
#         ]
#       ],
#       [
#         "I started to use groonga. It's very fast!"
#       ],
#       [
#         "I also started to use mroonga. It's also very fast! Really fast!"
#       ]
#     ]
#   ]
# ]

The expression matches records that contain a word fast in content column value.

  Prefix search operator

Its syntax is column @^ value.

The operator does prefix search with value. Prefix search searches records that contain a word that starts with value.

You can use fast prefix search against a column. The column must be indexed and index table must be patricia trie table (TABLE_PAT_KEY) or double array trie table (TABLE_DAT_KEY). You can also use fast prefix search against _key pseudo column of patricia trie table or double array trie table. You don't need to index _key.

Prefix search can be used with other table types but it causes all records scan. It's not problem for small records but it spends more time for large records.

Here is a simple exmaple.

Execution example:

select Entries --filter '_key @^ "Goo"' --output_columns _key
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ]
#       ],
#       [
#         "Good-bye Tritonn"
#       ],
#       [
#         "Good-bye Senna"
#       ]
#     ]
#   ]
# ]

The expression matches records that contain a word that starts with Goo in _key pseudo column value. Good-bye Senna and Good-bye Tritonn are matched with the expression.

  Suffix search operator

Its syntax is column @$ value.

This operator does suffix search with value. Suffix search searches records that contain a word that ends with value.

You can use fast suffix search against a column. The column must be indexed and index table must be patricia trie table (TABLE_PAT_KEY) with KEY_WITH_SIS flag. You can also use fast suffix search against _key pseudo column of patricia trie table (TABLE_PAT_KEY) with KEY_WITH_SIS flag. You don't need to index _key. We recommended that you use index column based fast suffix search instead of _key based fast suffix search. _key based fast suffix search returns automatically registered substrings. (TODO: write document about suffix search and link to it from here.)

Note
    Fast suffix search can be used only for non-ASCII characters such as hiragana in Japanese. You cannot use fast suffix search for ASCII character.

Suffix search can be used with other table types or patricia trie table without KEY_WITH_SIS flag but it causes all records scan. It's not problem for small records but it spends more time for large records.

Here is a simple exmaple. It uses fast suffix search for hiragana in Japanese that is one of non-ASCII characters.

Execution example:

table_create Titles TABLE_NO_KEY
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Titles content COLUMN_SCALAR ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
table_create SuffixSearchTerms TABLE_PAT_KEY|KEY_WITH_SIS ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create SuffixSearchTerms index COLUMN_INDEX Titles content
# [[0, 1337566253.89858, 0.000355720520019531], true]
load --table Titles
[
{"content": "ぐるんが"},
{"content": "むるんが"},
{"content": "せな"},
{"content": "とりとん"}
]
# [[0, 1337566253.89858, 0.000355720520019531], 4]
select Titles --query 'content:$んが'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "content",
#           "ShortText"
#         ]
#       ],
#       [
#         2,
#         "むるんが"
#       ],
#       [
#         1,
#         "ぐるんが"
#       ]
#     ]
#   ]
# ]

The expression matches records that have value that ends with んが in content column value. ぐるんが and むるんが are matched with the expression.

  Near search operator

Its syntax is column *N "word1 word2 ...".

The operator does near search with words word1 word2 .... Near search searches records that contain the words and the words are appeared in the near distance. Near distance is always 10 for now. The unit of near distance is the number of characters in N-gram family tokenizers and the number of words in morphological analysis family tokenizers.

(TODO: Add a description about TokenBigram doesn't split ASCII only word into tokens. So the unit for ASCII words with TokenBigram is the number of words even if TokenBigram is a N-gram family tokenizer.)

Note that an index column for full text search must be defined for column.

Here is a simple exmaple.

Execution example:

select Entries --filter 'content *N "I fast"'      --output_columns content
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "content",
#           "Text"
#         ]
#       ],
#       [
#         "I started to use groonga. It's very fast!"
#       ]
#     ]
#   ]
# ]
select Entries --filter 'content *N "I Really"'    --output_columns content
# [[0, 1337566253.89858, 0.000355720520019531], [[[0], [["content", "Text"]]]]]
select Entries --filter 'content *N "also Really"' --output_columns content
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "content",
#           "Text"
#         ]
#       ],
#       [
#         "I also started to use mroonga. It's also very fast! Really fast!"
#       ]
#     ]
#   ]
# ]

The first expression matches records that contain I and fast and the near distance of those words are in 10 words. So the record that its content is I also started to use mroonga. It's also very fast! ... is matched. The number of words between I and fast is just 10.

The second expression matches records that contain I and Really and the near distance of those words are in 10 words. So the record that its content is I also started to use mroonga. It's also very fast! Really fast! is not matched. The number of words between I and Really is 11.

The third expression matches records that contain also and Really and the near distance of those words are in 10 words. So the record that its content is I also st arted to use mroonga. It's also very fast! Really fast! is matched. The number of words between also and Really is 10.

  Similar search

Its syntax is column *S "document".

The operator does similar search with document document. Similar search searches records that have similar content to document.

Note that an index column for full text search must be defined for column.

Here is a simple exmaple.

Execution example:

select Entries --filter 'content *S "I migrated all Solr system!"' --output_columns content
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "content",
#           "Text"
#         ]
#       ],
#       [
#         "I migrated all Senna system!"
#       ],
#       [
#         "I also migrated all Tritonn system!"
#       ]
#     ]
#   ]
# ]

The expression matches records that have similar content to I migrated all Solr system!. In this case, records that have I migrated all XXX system! content are matched.

  Term extract operator

Its syntax is _key *T "document".

The operator extracts terms from document. Terms must be registered as keys of the table of _key.

Note that the table must be patricia trie (TABLE_PAT_KEY) or double array trie (TABLE_DAT_KEY). You can't use hash table (TABLE_HASH_KEY) and array (TABLE_NO_KEY) becuase they don't support longest common prefix search. Longest common prefix search is used to implement the operator.

Here is a simple exmaple.

Execution example:

table_create Words TABLE_PAT_KEY|KEY_NORMALIZE ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
load --table Words
[
{"_key": "groonga"},
{"_key": "mroonga"},
{"_key": "Senna"},
{"_key": "Tritonn"}
]
# [[0, 1337566253.89858, 0.000355720520019531], 4]
select Words --filter '_key *T "Groonga is the successor project to Senna."' --output_columns _key
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_key",
#           "ShortText"
#         ]
#       ],
#       [
#         "groonga"
#       ],
#       [
#         "senna"
#       ]
#     ]
#   ]
# ]

The expression extrcts terms that included in document Groonga is the successor project to Senna.. In this case, KEY_NORMALIZE flag is specified to Words. So Groonga can be extracted even if it is loaded as groonga into Words. All of extracted terms are also normalized.

  See also

•   /reference/api/grn_expr: grn_expr related APIs

  Function

Function can be used in some commands. For example, you can use function in --filter, --scorer and output_columns options of commands/select.

This section describes about function and built-in functions.

TODO: Add documentations about function.

  edit_distance

  名前

edit_distance - 指定した2つの文字列の編集距離を計算する

  書式

edit_distance(string1, string2)

  説明

groonga組込関数の一つであるedit_distanceについて説明します。組込関数は、script形式のgrn_expr中で呼び出すことができます。

edit_distance() 関数は、string1に指定した文字列とstring2に指定した文字列の間の編集距離を求めます。

  引数

string1 文字列を指定します

string2 もうひとつの文字列を指定します

  返値

指定した2つ文字列の編集距離をUint32型の値として返します。

  例

edit_distance(title, "hoge")
1

  geo_distance

  Summary

geo_distance calculates the value of distance between specified two points.

  Syntax

geo_distance requires two point. The parameter approximate_type is optional:

geo_distance(point1, point2)
geo_distance(point1, point2, approximate_type)

The default value of approximate_type is "rectangle". If you omit approximate_type, geo_distance calculates the value of distance as if "rectangle" was specified.

  Usage

geo_distance is one of the groonga builtin functions.

You can call a builtin function in /reference/grn_expr

geo_distance function calculates the value of distance (approximate value) between the coordinate of point1 and the coordinate of point2.

Note
    groonga provides three built in functions for calculating the value of distance. There are geo_distance(), geo_distance2() and geo_distance3(). The difference of them is the algorithm of calculating distance. geo_distance2() and geo_distance3() were deprecated since version 1.2.9. Use geo_distance(point1, point2, "sphere") instead of geo_distance2(point1, point2). Use geo_distance(point1, point2, "ellipsoid") instead of geo_distance3(point1, point2).

Lets's learn about geo_distance usage with examples. This section shows simple usages.

Here are two schema definition and sample data to show the difference according to the usage. Those samples show how to calculate the value of distance between New York City and London.

1.  Using the column value of location for calculating the distance (Cities table)

2.  Using the explicitly specified coordinates for calculating the distance (Geo table)

  Using the column value of location

Here are a schema definition of Cities table and sample data to show usage.

table_create Cities TABLE_HASH_KEY ShortText
column_create Cities location COLUMN_SCALAR WGS84GeoPoint
load --table Cities
[
  {
    "_key", "location"
  },
  {
    "New York City", "146566000x-266422000",
  },
]

Execution example:

table_create Cities TABLE_HASH_KEY ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Cities location COLUMN_SCALAR WGS84GeoPoint
# [[0, 1337566253.89858, 0.000355720520019531], true]
load --table Cities
[
  {
     "_key", "location"
  },
  {
     "New York City", "146566000x-266422000",
  },
]
# [[0, 1337566253.89858, 0.000355720520019531], 1]

This execution example creates a table named Cities which has one column named location. location column stores the value of coordinate. The coordinate of Tokyo is stored as sample data.

Execution example:

select Cities --output_columns _score --filter 1 --scorer '_score = geo_distance(location, "185428000x-461000", "rectangle")'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_score",
#           "Int32"
#         ]
#       ],
#       [
#         5715104
#       ]
#     ]
#   ]
# ]

This sample shows that geo_distance use the value of location column and the value of coordinate to calculate distance.

The value ("185428000x-461000") passed to geo_distance as the second argument is the coordinate of London.

  Using the explicitly specified value of location

Here are a schema definition of Geo table and sample data to show usage.

table_create Geo TABLE_HASH_KEY ShortText
column_create Geo distance COLUMN_SCALAR Int32
load --table Geo
[
  {
    "_key": "the record for geo_distance() result"
  }
]

Execution example:

table_create Geo TABLE_HASH_KEY ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Geo distance COLUMN_SCALAR Int32
# [[0, 1337566253.89858, 0.000355720520019531], true]
load --table Geo
[
  {
    "_key": "the record for geo_distance() result"
  }
]
# [[0, 1337566253.89858, 0.000355720520019531], 1]

This execution example creates a table named Geo which has one column named distance. distance column stores the value of distance.

Execution example:

select Geo --output_columns distance --scorer 'distance = geo_distance("146566000x-266422000", "185428000x-461000", "rectangle")'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "distance",
#           "Int32"
#         ]
#       ],
#       [
#         5807750
#       ]
#     ]
#   ]
# ]

This sample shows that geo_distance use the coordinate of London and the coordinate of New York to calculate distance.

  Parameters

  Required parameter

There are two required parameter, point1 and point2.

  point1

It specifies the start point that you want to calculate the value of distance between two points.

You can specify the value of GeoPoint type. [1]

See /reference/types about GeoPoint.

  point2

It specifies the end point that you want to calculate the value of distance between two points.

You can specify the value of GeoPoint type or the string indicating the coordinate.

See /reference/types about GeoPoint and the coordinate.

  Optional parameter

There is a optional parameter, approximate_type.

  approximate_type

It specifies how to approximate the geographical features for calculating the value of distance.

You can specify the value of approximate_type by one of the followings.

•   rectangle

•   sphere

•   ellipsoid

Note
    There is a limitation about geo_distance. geo_distance can not calculate the value of distance between two points across meridian, equator or the date line if you use sphere or ellipsoid as approximate type. There is not such a limitation for rectangle. This is temporary limitation according to the implementation of groonga, but it will be fixed in the future release.

  rectangle

This parameter require to approximate the geographical features by square approximation for calculating the distance.

Since the value of distance is calculated by simple formula, you can calculate the value of distance fast. But, the error of distance increases as it approaches the pole.

You can also specify rect as abbrev expression.

Here is a sample about calculating the value of distance with column value.

Execution example:

select Cities --output_columns _score --filter 1 --scorer '_score = geo_distance(location, "185428000x-461000", "rectangle")'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_score",
#           "Int32"
#         ]
#       ],
#       [
#         5715104
#       ]
#     ]
#   ]
# ]

Here is a sample about calculating the value of distance with explicitly specified point.

Execution example:

select Geo --output_columns distance --scorer 'distance = geo_distance("146566000x-266422000", "185428000x-461000", "rectangle")'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "distance",
#           "Int32"
#         ]
#       ],
#       [
#         5807750
#       ]
#     ]
#   ]
# ]

Here are samples about calculating the value of distance with explicitly specified point across meridian, equator, the date line.

Execution example:

select Geo --output_columns distance --scorer 'distance = geo_distance("175904000x8464000", "145508000x-13291000", "rectangle")'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "distance",
#           "Int32"
#         ]
#       ],
#       [
#         1051293
#       ]
#     ]
#   ]
# ]

This sample shows the value of distance across meridian. The return value of geo_distance("175904000x8464000", "145508000x-13291000", "rectangle") is the value of distance from Paris, Flance to Madrid, Spain.

Execution example:

select Geo --output_columns distance --scorer 'distance = geo_distance("146566000x-266422000", "-56880000x-172310000", "rectangle")'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "distance",
#           "Int32"
#         ]
#       ],
#       [
#         6880439
#       ]
#     ]
#   ]
# ]

This sample shows the value of distance across equator. The return value of geo_distance("146566000x-266422000", "-56880000x-172310000", "rectangle") is the value of distance from New York, The United Status to Brasillia, Brasil.

Execution example:

select Geo --output_columns distance --scorer 'distance = geo_distance("143660000x419009000", "135960000x-440760000", "rectangle")'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "distance",
#           "Int32"
#         ]
#       ],
#       [
#         10475205
#       ]
#     ]
#   ]
# ]

This sample shows the value of distance across the date line. The return value of geo_distance("143660000x419009000", "135960000x-440760000", "rectangle") is the value of distance from Beijin, China to San Francisco, The United States.

Note
    geo_distance uses square approximation as default. If you omit approximate_type, geo_distance behaves like rectangle was specified.

Note
    geo_distance accepts the string indicating the coordinate as the value of point1 when the value of approximate_type is "rectangle". If you specified the string indicating the coordinate as the value of point1 with sphere or ellipsoid, geo_distance returns 0 as the value of distance.

  sphere

This parameter require to approximate the geographical features by spherical approximation for calculating the distance.

It is slower than rectangle, but the error of distance becomes smaller than rectangle.

You can also specify sphr as abbrev expression.

Here is a sample about calculating the value of distance with column value.

Execution example:

select Cities --output_columns _score --filter 1 --scorer '_score = geo_distance(location, "185428000x-461000", "sphere")'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_score",
#           "Int32"
#         ]
#       ],
#       [
#         5715102
#       ]
#     ]
#   ]
# ]

  ellipsoid

This parameter require to approximate the geographical features by ellipsoid approximation for calculating the distance.

It uses the calculation of distance by the formula of Hubeny. It is slower than sphere, but the error of distance becomes smaller than sphere.

You can also specify ellip as abbrev expression.

Here is a sample about calculating the value of distance with column value.

Execution example:

select Cities --output_columns _score --filter 1 --scorer '_score = geo_distance(location, "185428000x-461000", "ellipsoid")'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_score",
#           "Int32"
#         ]
#       ],
#       [
#         5706263
#       ]
#     ]
#   ]
# ]

  Return value

geo_distance returns the value of distance in float type. The unit of return value is meter. Footnote

[1] You can specify whether TokyoGeoPoint or WGS84GeoPoint.

  geo_in_circle

  名前

geo_in_circle - 座標が円の範囲内に存在するかどうかを調べます。

  書式

geo_in_circle(point, center, radious_or_point[, approximate_type])

  説明

groonga組込関数の一つであるgeo_in_circleについて説明します。組込関数は、script形式のgrn_expr中で呼び出すことができます。

geo_in_circle() 関数は、pointに指定した座標が、centerに指定した座標を中心とする円の範囲内にあるかどうかを調べます。

  引数

point 円の範囲内に存在するかどうかを調べる座標を指定します。Point型の値を指定できます。 [1]

center 円の中心となる座標を指定します。Point型の値、あるいは座標を示す文字列を指定できます。

radious_or_point 円の半径を指定します。数値を指定した場合には、半径(単位:メートル)が指定されたものとみなします。 Point型の値、あるいは座標を示す文字列を指定した場合は、円周上の点の一つの座標が指定されたものとみなします。

approximate_type 半径からの距離を求めるために地形をどのように近似するかを指定します。指定できる値は以下の通りです。

"rectangle" 方形近似で近似します。単純な計算式で距離を求めることができるため高速ですが、極付近では誤差が大きくなります。

"rect" と省略して指定することもできます。

この近似方法がデフォルト値です。 approximate_type を省略した場合は方形近似になります。

"sphere" 球面近似で近似します。 "rectangle" よりも遅くなりますが、誤差は小さいです。

"sphr" と省略して指定することもできます。

"ellipsoid" 楕円体近似で近似します。距離の計算にはヒュベニの距離計算式を用います。 "sphere" よりも遅くなりますが、誤差は小さくなります。

"ellip" と省略して指定することもできます。

  返値

pointに指定した座標が円の範囲内にあるかどうかをBool型の値で返します。

  例

geo_in_circle(pos, "100x100", 100)
true
脚注

[1] TokyoGeoPoint(日本測地系座標)かWGS84GeoPoint(世界測地系座標)のいずれかを指定できます。

  geo_in_rectangle

  名前

geo_in_rectangle - 座標が矩形の範囲内に存在するかどうかを調べます。

  書式

geo_in_rectangle(point, top_left, bottom_right)

  説明

groonga組込関数の一つであるgeo_in_rectangleについて説明します。組込関数は、script形式のgrn_expr中で呼び出すことができます。

geo_in_rectangle() 関数は、pointに指定した座標が、top_leftとbottom_rightがなす矩形の範囲内にあるかどうかを調べます。

  引数

point 矩形の範囲内に存在するかどうかを調べる座標を指定します。Point型の値を指定できます。 [1]

top_left 矩形の左上隅となる座標を指定します。Point型の値、あるいは座標を示す文字列を指定できます。

bottom_right 矩形の右下隅となる座標を指定します。Point型の値、あるいは座標を示す文字列を指定できます。

  返値

pointに指定した座標が矩形の範囲内にあるかどうかをBool型の値で返します。

  例

geo_in_rectangle(pos, "150x100", "100x150")
true
脚注

[1] TokyoGeoPoint(日本測地系座標)かWGS84GeoPoint(世界測地系座標)のいずれかを指定できます。

  now

  名前

now - 現在時刻を返す

  書式

now()

  説明

groonga組込関数の一つであるnowについて説明します。組込関数は、script形式のgrn_expr中で呼び出すことができます。

now() 関数は現在時刻に対応するTime型の値を返します。

  返値

現在時刻に対応するTime型のオブジェクトを返します。

  例

now()
1256791194.55541

  query

  Summary

query enables you to specify --match_columns and --query parameters as function arguments.

query is one of the groonga builtin functions, so you can specify multiple query function as parameters of --filter option.

Because of such flexibility, you can control full text search behavior by combination of multiple query function.

query can be used in only --filter in /reference/commands/select.

  Syntax

query requires two arguments - match_column and query_string.

query(match_column, query_string)

  Usage

Here are a schema definition and sample data to show usage.

Sample schema:

Execution example:

table_create Documents TABLE_NO_KEY
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Documents content COLUMN_SCALAR Text
# [[0, 1337566253.89858, 0.000355720520019531], true]
table_create Terms TABLE_PAT_KEY|KEY_NORMALIZE ShortText --default_tokenizer TokenBigram
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Terms documents_content_index COLUMN_INDEX|WITH_POSITION Documents content
# [[0, 1337566253.89858, 0.000355720520019531], true]
table_create Users TABLE_NO_KEY
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Users name COLUMN_SCALAR ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Users memo COLUMN_SCALAR ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
table_create Lexicon TABLE_HASH_KEY ShortText \
  --default_tokenizer TokenBigramSplitSymbolAlphaDigit \
  --normalizer NormalizerAuto
column_create Lexicon users_name COLUMN_INDEX|WITH_POSITION Users name
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Lexicon users_memo COLUMN_INDEX|WITH_POSITION Users memo
# [[0, 1337566253.89858, 0.000355720520019531], true]

Sample data:

Execution example:

load --table Users
[
{"name": "Alice", "memo": "groonga user"},
{"name": "Alisa", "memo": "mroonga user"},
{"name": "Bob",   "memo": "rroonga user"},
{"name": "Tom",   "memo": "nroonga user"},
{"name": "Tobby", "memo": "groonga and mroonga user. mroonga is ..."},
]
# [[0, 1337566253.89858, 0.000355720520019531], true]
# [[0, 1337566253.89858, 0.000355720520019531], 5]

Here is the simple usage of query function which execute full text search by keyword 'alice' without using --match_column and --query arguments in --filter.

Execution example:

select Users --output_columns name,_score --filter 'query("name * 10", "alice")'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "name",
#           "ShortText"
#         ],
#         [
#           "_score",
#           "Int32"
#         ]
#       ],
#       [
#         "Alice",
#         10
#       ]
#     ]
#   ]
# ]

When executing above query, the keyword 'alice' is weighted to the value - '10'.

Here are the contrasting examples with/without query.

Execution example:

select Users --output_columns name,memo,_score --match_columns "memo * 10" --query "memo:@groonga OR memo:@mroonga OR memo:@user" --sortby -_score
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         5
#       ],
#       [
#         [
#           "name",
#           "ShortText"
#         ],
#         [
#           "memo",
#           "ShortText"
#         ],
#         [
#           "_score",
#           "Int32"
#         ]
#       ],
#       [
#         "Tobby",
#         "groonga and mroonga user. mroonga is ...",
#         4
#       ],
#       [
#         "Alice",
#         "groonga user",
#         2
#       ],
#       [
#         "Alisa",
#         "mroonga user",
#         2
#       ],
#       [
#         "Bob",
#         "rroonga user",
#         1
#       ],
#       [
#         "Tom",
#         "nroonga user",
#         1
#       ]
#     ]
#   ]
# ]

In this case, the keywords 'groonga' and 'mroonga' and 'user' are given same weight value. You can't pass different weight value to each keyword in this way.

Execution example:

select Users --output_columns name,memo,_score --filter 'query("memo * 10", "groonga") || query("memo * 20", "mroonga") || query("memo * 1", "user")' --sortby -_score
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         5
#       ],
#       [
#         [
#           "name",
#           "ShortText"
#         ],
#         [
#           "memo",
#           "ShortText"
#         ],
#         [
#           "_score",
#           "Int32"
#         ]
#       ],
#       [
#         "Tobby",
#         "groonga and mroonga user. mroonga is ...",
#         51
#       ],
#       [
#         "Alisa",
#         "mroonga user",
#         21
#       ],
#       [
#         "Alice",
#         "groonga user",
#         11
#       ],
#       [
#         "Tom",
#         "nroonga user",
#         1
#       ],
#       [
#         "Bob",
#         "rroonga user",
#         1
#       ]
#     ]
#   ]
# ]

On the other hand, by specifying multiple query, the keywords 'groonga' and 'mroonga' and 'user' are given different value of weight.

As a result, you can control full text search result by giving different weight to the keywords on your purpose.

  Parameters

There are two required parameter, match_column and query_string.

  match_column
It specifies match_column equivalent parameter.

See select-match-columns about match_column.

  query_string
It specifies query equivalent parameter.

See select-query about query string.

  Return value

query returns a value of boolean (true or false).

  TODO

•   Support query_expansion

•   Support query_flags

  See also

•   /reference/commands/select

  rand

  名前

rand - 乱数を生成する

  書式

rand([max])

  説明

groonga組込関数の一つであるrandについて説明します。組込関数は、script形式のgrn_expr中で呼び出すことができます。

rand() 関数は 0 から max の間の疑似乱数整数を返します。

  引数

max 返値の最大値を指定します。省略した場合は RAND_MAX が指定されたものとみなされます。

  返値

0 と max の間の数を表すInt32型の値を返します。

  例

rand(10)
3

  snippet_html

Caution
    This feature is experimental. API will be changed.

  Summary

snippet_html extracts snippets of target text around search keywords (KWIC. KeyWord In Context). The snippets are prepared for embedding HTML. Special characters such as < and > are escapsed as &lt; and &gt;. Keyword is surrounded with <span class="keyword"> and </span>. For example, a snippet of I am a groonga user. <3 for keyword groonga is I am a <span class="keyword">groonga</span> user. &lt;3.

  Syntax

snippet_html has only one parameter:

snippet_html(column)

snippet_html has many parameters internally but they can't be specified for now. You will be able to custom those parameters soon.

  Usage

Here are a schema definition and sample data to show usage.

Execution example:

table_create Documents TABLE_NO_KEY
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Documents content COLUMN_SCALAR Text
# [[0, 1337566253.89858, 0.000355720520019531], true]
table_create Terms TABLE_PAT_KEY|KEY_NORMALIZE ShortText --default_tokenizer TokenBigram
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Terms documents_content_index COLUMN_INDEX|WITH_POSITION Documents content
# [[0, 1337566253.89858, 0.000355720520019531], true]
load --table Documents
[
["content"],
["Groonga is a fast and accurate full text search engine based on inverted index. One of the characteristics of groonga is that a newly registered document instantly appears in search results. Also, groonga allows updates without read locks. These characteristics result in superior performance on real-time applications."],
["Groonga is also a column-oriented database management system (DBMS). Compared with well-known row-oriented systems, such as MySQL and PostgreSQL, column-oriented systems are more suited for aggregate queries. Due to this advantage, groonga can cover weakness of row-oriented systems."]
]
# [[0, 1337566253.89858, 0.000355720520019531], 2]

snippet_html can be used in only --output_columns in /reference/commands/select.

You need to specify --command_version 2 argument explicitly because function call in --output_columns is experimental feature in groonga 2.0.9. It will be enabled by default soon.

You also need to specify --query and/or --filter. Keywords are extracted from --query and --filter arguments.

The following example uses --query "fast performance". In this case, fast and performance are used as keywords.

Execution example:

select Documents --output_columns "snippet_html(content)" --command_version 2 --match_columns content --query "fast performance"
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "snippet_html",
#           "null"
#         ]
#       ],
#       [
#         [
#           "Groonga is a <span class=\"keyword\">fast</span> and accurate full text search engine based on inverted index. One of the characteristics of groonga is that a newly registered document instantly appears in search results. Also, gro",
#           "onga allows updates without read locks. These characteristics result in superior <span class=\"keyword\">performance</span> on real-time applications."
#         ]
#       ]
#     ]
#   ]
# ]

--query "fast performance" matches to only the first record's content. snippet_html(content) extracts two text parts that include the keywords fast or performance and surronds the keywords with <span class="keyword"> and </span>.

The max number of text parts is 3. If there are 4 or more text parts that include the keywords, only the leading 3 parts are only used.

The max size of a text part is 200byte. The unit is bytes not chracters. The size doesn't include inserted <span keyword="keyword"> and </span>.

Both the max number of text parts and the max size of a text part aren't customizable.

You can specify string literal instead of column.

Execution example:

select Documents --output_columns 'snippet_html("Groonga is very fast fulltext search engine.")' --command_version 2 --match_columns content --query "fast performance"
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "snippet_html",
#           "null"
#         ]
#       ],
#       [
#         [
#           "Groonga is very <span class=\"keyword\">fast</span> fulltext search engine."
#         ]
#       ]
#     ]
#   ]
# ]

  Return value

snippet_html returns an array of string. An element of array is a snippet:

[SNIPPET1, SNIPPET2, SNIPPET3]

A snippet includes one or more keywords. The max byte size of a snippet except <span keyword="keyword"> and </span> is 200byte. The unit isn't the number of chracters.

The array size is larger than or equal to 0 and less than or equal to 3. The max size 3 will be customizable soon.

  TODO

•   Make the max number of text parts customizable.

•   Make the max size of a text part customizable.

•   Make keywords customizable.

•   Make tag that surrounds a keyword customizable.

•   Make normalization customizable.

•   Support options by object literal.

  See also

•   /reference/commands/select

  Indexing

Groonga supports both online index construction and offline index construction since 2.0.0.

  Online index construction

In online index construction, registered documents can be searchable quickly while indexing. But indexing requires more cost rather than indexing by offline index construction.

Online index construction is suitable for a search system that values freshness. For example, a search system for tweets, news, blog posts and so on will value freshness. Online index construction can make fresh documents searchable and keep searchable while indexing.

  Offline index construction

In offline index construction, indexing cost is less than indexing cost by online index construction. Indexing time will be shorter. Index will be smaller. Resources required for indexing will be smaller. But a registering document cannot be searchable until all registered documents are indexed.

Offline index construction is suitable for a search system that values less required resources. If a search system doesn't value freshness, offline index construction will be suitable. For example, a reference manual search system doesn't value freshness because a reference manual will be updated only at a release.

  How to use

Groonga uses online index construction by default. We register a document, we can search it quickly.

Groonga uses offline index construction by adding an index to a column that already has data.

We define a schema:

Execution example:

table_create Tweets TABLE_NO_KEY
# [[0, 1337566253.89858, 0.000355720520019531], true]
column_create Tweets content COLUMN_SCALAR ShortText
# [[0, 1337566253.89858, 0.000355720520019531], true]
table_create Lexicon TABLE_HASH_KEY|KEY_NORMALIZE ShortText --default_tokenizer TokenBigram
# [[0, 1337566253.89858, 0.000355720520019531], true]

We register data:

Execution example:

load --table Tweets
[
{"content":"Hello!"},
{"content":"I just start it!"},
{"content":"I'm sleepy... Have a nice day... Good night..."}
]
# [[0, 1337566253.89858, 0.000355720520019531], 3]

We search without index. We get no result:

Execution example:

select Tweets --match_columns content --query 'good nice'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         0
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "content",
#           "ShortText"
#         ]
#       ]
#     ]
#   ]
# ]

We create index for Tweets.content. Already registered data in Tweets.content are indexed by offline index construction:

Execution example:

column_create Lexicon tweet COLUMN_INDEX|WITH_POSITION Tweets content
# [[0, 1337566253.89858, 0.000355720520019531], true]

We search with index. We get a matched record:

Execution example:

select Tweets --match_columns content --query 'good nice'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         1
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "content",
#           "ShortText"
#         ]
#       ],
#       [
#         3,
#         "I'm sleepy... Have a nice day... Good night..."
#       ]
#     ]
#   ]
# ]

We register data again. They are indexed by online index construction:

Execution example:

load --table Tweets
[
{"content":"Good morning! Nice day."},
{"content":"Let's go shopping."}
]
# [[0, 1337566253.89858, 0.000355720520019531], 2]

We can also get newly registered records by searching:

Execution example:

select Tweets --match_columns content --query 'good nice'
# [
#   [
#     0,
#     1337566253.89858,
#     0.000355720520019531
#   ],
#   [
#     [
#       [
#         2
#       ],
#       [
#         [
#           "_id",
#           "UInt32"
#         ],
#         [
#           "content",
#           "ShortText"
#         ]
#       ],
#       [
#         3,
#         "I'm sleepy... Have a nice day... Good night..."
#       ],
#       [
#         4,
#         "Good morning! Nice day."
#       ]
#     ]
#   ]
# ]

  Log

Groonga has two log files. They are process log and query log. Process log is for all of executables/groonga works. Query log is just for query processing.

  Process log

Process log is enabled by default. Log path can be customized by --log-path option. Each log has its log level. If a log is smaller than groonga process' log level, it's not logged. Log level can be customized by -l or commands/log_level.

  Format

Process log uses the following format:

#{TIME_STAMP}|#{L}| #{MESSAGE}

TIME_STAMP
    It's time stamp uses the following format:

    YYYY-MM-DD hh:mm:ss.SSSSSS

YYYY
    Year with four digits.

MM  Month with two digits.

DD  Day with two digits.

hh  Hour with two digits.

mm  Minute with two digits.

ss  Second with two digits.

SSSSSS
    Microsecond with six digits.

    Example:

    2011-07-05 06:25:18.345734

L   Log level with a character. Here is a character and log level map.

E   Emergency

A   Alert

C   Critical

e   Error

w   Warning

n   Notification

i   Information

d   Debug

-   Dump

    Example:

    E

MESSAGE
    Details about the log with free format.

    Example:

    log opened.

    Example:

    2011-07-05 08:35:09.276421|n| grn_init
    2011-07-05 08:35:09.276553|n| RLIMIT_NOFILE(4096,4096)

  Query log

Query log is disabled by default. It can be enabled by --query-log-path option.

  Format

Query log uses the following formats:

#{TIME_STAMP}|#{MESSAGE}
#{TIME_STAMP}|#{ID}|>#{QUERY}
#{TIME_STAMP}|#{ID}|:#{ELAPSED_TIME} #{PROGRESS}
#{TIME_STAMP}|#{ID}|<#{ELAPSED_TIME} #{RETURN_CODE}

TIME_STAMP
    It's time stamp uses the following format:

    YYYY-MM-DD hh:mm:ss.SSSSSS

YYYY
    Year with four digits.

MM  Month with two digits.

DD  Day with two digits.

hh  Hour with two digits.

mm  Minute with two digits.

ss  Second with two digits.

SSSSSS
    Microsecond with six digits.

    Example:

    2011-07-05 06:25:18.345734

ID  ID of a thread. Groonga process creates threads to process requests concurrently. Each thread outputs some logs for a request. This ID can be used to extract a log sequence by a thread.

    Example:

    45ea3034

>   A character that indicates query is started.

:   A character that indicates query is processing.

<   A character that indicates query is finished.

MESSAGE
    Details about the log with free format.

    Example:

    query log opened.

QUERY
    A query to be processed.

    Example:

    select users --match_columns hobby --query music

ELAPSED_TIME
    Elapsed time in nanoseconds since query is started.

    Example:

    000000000075770
    (It means 75,770 nanoseconds.)

PROGRESS
    A processed work at the time.

    Example:

    select(313401)
    (It means that 'select' is processed and 313,401 records are remained.)

RETURN_CODE
    A return code for the query.

    Example:

    rc=0
    (It means return code is 0. 0 means GRN_SUCCESS.)

    Example:

    2011-07-05 06:25:19.458756|45ea3034|>select Properties --limit 0
    2011-07-05 06:25:19.458829|45ea3034|:000000000072779 select(19)
    2011-07-05 06:25:19.458856|45ea3034|:000000000099998 output(0)
    2011-07-05 06:25:19.458875|45ea3034|<000000000119062 rc=0
    2011-07-05 06:25:19.458986|45ea3034|>quit

  API

TODO...

SPECIFICATION

  GQTP

GQTP is the acronym of Groonga Query Transfer Protocol. GQTP is the original protocol for groonga.

  Protocol

GQTP is stateful client server model protocol. The following sequence is one processing unit:

•   Client sends a request

•   Server receives the request

•   Server processes the request

•   Server sends a response

•   Client receives the response

    You can do zero or more processing units in a session.

    Both request and response consist of GQTP header and body. GQTP header is fixed size data. Body is variable size data and its size is stored in GQTP header. The content of body isn't defined in GQTP.

  GQTP header

GQTP header consists of the following unsigned integer values:
Name | Size | Description
protocol | 1byte | Protocol type.
query_type | 1byte | Content type of body.
key_length | 2byte | Not used.
level | 1byte | Not used.
flags | 1byte | Flags.
status | 2byte | Return code.
size | 4byte | Body size.
opaque | 4byte | Not used.
cas | 8byte | Not used.

All header values are encoded by network byte order.

The following sections describes available values of each header value.

The total size of GQTP header is 24byte.

  protocol

The value is always 0xc7 in both request and response GQTP header.

  query_type

The value is one of the following values:
Name | Value | Description
NONE | 0 | Free format.
TSV | 1 | Tab Separated Values.
JSON | 2 | JSON.
XML | 3 | XML.
MSGPACK | 4 | MessagePack.

This is not used in request GQTP header.

This is used in response GQTP header. Body is formatted as specified type.

  flags

The value is bitwise OR of the following values:
Name | Value | Description
MORE | 0x01 | There are more data.
TAIL | 0x02 | There are no more data.
HEAD | 0x04 | Not used.
QUIET | 0x08 | Be quiet.
QUIT | 0x10 | Quit.

You must specify MORE or TAIL flag.

If you use MORE flag, you should also use QUIET flag. Because you don't need to show a response for your partial request.

Use QUIT flag to quit this session.

  status

Here are available values. The new statuses will be added in the future.

•   0: SUCCESS

•   1: END_OF_DATA

•   65535: UNKNOWN_ERROR

•   65534: OPERATION_NOT_PERMITTED

•   65533: NO_SUCH_FILE_OR_DIRECTORY

•   65532: NO_SUCH_PROCESS

•   65531: INTERRUPTED_FUNCTION_CALL

•   65530: INPUT_OUTPUT_ERROR

•   65529: NO_SUCH_DEVICE_OR_ADDRESS

•   65528: ARG_LIST_TOO_LONG

•   65527: EXEC_FORMAT_ERROR

•   65526: BAD_FILE_DESCRIPTOR

•   65525: NO_CHILD_PROCESSES

•   65524: RESOURCE_TEMPORARILY_UNAVAILABLE

•   65523: NOT_ENOUGH_SPACE

•   65522: PERMISSION_DENIED

•   65521: BAD_ADDRESS

•   65520: RESOURCE_BUSY

•   65519: FILE_EXISTS

•   65518: IMPROPER_LINK

•   65517: NO_SUCH_DEVICE

•   65516: NOT_A_DIRECTORY

•   65515: IS_A_DIRECTORY

•   65514: INVALID_ARGUMENT

•   65513: TOO_MANY_OPEN_FILES_IN_SYSTEM

•   65512: TOO_MANY_OPEN_FILES

•   65511: INAPPROPRIATE_I_O_CONTROL_OPERATION

•   65510: FILE_TOO_LARGE

•   65509: NO_SPACE_LEFT_ON_DEVICE

•   65508: INVALID_SEEK

•   65507: READ_ONLY_FILE_SYSTEM

•   65506: TOO_MANY_LINKS

•   65505: BROKEN_PIPE

•   65504: DOMAIN_ERROR

•   65503: RESULT_TOO_LARGE

•   65502: RESOURCE_DEADLOCK_AVOIDED

•   65501: NO_MEMORY_AVAILABLE

•   65500: FILENAME_TOO_LONG

•   65499: NO_LOCKS_AVAILABLE

•   65498: FUNCTION_NOT_IMPLEMENTED

•   65497: DIRECTORY_NOT_EMPTY

•   65496: ILLEGAL_BYTE_SEQUENCE

•   65495: SOCKET_NOT_INITIALIZED

•   65494: OPERATION_WOULD_BLOCK

•   65493: ADDRESS_IS_NOT_AVAILABLE

•   65492: NETWORK_IS_DOWN

•   65491: NO_BUFFER

•   65490: SOCKET_IS_ALREADY_CONNECTED

•   65489: SOCKET_IS_NOT_CONNECTED

•   65488: SOCKET_IS_ALREADY_SHUTDOWNED

•   65487: OPERATION_TIMEOUT

•   65486: CONNECTION_REFUSED

•   65485: RANGE_ERROR

•   65484: TOKENIZER_ERROR

•   65483: FILE_CORRUPT

•   65482: INVALID_FORMAT

•   65481: OBJECT_CORRUPT

•   65480: TOO_MANY_SYMBOLIC_LINKS

•   65479: NOT_SOCKET

•   65478: OPERATION_NOT_SUPPORTED

•   65477: ADDRESS_IS_IN_USE

•   65476: ZLIB_ERROR

•   65475: LZO_ERROR

•   65474: STACK_OVER_FLOW

•   65473: SYNTAX_ERROR

•   65472: RETRY_MAX

•   65471: INCOMPATIBLE_FILE_FORMAT

•   65470: UPDATE_NOT_ALLOWED

•   65469: TOO_SMALL_OFFSET

•   65468: TOO_LARGE_OFFSET

•   65467: TOO_SMALL_LIMIT

•   65466: CAS_ERROR

•   65465: UNSUPPORTED_COMMAND_VERSION

  size

The size of body. The maximum body size is 4GiB because size is 4byte unsigned integer. If you want to send 4GiB or more larger data, use MORE flag.

  Example

TODO

  See also

TODO

  検索

/reference/commands/select コマンドがqueryパラメータを使ってどのように検索するのかを説明します。

  検索の挙動

検索の挙動には以下の3種類あり、検索結果によって動的に使い分けています。

1.  完全一致検索

2.  非わかち書き検索

3.  部分一致検索

    どのように検索の挙動を使い分けているかを説明する前に、まず、それぞれの検索の挙動を説明します。

  完全一致検索

検索対象文書は複数の語彙にトークナイズ(分割)され、それぞれを単位とした語彙表に索引を管理します。 検索キーワードも同一の方法でトークナイズされます。

このとき、検索キーワードをトークナイズした結果得られる語彙の配列と同一の配列を含む文書を検索する処理を完全一致検索と呼んでいます。

たとえば、TokenMecabトークナイザを使用した索引では「東京都民」という文字列は 東京 / 都民

という二つの語彙の配列として格納されます。この索引に対して「東京都」というキーワードで検索した時、このキーワードは、 東京 / 都

という二つの語彙の配列として処理されます。この語彙の並びは、「東京 / 都民」という語彙の並びには一致しませんので、完全一致検索ではヒットしません。

これに対して、TokenBigramトークナイザを使用した索引では「東京都民」という文字列は 東京 / 京都 / 都民 / 民

という四つの語彙の配列として格納されます。この索引に対して「東京都」というキーワードで検索した時、このキーワードは、 東京 / 京都

という二つの語彙の配列として処理されます。この語彙の並びは、「東京 / 京都 / 都民」という語彙の並びに含まれますので、完全一致検索でヒットします。

なお、TokenBigramトークナイザでは、アルファベット・数値・記号文字列についてはbigramを生成せず、一つの連続したトークンとして扱います。たとえば、「楽しいbilliard」という文字列は、 楽し / しい / billiard

という三つの語彙の配列として格納されます。これに対して「bill」というキーワードで検索した時、このキーワードは、 bill

という一つの語彙として処理されます。この語彙の並びは「楽し / しい / billiard」という語彙の並びには含まれないので、完全一致でヒットしません。

これに対して、TokenBigramSplitSymbolAlphaトークナイザではアルファベット文字列についてもbigramを生成し、「楽しいbilliard」という文字列は、 楽し / しい / いb / bi / il / ll / li / ia / ar / rd / d

という十一の語彙の配列として格納されます。これに対して「bill」というキーワードで検索した時、このキーワードは、 bi / il / ll

という三つの語彙として処理されます。この語彙の並びは「楽し / しい / いb / bi / il / ll / li / ia / ar / rd / d」という語彙の並びに含まれるので、完全一致でヒットします。

  非わかち書き検索

非わかち書き検索はパトリシア木で語彙表を構築している場合のみ利用可能です。

非わかち書き検索の挙動はTokenBigramなどN-gram系のトークナイザーを利用している場合とTokenMecabトークナイザーを利用している場合で挙動が変わります。

N-gram系のトークナイザーを利用している場合はキーワードで前方一致検索をします。

例えば、「bill」というキーワードで検索した場合、「bill」も「billiard」もヒットします。

TokenMeCabトークナイザーの場合はわかち書き前のキーワードで前方一致検索をします。

例えば、「スープカレー」というキーワードで検索した場合、「スープカレーバー」（1単語扱い）にヒットしますが、「スープカレー」（"スープ"と"カレー"の2単語扱い）や「スープカレーライス」（"スープ"と"カレーライス"の2単語扱い）にはヒットしません。

  部分一致検索

部分一致検索はパトリシア木で語彙表を構築していて、かつ、KEY_WITH_SISオプションを指定している場合のみ利用可能です。KEY_WITH_SISオプションが指定されていない場合は非わかち書き検索と同等です。

部分一致検索の挙動はTokenBigramなどN-gram系のトークナイザーを利用している場合とTokenMecabトークナイザーを利用している場合で挙動が変わります。

Bigramの場合は前方一致検索と中間一致検索と後方一致検索を行います。

例えば、「ill」というキーワードで検索した場合、「bill」も「billiard」もヒットします。

TokenMeCabトークナイザーの場合はわかち書き後のキーワードで前方一致検索と中間一致検索と後方一致検索をします。

例えば、「スープカレー」というキーワードで検索した場合、「スープカレー」（"スープ"と"カレー"の2単語扱い）や「スープカレーライス」（"スープ"と"カレーライス"の2単語扱い）、「スープカレーバー」（1単語扱い）にもヒットします。

  検索の使い分け

groongaは基本的に完全一致検索のみを行います。完全一致検索でのヒット件数が所定の閾値以下の場合に限り、非わかち書き検索を行い、それでもヒット件数が閾値以下の場合は部分一致検索を行います。（閾値のデフォルト値は0です。）

ただし、すでに検索結果セットが存在する場合はたとえヒット件数が閾値以下でも完全一致検索のみを行います。

例えば、以下のようなクエリの場合は、それぞれの検索でヒット件数が閾値以下の場合は完全一致検索、非わかち書き検索、部分一致検索を順に行います。:

select Shops --match_column description --query スープカレー

しかし、以下のように全文検索を行う前に検索結果セットが存在する場合は完全一致検索のみを行います。（point > 3で閾値の件数よりヒットしている場合）:

select Shops --filter '"point > 3 && description @ \"スープカレー\""'

そのため、descriptionに「スープカレーライス」が含まれていても、「スープカレーライス」は「スープカレー」に完全一致しないのでヒットしません。

LIMITATIONS

Groonga has some limitations.

  Limitations of table

A table has the following limitations.

•   The maximum one key size: 4096Bytes

•   The maximum total size of keys: 4GBytes

    Keep in mind that these limitations may vary depending on conditions.

  Limitations of indexing

A full-text index has the following limitations.

•   The maximum number of records: 268,435,455 (more than 268 million)

•   The maximum number of distinct terms: 268,435,455 (more than 268 million)

•   The maximum index size: 256GBytes

    Keep in mind that these limitations may vary depending on conditions.

トラブルシューティング

  同じ検索キーワードなのに全文検索結果が異なる

同じ検索キーワードでも一緒に指定するクエリによっては全文検索の結果が異なることがあります。ここでは、その原因と対策方法を説明します。

  例

まず、実際に検索結果が異なる例を説明します。

DDLは以下の通りです。BlogsテーブルのbodyカラムをTokenMecabトークナイザーを使ってトークナイズしてからインデックスを作成しています。:

table_create Blogs TABLE_NO_KEY
column_create Blogs body COLUMN_SCALAR ShortText
column_create Blogs updated_at COLUMN_SCALAR Time
table_create Terms TABLE_PAT_KEY|KEY_NORMALIZE ShortText --default_tokenizer TokenMecab
column_create Terms blog_body COLUMN_INDEX|WITH_POSITION Blogs body

テスト用のデータは1件だけ投入します。:

load --table Blogs
[
  ["body", "updated_at"],
  ["東京都民に深刻なダメージを与えました。", "2010/9/21 10:18:34"],
]

まず、全文検索のみで検索します。この場合ヒットします。:

> select Blogs --filter 'body @ "東京都"'
[[0,4102.268052438,0.000743783],[[[1],[["_id","UInt32"],["updated_at","Time"],["body","ShortText"]],[1,1285031914.0,"東京都民に深刻なダメージを与えました。"]]]]

続いて、範囲指定と全文検索を組み合わせて検索します（1285858800は2010/10/1 0:0:0の秒表記）。この場合もヒットします。:

> select Blogs --filter 'body @ "東京都" && updated_at < 1285858800'
[[0,4387.524084839,0.001525487],[[[1],[["_id","UInt32"],["updated_at","Time"],["body","ShortText"]],[1,1285031914.0,"東京都民に深刻なダメージを与えました。"]]]]

最後に、範囲指定と全文検索の順番を入れ替えて検索します。個々の条件は同じですが、この場合はヒットしません。:

> select Blogs --filter 'updated_at < 1285858800 && body @ "東京都"'
[[0,4400.292570838,0.000647716],[[[0],[["_id","UInt32"],["updated_at","Time"],["body","ShortText"]]]]]

どうしてこのような挙動になるかを説明します。

  原因

このような挙動になるのは全文検索時に複数の検索の挙動を使い分けているからです。ここでは簡単に説明するので、詳細は /spec/search を参照してください。

検索の挙動には以下の3種類があります。

1.  完全一致検索

2.  非わかち書き検索

3.  部分一致検索

    groongaは基本的に完全一致検索のみを行います。上記の例では「東京都民に深刻なダメージを与えました。」を「東京都」というクエリで検索していますが、TokenMecabトークナイザーを使っている場合はこのクエリはマッチしません。

    検索対象の「東京都民に深刻なダメージを与えました。」は 東京 / 都民 / に / 深刻 / な / ダメージ / を / 与え / まし / た / 。

    とトークナイズされますが、クエリの「東京都」は 東京 / 都

    とトークナイズされるため、完全一致しません。

    groongaは完全一致検索した結果のヒット件数が所定の閾値を超えない場合に限り、非わかち書き検索を行い、それでもヒット件数が閾値を超えない場合は部分一致検索を行います（閾値は1がデフォルト値となっています）。このケースのデータは部分一致検索ではヒットするので、「東京都」クエリのみを指定するとヒットします。

    しかし、以下のように全文検索前にすでに閾値が越えている場合（「updated_at < 1285858800」で1件ヒットし、閾値を越える）は、たとえ完全一致検索で1件もヒットしない場合でも部分一致検索などを行いません。:

    select Blogs --filter 'updated_at < 1285858800 && body @ "東京都"'

    そのため、条件の順序を変えると検索結果が変わるという状況が発生します。以下で、この情報を回避する方法を2種類紹介しますが、それぞれトレードオフとなる条件があるので採用するかどうかを十分検討してください。

  対策方法1: トークナイザーを変更する

TokenMecabトークナイザーは事前に準備した辞書を用いてトークナイズするため、再現率よりも適合率を重視したトークナイザーと言えます。一方、TokenBigramなど、N-gram系のトークナイザーは適合率を重視したトークナイザーと言えます。例えば、TokenMecabの場合「東京都」で「京都」に完全一致することはありませんが、TokenBigramでは完全一致します。一方、TokenMecabでは「東京都民」に完全一致しませんが、TokenBigramでは完全一致します。

このようにN-gram系のトークナイザーを指定することにより再現率をあげることができますが、適合率が下がり検索ノイズが含まれる可能性が高くなります。この度合いを調整するためには /reference/commands/select のmatch_columnsで使用する索引毎に重み付けを指定します。

ここでも、前述の例を使って具体例を示します。まず、TokenBigramを用いた索引を追加します。:

table_create Bigram TABLE_PAT_KEY|KEY_NORMALIZE ShortText --default_tokenizer TokenBigram
column_create Bigram blog_body COLUMN_INDEX|WITH_POSITION Blogs body

この状態でも以前はマッチしなかったレコードがヒットするようになります。:

> select Blogs --filter 'updated_at < 1285858800 && body @ "東京都"'
[[0,7163.448064902,0.000418127],[[[1],[["_id","UInt32"],["updated_at","Time"],["body","ShortText"]],[1,1285031914.0,"東京都民に深刻なダメージを与えました。"]]]]

しかし、N-gram系のトークナイザーの方がTokenMecabトークナイザーよりも語のヒット数が多いため、N-gram系のヒットスコアの方が重く扱われてしまいます。N-gram系のトークナイザーの方がTokenMecabトークナイザーよりも適合率の低い場合が多いので、このままでは検索ノイズが上位に表示される可能性が高くなります。

そこで、TokenMecabトークナイザーを使って作った索引の方をTokenBigramトークナイザーを使って作った索引よりも重視するように重み付けを指定します。これは、match_columnsオプションで指定できます。:

> select Blogs --match_columns 'Terms.blog_body * 10 || Bigram.blog_body * 3' --query '東京都' --output_columns '_score, body'
[[0,8167.364602632,0.000647003],[[[1],[["_score","Int32"],["body","ShortText"]],[13,"東京都民に深刻なダメージを与えました。"]]]]

この場合はスコアが11になっています。内訳は、Terms.blog_body索引（TokenMecabトークナイザーを使用）でマッチしたので10、Bigram.blog_body索引（TokenBigramトークナイザーを使用）でマッチしたので3、これらを合計して13になっています。このようにTokenMecabトークナイザーの重みを高くすることにより、検索ノイズが上位にくることを抑えつつ再現率を上げることができます。

この例は日本語だったのでTokenBigramトークナイザーでよかったのですが、アルファベットの場合はTokenBigramSplitSymbolAlphaトークナイザーなども利用する必要があります。例えば、「楽しいbilliard」はTokenBigramトークナイザーでは 楽し / しい / billiard

となり、「bill」では完全一致しません。一方、TokenBigramSplitSymbolAlphaトークナイザーを使うと 楽し / しい / いb / bi / il / ll / li / ia / ar / rd / d

となり、「bill」でも完全一致します。

TokenBigramSplitSymbolAlphaトークナイザーを使う場合も重み付けを考慮する必要があることはかわりありません。

利用できるバイグラム系のトークナイザーの一覧は以下の通りです。

•   TokenBigram: バイグラムでトークナイズする。連続する記号・アルファベット・数字は一語として扱う。

•   TokenBigramSplitSymbol: 記号もバイグラムでトークナイズする。連続するアルファベット・数字は一語として扱う。

•   TokenBigramSplitSymbolAlpha: 記号とアルファベットもバイグラムでトークナイズする。連続する数字は一語として扱う。

•   TokenBigramSplitSymbolAlphaDigit: 記号・アルファベット・数字もバイグラムでトークナイズする。

•   TokenBigramIgnoreBlank: バイグラムでトークナイズする。連続する記号・アルファベット・数字は一語として扱う。空白は無視する。

•   TokenBigramIgnoreBlankSplitSymbol: 記号もバイグラムでトークナイズする。連続するアルファベット・数字は一語として扱う。空白は無視する。

•   TokenBigramIgnoreBlankSplitSymbolAlpha: 記号とアルファベットもバイグラムでトークナイズする。連続する数字は一語として扱う。空白は無視する。

•   TokenBigramIgnoreBlankSplitSymbolAlphaDigit: 記号・アルファベット・数字もバイグラムでトークナイズする。空白は無視する。

  対策方法2: 閾値をあげる

非わかち書き検索・部分一致検索を利用するかどうかの閾値は--with-match-escalation-threshold configureオプションで変更することができます。以下のように指定すると、100件以下のヒット数であれば、たとえ完全一致検索でヒットしても、非わかち書き検索・部分一致検索を行います。:

% ./configure --with-match-escalation-threashold=100

この場合も対策方法1同様、検索ノイズが上位に現れる可能性が高くなることに注意してください。検索ノイズが多くなった場合は指定する値を低くする必要があります。

DEVELOPMENT

This section describes about developing with groonga. You may develop an application that uses groonga as its detabase, a library that uses libgroonga, language bindings of libgroonga and so on.

  Travis CI

This section describes about using groonga on Travis CI. Travis CI is a hosted continuous integration service for the open source community.

You can use Travis CI for your open source software. This section only describes about groonga related configuration. See Travis CI: Documentation about general Travis CI.

  Configuration

Travis CI is running on 32-bit Ubuntu 11.10. (See Travis CI: About Travis CI Environment.) You can use apt-line for Ubuntu 11.10 provided by groonga project to install groonga on Travis CI.

You can custom build lifecycle by .travis.yml. (See Travis CI: Conifugration your Travis CI build with .travis.yml.) You can use before_install hook or install hook. You should use before_install if your software uses a language that is supported by Travis CI such as Ruby. You should use install otherwise.

Add the following before_install configuration to .travis.yml:

before_install:
  - curl https://raw.github.com/groonga/groonga/master/data/travis/setup.sh | sh

If you need to use install hook instead of before_install, you just substitute before_install: with install:.

With the above configuration, you can use groonga for your build.

  Examples

Here are open source softwares that use groonga on Travis CI:

•   rroonga (Ruby bindings)

•   rroonga on Travis CI

•   .travis.yml for rroonga

•   nroonga (node.js bindings)

•   nroonga on Travis CI

•   .travis.yml for nroonga

•   logaling-command (A glossary management command line tool)

•   logaling-command on Travis CI

•   .travis.yml for logaling-command

HOW TO CONTRIBUTE TO GROONGA

We welcome your contributions to the groonga project. There are many ways to contribute, such as using groonga, introduction to others, etc. For example, if you find a bug when using groonga, you are welcome to report the bug. Coding and documentation are also welcome for groonga and its related projects.

As a user:
    If you are interested in groonga, please read this document and try it.

As a spokesman:
    Please introduce groonga to your friends and colleagues.

As a developer: Bug report, development and documentation
    This section describes the details.

  How to report a bug

There are two ways to report a bug:

•   Submit a bug to the issue tracker

•   Report a bug to the mailing list

    You can use either way It makes no difference to us.

  Submit a bug to the issue tracker

Groonga project has two issue tracking systems, Redmine and GitHub issue tracker. Redmine is for Japanese and GitHub issue tracker is for English. You can use one of them to report a bug.

  Report a bug to the mailing list

Groonga project has /community for discussing about groonga. Please send a mail that describes a bug.

  groonga開発者向け情報

  groonga 通信アーキテクチャ

  gqtpでのアーキテクチャ

•   comが外部からの接続を受け付ける。

•   comは1スレッド。

•   comがedgeを作る。

•   edgeは接続と１対１対応。

•   edgeはctxを含む。

•   workerはthreadと１対１対応。

•   workerは上限が個定数。

•   workerは、１つのedgeと結びつくことができる。

•   edgeごとにqueueを持つ。

•   msgはcomによって、edgeのqueueにenqueueされる。 edgeがworkerに結びついていないときは、同時に、ctx_newというqueueに、msgをenqueueした対象のedgeをenqueueする。

  ドキュメント作成

  Sphinxのインストール

groongaのドキュメントは、Sphinxというツールを用いて作成されています。Sphinxは以下のように導入します。:

# aptitude install python-setuptools
# easy_install -U sphinx

  htmlの作成

以下のコマンドでhtmlが作成されます。:

% make html

  pdfの作成

groongaのドキュメントは、pdf出力することもできます。rst2pdfと、IPAフォント(IPA Gothic/IPAexGothic)が必要となります。

  rst2pdfのインストール

以下のようにしてインストールできます。:

# easy_install rst2pdf

  pdfの作成

以下のコマンドでpdfが作成されます。:

% make pdf

  クエリの実現

groongaのデータベースには大量のデータを格納し、その中から必要な部分を高速に取り出すことができます。必要な部分をgroongaのデータベースに問い合わせるためのクエリの表現と実行に関して、groongaは複数の手段を用意しています。

  クエリ実行のためのインタフェース

groongaは低機能で単純なライブラリインタフェースから、高機能で複雑なコマンドインタフェースまでいくつかの階層的なインタフェースをユーザプログラムに提供しています。

クエリ実行のためのインタフェースも階層的なインタフェースのそれぞれに対応する形で用意されています。以下に低レイヤなインタフェースから順に説明します。

  DB_API

DB_APIは、groongaデータベースを操作するための一群のC言語向けAPI関数を提供します。DB_APIはデータベースを構成する個々の部分に対する単純な操作関数を提供します。DB_APIの機能を組み合わせることによって複雑なクエリを実行することができます。後述のすべてのクエリインタフェースはDB_APIの機能を組み合わせることによって実現されています。

  grn_expr

grn_exprは、groongaデータベースに対する検索処理や更新処理のための条件を表現するためのデータ構造で、複数の条件を再帰的に組み合わせてより複雑な条件を表現することができます。grn_exprによって表現されたクエリを実行するためには、grn_table_select()関数を使用します。

  groonga実行ファイル

groongaデータベースを操作するためのコマンドインタープリタです。渡されたコマンドを解釈し、実行結果を返します。コマンドの実処理はC言語で記述されます。ユーザがC言語で定義した関数を新たなコマンドとしてgroonga実行ファイルに組み込むことができます。各コマンドはいくつかの文字列引数を受け取り、これをクエリとして解釈して実行します。引数をgrn_exprとして解釈するか、別の形式として解釈してDB_APIを使ってデータベースを操作するかはコマンド毎に自由に決めることができます。

  grn_exprで表現できるクエリ

grn_exprは代入や関数呼び出しのような様々な操作を表現できますが、この中で検索クエリを表現するgrn_exprのことを特に条件式とよびます。条件式を構成する個々の要素を関係式と呼びます。条件式は一個以上の関係式か、あるいは条件式を論理演算子で結合したものです。

論理演算子は、以下の3種類があります。

&& (論理積)
|| (論理和)
!  (否定)

関係式は、下記の11種類が用意されています。また、ユーザが定義した関数を新たな関係式として使うこともできます。

equal(==)
not_equal(!=)
less(<)
greater(>)
less_equal(<=)
greater_equal(>=)
contain()
near()
similar()
prefix()
suffix()

  grn_table_select()

grn_table_select()関数は、grn_exprで表現された検索クエリを実行するときに使います。引数として、検索対象となるテーブル、クエリを表すgrn_expr、検索結果を格納するテーブル、それに検索にマッチしたレコードを検索結果にどのように反映するかを指定する演算子を渡します。演算子と指定できるのは下記の4種類です。

GRN_OP_OR
GRN_OP_AND
GRN_OP_BUT
GRN_OP_ADJUST

GRN_OP_ORは、検索対象テーブルの中からクエリにマッチするレコードを検索結果テーブルに加えます。GRN_OP_OR以外の演算子は、検索結果テーブルが空でない場合にだけ意味を持ちます。GRN_OP_ANDは、検索結果テーブルの中からクエリにマッチしないレコードを取り除きます。GRN_OP_BUTは、検索結果テーブルの中からクエリにマッチするレコードを取り除きます。GRN_OP_ADJUSTは、検索結果テーブルの中でクエリにマッチするレコードに対してスコア値の更新のみを行います。

grn_table_select()は、データベース上に定義されたテーブルや索引などを組み合わせて可能な限り高速に指定されたクエリを実行しようとします。

  関係式

関係式は、検索しようとしているデータが満たすべき条件を、指定した値の間の関係として表現します。いずれの関係式も、その関係が成り立ったときに評価されるcallback、コールバック関数に渡されるargとを引数として指定することができます。callbackが与えられず、argのみが数値で与えられた場合はスコア値の係数とみなされます。主な関係式について説明します。

  equal(v1, v2, arg, callback)

v1の値とv2の値が等しいことを表します。

  not_equal(v1, v2, arg, callback)

v1の値とv2の値が等しくないことを表します。

  less(v1, v2, arg, callback)

v1の値がv2の値よりも小さいことを表します。

  greater(v1, v2, arg, callback)

v1の値がv2の値よりも大きいことを表します。

  less_equal(v1, v2, arg, callback)

v1の値がv2の値と等しいか小さいことを表します。

  greater_equal(v1, v2, arg, callback)

v1の値がv2の値と等しいか大きいことを表します。

  contain(v1, v2, mode, arg, callback)

v1の値がv2の値を含んでいることを表します。また、v1の値が要素に分解されるとき、それぞれの要素に対して二つ目の要素が一致するためのmodeとして下記のいずれかを指定することができます。

EXACT: v2の値もv1の値と同様に要素に分解したとき、それぞれの要素が完全に一致する(デフォルト)
UNSPLIT: v2の値は要素に分解しない
PREFIX: v1の値の要素がv2の値に前方一致する
SUFFIX: v1の値の要素がv2の値に後方一致する
PARTIAL: v1の値の要素がv2の値に中間一致する

  near(v1, v2, arg, callback)

v1の値の中に、v2の値の要素が接近して含まれていることを表します。(v2には値の配列を渡します)

  similar(v1, v2, arg, callback)

v1の値とv2の値が類似していることを表します。

  prefix(v1, v2, arg, callback)

v1の値がv2の値に対して前方一致することを表します。

  suffix(v1, v2, arg, callback)

v1の値がv2の値に対して後方一致することを表します。

  クエリの実例

grn_exprを使って様々な検索クエリを表現することができます。

  検索例1

GRN_EXPR_CREATE_FOR_QUERY(ctx, table, query, var);
grn_expr_append_obj(ctx, query, contain, GRN_OP_PUSH, 1);
grn_expr_append_obj(ctx, query, column, GRN_OP_PUSH, 1);
grn_expr_append_const(ctx, query, string, GRN_OP_PUSH, 1);
grn_expr_append_op(ctx, query, GRN_OP_CALL, 3);
result = grn_table_select(ctx, table, query, NULL, GRN_OP_OR);

tableのcolumnの値がstringを含むレコードをresultに返します。columnの値が'needle in haystack'であるレコードr1と、columnの値が'haystack'であるレコードr2がtableに登録されていたとき、stringに'needle'を指定したなら、レコードr1のみがヒットします。

  検索例2

GRN_EXPR_CREATE_FOR_QUERY(ctx, table, query, var);
grn_expr_append_obj(ctx, query, contain, GRN_OP_PUSH, 1);
grn_expr_append_obj(ctx, query, column1, GRN_OP_PUSH, 1);
grn_expr_append_const(ctx, query, string, GRN_OP_PUSH, 1);
grn_expr_append_const(ctx, query, exact, GRN_OP_PUSH, 1);
grn_expr_append_const(ctx, query, score1, GRN_OP_PUSH, 1);
grn_expr_append_op(ctx, query, GRN_OP_CALL, 5);
result = grn_table_select(ctx, table, query, NULL, GRN_OP_OR);
grn_obj_close(ctx, query);
GRN_EXPR_CREATE_FOR_QUERY(ctx, table, query, var);
grn_expr_append_obj(ctx, query, contain, GRN_OP_PUSH, 1);
grn_expr_append_obj(ctx, query, column2, GRN_OP_PUSH, 1);
grn_expr_append_const(ctx, query, string, GRN_OP_PUSH, 1);
grn_expr_append_const(ctx, query, exact, GRN_OP_PUSH, 1);
grn_expr_append_const(ctx, query, score2, GRN_OP_PUSH, 1);
grn_expr_append_op(ctx, query, GRN_OP_CALL, 5);
grn_table_select(ctx, table, query, result, GRN_OP_ADJUST);
grn_obj_close(ctx, query);

tableのcolumn1の値がstringにexactモードでヒットするレコードについて得られるスコア値にscore1を積算してresultにセットします。次に、resultにセットされたレコードのうち、column2の値がstringにexactモードでヒットするレコードについては、得られたスコア値にscore2を積算したものを、元のスコア値に加えます。

  検索例3

GRN_EXPR_CREATE_FOR_QUERY(ctx, table, query, var);
grn_expr_append_obj(ctx, query, contain, GRN_OP_PUSH, 1);
grn_expr_append_obj(ctx, query, column1, GRN_OP_PUSH, 1);
grn_expr_append_const(ctx, query, string, GRN_OP_PUSH, 1);
grn_expr_append_const(ctx, query, exact, GRN_OP_PUSH, 1);
grn_expr_append_const(ctx, query, score1, GRN_OP_PUSH, 1);
grn_expr_append_op(ctx, query, GRN_OP_CALL, 5);
result = grn_table_select(ctx, table, query, NULL, GRN_OP_OR);
grn_obj_close(ctx, query);
if (grn_table_size(ctx, result) < t1) {
  GRN_EXPR_CREATE_FOR_QUERY(ctx, table, query, var);
  grn_expr_append_obj(ctx, query, contain, GRN_OP_PUSH, 1);
  grn_expr_append_obj(ctx, query, column1, GRN_OP_PUSH, 1);
  grn_expr_append_const(ctx, query, string, GRN_OP_PUSH, 1);
  grn_expr_append_const(ctx, query, partial, GRN_OP_PUSH, 1);
  grn_expr_append_const(ctx, query, score2, GRN_OP_PUSH, 1);
  grn_expr_append_op(ctx, query, GRN_OP_CALL, 3);
  grn_table_select(ctx, table, query, result, GRN_OP_OR);
  grn_obj_close(ctx, query);
}

tableのcolumn1の値がstringにexactモードでヒットするレコードについて得られるスコア値にscore1を積算してresultにセットします。得られた検索結果数がt1よりも小さい場合は、partialモードで再度検索し、ヒットしたレコードについて得られるスコア値にscore2を積算してresultに追加します。

  検索例4

GRN_EXPR_CREATE_FOR_QUERY(ctx, table, query, var);
grn_expr_append_obj(ctx, query, contain, GRN_OP_PUSH, 1);
grn_expr_append_const(ctx, query, string, GRN_OP_PUSH, 1);
grn_expr_append_obj(ctx, query, column, GRN_OP_PUSH, 1);
grn_expr_append_op(ctx, query, GRN_OP_CALL, 3);
result = grn_table_select(ctx, table, query, NULL, GRN_OP_OR);

tableのcolumnの値がstringに含まれるレコードをresultに返します。 columnの値が'needle'であるレコードr1と、columnの値が'haystack'であるレコードr2がtableに登録されていたとき、stringに'hay in haystack'を指定したなら、レコードr2のみがヒットします。

  リリース手順

  前提条件

リリース手順の前提条件は以下の通りです。

•   ビルド環境は Ubuntu 12.04 LTS(Precise Pangolin)

•   コマンドラインの実行例はzsh

    作業ディレクトリ例は以下を使用します。

•   GROONGA_DIR=$HOME/work/groonga

•   GROONGA_CLONE_DIR=$HOME/work/groonga/groonga.clean

•   GROONGA_GITHUB_COM_PATH=$HOME/work/groonga/groonga.github.com

•   CUTTER_DIR=$HOME/work/cutter

•   CUTTER_SOURCE_PATH=$HOME/work/cutter/cutter

  ビルド環境の準備

以下にgroongaのリリース作業を行うために事前にインストール しておくべきパッケージを示します。

なお、ビルド環境としては Ubuntu 12.04 LTS(Precise Pangolin)を前提として説明しているため、その他の環境では適宜読み替えて下さい。:

% sudo apt-get install -V debootstrap rinse createrepo rpm
mercurial python-docutils python-jinja2 ruby1.9.1-full mingw-w64 g++-mingw-w64 mecab libmecab-dev nsis gnupg2

rinseのバージョンが古いとCentOS 5/6パッケージのビルドを行うことができません。 別途debパッケージを以下のコマンドを実行して最新版をインストールします。:

% sudo dpkg -i rinse_1.9.2-1_all.deb

また、rubyのrakeパッケージを以下のコマンドによりインストールします。:

% sudo gem1.9.1 install rake

  パッケージ署名用秘密鍵のインポート

リリース作業ではRPMパッケージに対する署名を行います。 その際、パッケージ署名用の鍵が必要です。

groongaプロジェクトでは署名用の鍵をリリース担当者の公開鍵で暗号化してリポジトリのpackages/ディレクトリ以下へと登録しています。

リリース担当者はリポジトリに登録された秘密鍵を復号した後に鍵のインポートを以下のコマンドにて行います。:

% cd packages
% gpg --decrypt release-key-secret.asc.gpg.(担当者) > (復号した鍵
ファイル)
% gpg --import  (復号した鍵ファイル)

鍵のインポートが正常終了すると gpg --list-keys でgroongaの署名用の鍵を確認することができます。:

pub   1024R/F10399C0 2012-04-24
uid                  groonga Key (groonga Official Signing Key)
<packages@groonga.org>
sub   1024R/BC009774 2012-04-24

鍵をインポートしただけでは使用することができないため、インポートした鍵に対してtrust,signを行う必要があります。

以下のコマンドを実行して署名を行います。(途中の選択肢は省略):

% gpg --edit-key packages@groonga.org
gpg> trust
gpg> sign
gpg> save
gpg> quit

この作業は、新規にリリースを行うことになった担当者やパッケージに署名する鍵に変更があった場合などに行います。

  リリース作業用ディレクトリの作成

groongaのリリース作業ではリリース専用の環境下(コンパイルフラグ)でビルドする必要があります。

リリース時と開発時でディレクトリを分けずに作業することもできますが、誤ったコンパイルフラグでリリースしてしまう危険があります。

そのため、以降の説明では$GROONGA_DIR以下のディレクトリにリリース用の作業ディレクトリ(groonga.clean)としてソースコードをcloneしたものとして説明します。

リリース用のクリーンな状態でソースコードを取得するために$GROONGA_DIRにて以下のコマンドを実行します。:

% git clone git@github.com:groonga/groonga.git groonga.clean

この作業はリリース作業ごとに行います。

  変更点のまとめ

前回リリース時からの変更点を$GROONGA_CLONE_DIR/doc/source/news.txtにまとめます。 ここでまとめた内容についてはリリースアナウンスにも使用します。

前回リリースからの変更履歴を参照するには以下のコマンドを実行します。:

% git log -p --reverse $(git tag | tail -1)..

ログを^commitで検索しながら、以下の基準を目安として変更点を追記していきます。

含めるもの

•   ユーザへ影響するような変更

•   互換性がなくなるような変更

    含めないもの

•   内部的な変更(変数名の変更やらリファクタリング)

  groongaのウェブサイトの取得

groongaのウェブサイトのソースはgroonga同様にgithubにリポジトリを置いています。

リリース作業では後述するコマンド(make update-latest-release)にてトップページのバージョンを置き換えることができるようになっています。

groongaのウェブサイトのソースコードを$GROONGA_GITHUB_COM_PATHとして取得するためには、$GROONGA_DIRにて以下のコマンドを実行します。:

% git clone git@github.com:groonga/groonga.github.com.git

これで、$GROONGA_GITHUB_COM_PATHにgroonga.github.comのソースを取得できます。

  cutterのソースコード取得

groongaのリリース作業では、cutterに含まれるスクリプトを使用しています。

そこであらかじめ用意しておいた$HOME/work/cutterディレクトリにてcutterのソースコードを以下のコマンドにて取得します。:

% git clone git@github.com:clear-code/cutter.git

これで、$CUTTER_SOURCE_PATHディレクトリにcutterのソースを取得できます。

  configureスクリプトの生成

groongaのソースコードをcloneした時点ではconfigureスクリプトが含まれておらず、そのままmakeコマンドにてビルドすることができません。

$GROONGA_CLONE_DIRにてautogen.shを以下のように実行します。:

% sh autogen.sh

このコマンドの実行により、configureスクリプトが生成されます。

  configureスクリプトの実行

Makefileを生成するためにconfigureスクリプトを実行します。

リリース用にビルドするためには以下のオプションを指定してconfigureを実行します。:

% ./configure CFLAGS="-O0 -ggdb3" CXXFLAGS="-O0 -ggdb3" --prefix=/tmp/local --with-rsync-path="packages@packages.groonga.org:public" --with-groonga-github-com-path=$HOME/work/groonga/groonga.github.com --enable-document --with-ruby19 --with-cutter-source-path=$HOME/work/cutter/cutter

configureオプションである--with-groonga-github-com-pathにはgroongaのウェブサイトのリポジトリをcloneした場所を指定します。

configureオプションである--with-cutter-source-pathにはcutterのソースをcloneした場所を指定します。

以下のようにgroongaのソースコードをcloneした先からの相対パスを指定することもできます。:

% ./configure CFLAGS="-O0 -ggdb3" CXXFLAGS="-O0 -ggdb3" --prefix=/tmp/local --with-rsync-path="packages@packages.groonga.org:public" --with-groonga-github-com-path=../groonga.github.com --enable-document --with-ruby19 --with-cutter-source-path=../../cutter/cutter

あらかじめpackagesユーザでpackages.groonga.orgにsshログインできることを確認しておいてください。

ログイン可能であるかの確認は以下のようにコマンドを実行して行います。:

% ssh packages@packages.groonga.org

  make update-latest-releaseの実行

make update-latest-releaseコマンドでは、OLD_RELEASE_DATEに前回のリリースの日付を、NEW_RELEASE_DATEに次回リリースの日付を指定します。

2.0.2のリリースを行った際は以下のコマンドを実行しました。::

% make update-latest-release OLD_RELEASE=2.0.1 OLD_RELEASE_DATE=2012-03-29 NEW_RELEASE_DATE=2012-04-29

これにより、clone済みのgroongaのWebサイトのトップページのソース(index.html,ja/index.html)やRPMパッケージのspecファイルのバージョン表記などが更新されます。

  make update-filesの実行

ロケールメッセージの更新や変更されたファイルのリスト等を更新するために以下のコマンドを実行します。:

% make update-files

make update-filesを実行すると新規に追加されたファイルなどが各種.amファイルへとリストアップされます。

リリースに必要なファイルですので漏れなくコミットします。

  make update-poの実行

ドキュメントの最新版と各国語版の内容を同期するために、poファイルの更新を以下のコマンドにて実行します。:

% make update-po

make update-poを実行すると、doc/locale/ja/LC_MESSAGES以下の各種.poファイルが更新されます。

  poファイルの翻訳

make update-poコマンドの実行により更新した各種.poファイルを翻訳します。

翻訳結果をHTMLで確認するために、以下のコマンドを実行します。:

% make -C doc/locale/ja html
% make -C doc/locale/en html

確認が完了したら、翻訳済みpoファイルをコミットします。

  リリースタグの設定

リリース用のタグを打つには以下のコマンドを実行します。:

% make tag

  リリース用アーカイブファイルの作成

リリース用のソースアーカイブファイルを作成するために以下のコマンドを$GROONGA_CLONE_DIRにて実行します。:

% make dist

これにより$GROONGA_CLONE_DIR/groonga-(バージョン).tar.gzが作成されます。

Note
    タグを打つ前にmake distを行うとversionが古いままになることがあります。 するとgroonga --versionで表示されるバージョン表記が更新されないので注意が必要です。 make distで生成したtar.gzのversionおよびversion.shがタグと一致することを確認するのが望ましいです。

  パッケージのビルド

リリース用のアーカイブファイルができたので、パッケージ化する作業を行います。

パッケージ化作業は以下の3種類を対象に行います。

•   Debian系(.deb)

•   Red Hat系(.rpm)

•   Windows系(.exe,.zip)

    パッケージのビルドではいくつかのサブタスクから構成されています。

  ビルド用パッケージのダウンロード

debパッケージのビルドに必要なパッケージをダウンロードするには以下のコマンドを実行します。:

% cd packages/apt
% make download

これにより、lucid以降の関連する.debパッケージやソースアーカイブなどがカレントディレクトリ以下へとダウンロードされます。

rpmパッケージのビルドに必要なパッケージをダウンロードするには以下のコマンドを実行します。:

% cd packages/yum
% make download

これにより、groongaやMySQLのRPM/SRPMパッケージなどがカレントディレクトリ以下へとダウンロードされます。

windowsパッケージのビルドに必要なパッケージをダウンロードするには以下のコマンドを実行します。:

% cd packages/windows
% make download

これにより、groongaのインストーラやzipアーカイブがカレントディレクトリ以下へとダウンロードされます。

sourceパッケージに必要なものをダウンロードするには以下のコマンドを実行します。:

% cd packages/source
% make download

これにより過去にリリースしたソースアーカイブ(.tar.gz)が packages/source/filesディレクトリ以下へとダウンロードされます。

  Debian系パッケージのビルド

groongaのpackages/aptサブディレクトリに移動して、以下のコマンドを実行します。:

% cd packages/apt
% make build PALALLEL=yes

make build PALALLEL=yesコマンドを実行すると、ディストリビューションのリリースとアーキテクチャの組み合わせでビルドを平行して行うことができます。

現在サポートされているのは以下の通りです。

•   squeeze i386/amd64

•   wheezy i386/amd64

•   unstable i386/amd64

•   lucid i386/amd64

•   natty i386/amd64

•   oneiric i386/amd64

•   precise i386/amd64

•   quantal i386/amd64

    正常にビルドが終了すると$GROONGA_CLONE_DIR/packages/apt/repositories配下に.debパッケージが生成されます。

    make build ではまとめてビルドできないこともあります。 その場合にはディストリビューションごとやアーキテクチャごとなど、個別にビルドすることで問題が発生している箇所を切り分ける必要があります。

    生成したパッケージへの署名を行うには以下のコマンドを実行します。:

    % make sign-packages

    リリース対象のファイルをリポジトリに反映するには以下のコマンドを実行します。:

    % make update-repository

    リポジトリにGnuPGで署名を行うために以下のコマンドを実行します。:

    % make sign-repository

  Red Hat系パッケージのビルド

groongaのpackages/yumサブディレクトリに移動して、以下のコマンドを実行します。:

% cd packages/yum
% make build PALALLES=yes

make build PALALLEL=yesコマンドを実行すると、ディストリビューションのリリースとアーキテクチャの組み合わせでビルドを平行して行うことができます。

現在サポートされているのは以下の通りです。

•   centos-5 i386/x86_64

•   centos-6 i386/x86_64

•   fedora-17 i386/x86_64

    ビルドが正常終了すると$GROONGA_CLONE_DIR/packages/yum/repositories配下にRPMパッケージが生成されます。

•   repositories/yum/centos/5/i386/Packages

•   repositories/yum/centos/5/x86_64/Packages

•   repositories/yum/centos/6/i386/Packages

•   repositories/yum/centos/6/x86_64/Packages

•   repositories/yum/fedora/17/i386/Packages

•   repositories/yum/fedora/17/x86_64/Packages

    リリース対象のRPMに署名を行うには以下のコマンドを実行します。:

    % make sign-packages

    リリース対象のファイルをリポジトリに反映するには以下のコマンドを実行します。:

    % make update-repository

  Windows用パッケージのビルド

packages/windowsサブディレクトリに移動して、以下のコマンドを実行します。:

% cd packages/windows
% make build
% make package
% make installer

make releaseを実行することでbuildからuploadまで一気に実行することができますが、途中で失敗することもあるので順に実行することをおすすめします。

make buildでクロスコンパイルを行います。 正常に終了するとdist-x64/dist-x86ディレクトリ以下にx64/x86バイナリを作成します。

make packageが正常に終了するとzipアーカイブをfilesディレクトリ以下に作成します。

make installerが正常に終了するとWindowsインストーラをfilesディレクトリ以下に作成します。

  パッケージの動作確認

ビルドしたパッケージに対しリリース前の動作確認を行います。

Debian系もしくはRed Hat系の場合には本番環境へとアップロードする前にローカルのaptないしyumのリポジトリを参照して正常に更新できることを確認します。

ここでは以下のようにrubyを利用してリポジトリをwebサーバ経由で参照できるようにします。:

% ruby1.9.1 -run -e httpd -- packages/yum/repositories (yumの場合)
% ruby1.9.1 -run -e httpd -- packages/apt/repositories (aptの場合)

  grntestの準備

grntestを実行するためにはgroongaのテストデータとgrntestのソースが必要です。

まずgroongaのソースを任意のディレクトリへと展開します。:

% tar zxvf groonga-(バージョン).tar.gz

次にgroongaのtest/functionディレクトリ以下にgrntestのソースを展開します。 つまりtest/function/grntestという名前でgrntestのソースを配置します。:

% ls test/function/grntest/
README.md  binlib  license  test

  grntestの実行方法

grntestではgroongaコマンドを明示的にしていすることができます。 後述のパッケージごとのgrntestによる動作確認では以下のようにして実行します。:

% GROONGA=(groongaのパス指定) test/function/run-test.sh

最後にgrntestによる実行結果が以下のようにまとめて表示されます。:

55 tests, 52 passes, 0 failures, 3 not checked tests.
94.55% passed.

grntestでエラーが発生しないことを確認します。

  Debian系の場合

Debian系の場合の動作確認手順は以下の通りとなります。

•   旧バージョンをchroot環境へとインストールする

•   chroot環境の/etc/hostsを書き換えてpackages.groonga.orgがホストを 参照するように変更する

•   ホストでwebサーバを起動してドキュメントルートをビルド環境のもの (repositories/apt/packages)に設定する

•   アップグレード手順を実行する

•   grntestのアーカイブを展開してインストールしたバージョンでテストを実 行する

•   grntestの正常終了を確認する

  Red Hat系の場合

Red Hat系の場合の動作確認手順は以下の通りとなります。

•   旧バージョンをchroot環境へとインストール

•   chroot環境の/etc/hostsを書き換えてpackages.groonga.orgがホストを参照するように変更する

•   ホストでwebサーバを起動してドキュメントルートをビルド環境のもの(packages/yum/repositories)に設定する

•   アップグレード手順を実行する

•   grntestのアーカイブを展開してインストールしたバージョンでテストを実行する

•   grntestの正常終了を確認する

  Windows向けの場合

•   新規インストール/上書きインストールを行う

•   grntestのアーカイブを展開してインストールしたバージョンでテストを実行する

•   grntestの正常終了を確認する

    zipアーカイブも同様にしてgrntestを実行し動作確認を行います。

  リリースアナウンスの作成

リリースの際にはリリースアナウンスを流して、groongaを広く通知します。

news.txtに変更点をまとめましたが、それを元にリリースアナウンスを作成します。

リリースアナウンスには以下を含めます。

•   インストール方法へのリンク

•   リリースのトピック紹介

•   リリース変更点へのリンク

•   リリース変更点(news.txtの内容)

    リリースのトピック紹介では、これからgroongaを使う人へアピールする点や既存のバージョンを利用している人がアップグレードする際に必要な情報を提供します。

    非互換な変更が含まれるのであれば、回避方法等の案内を載せることも重要です。

    参考までに過去のリリースアナウンスへのリンクを以下に示します。

•   [Groonga-talk] [ANN] groonga 2.0.2

•   http://sourceforge.net/mailarchive/message.php?msg_id=29195195

•   [groonga-dev,00794] [ANN] groonga 2.0.2

•   http://sourceforge.jp/projects/groonga/lists/archive/dev/2012-April/000794.html

  パッケージのアップロード

動作確認が完了し、Debian系、Red Hat系、Windows向け、ソースコードそれぞれにおいてパッケージやアーカイブのアップロードを行います。

Debian系のパッケージのアップロードには以下のコマンドを実行します。:

% cd packages/apt
% make upload

Red Hat系のパッケージのアップロードには以下のコマンドを実行します。:

% cd packages/yum
% make upload

Windows向けのパッケージのアップロードには以下のコマンドを実行します。:

% cd packages/windows
% make upload

ソースアーカイブのアップロードには以下のコマンドを実行します。:

% cd packages/source
% make upload

アップロードが正常終了すると、リリース対象のリポジトリデータやパッケージ、アーカイブ等がpackages.groonga.orgへと反映されます。

  blogroonga(ブログ)の更新

http://groonga.org/blog/ および http://groonga.org/blog/ にて公開されているリリース案内を作成します。

基本的にはリリースアナウンスの内容をそのまま記載します。

cloneしたWebサイトのソースに対して以下のファイルを新規追加します。

•   groonga.github.com/en/_post/(リリース日)-release.textile

•   groonga.github.com/ja/_post/(リリース日)-release.textile

    編集した内容をpushする前に確認したい場合にはjekyllおよびRedClothが必要です。 インストールするには以下のコマンドを実行します。:

    % sudo gem1.9.1 install jekyll RedCloth

    jekyllのインストールを行ったら、以下のコマンドでローカルにwebサーバを起動します。:

    % jekyll --server --auto

    あとはブラウザにてhttp://localhost:4000にアクセスして内容に問題がないかを確認します。

Note
    記事を非公開の状態でアップロードするには.textileファイルのpublished:をfalseに設定します。:

    ---
    layout: post.en
    title: Groonga 2.0.5 has been released
    published: false
    ---

  ドキュメントのアップロード

doc/source以下のドキュメントを更新、翻訳まで完了している状態で、ドキュメントのアップロード作業を行います。

そのためにはまず以下のコマンドを実行します。:

% make update-document

これによりcloneしておいたgroonga.github.comのdoc/locale以下に更新したドキュメントがコピーされます。

生成されているドキュメントに問題のないことを確認できたら、コミット、pushしてgroonga.orgへと反映します。

  リリースアナウンス

作成したリリースアナウンスをメーリングリストへと流します。

•   groonga-dev groonga-dev@lists.sourceforge.jp

•   Groonga-talk groonga-talk@lists.sourceforge.net

  freecode.comへリリース情報を登録

groongaプロジェクトではfreecode.comでもリリース情報を発信しています。

freecode.comのプロジェクトページは以下の通りです。 https://freecode.com/projects/groonga

プロジェクトの管理メニューから「Submit a release」をクリックし、 新規リリース情報を登録します。 https://freecode.com/projects/groonga/releases/new

Note
    投稿した内容に対するレビューが運営側で実施されるので、反映されるまでしばらく時間がかかります。

  Twitterでリリースアナウンスをする

blogroongaのリリースエントリには「リンクをあなたのフォロワーに共有する」ためのツイートボタンがあるので、そのボタンを使ってリリースアナウンスします。(画面下部に配置されている)

このボタンを経由する場合、ツイート内容に自動的にリリースタイトル(「groonga 2.0.8リリース」など)とblogroongaのリリースエントリのURLが挿入されます。

この作業はblogroongaの英語版、日本語版それぞれで行います。 あらかじめgroongaアカウントでログインしておくとアナウンスを円滑に行うことができます。

以上でリリース作業は終了です。

  リリース後にやること

リリースアナウンスを流し終えたら、次期バージョンの開発が始まります。

•   groonga プロジェクトの新規バージョン追加

•   groonga のbase_versionの更新

  groonga プロジェクトの新規バージョン追加

groonga プロジェクトの設定ページ にて新規バージョンを追加します。(例: release-2.0.6)

  groonga バージョン更新

$GROONGA_CLONE_DIRにて以下のコマンドを実行します。:

% make update-version NEW_VERSION=2.0.6

これにより$GROONGA_CLONE_DIR/base_versionが更新されるのでコミットしておきます。

Note
    base_versionはtar.gzなどのリリース用のファイル名で使用します。

  ビルド時のTIPS

  ビルドを並列化したい

make build PALALLES=yesを指定するとchroot環境で並列にビルドを 実行できます。

  特定の環境向けのみビルドしたい

Debian系の場合、CODES,ARCHITECTURESオプションを明示的に指定することで、特定のリリース、アーキテクチャのみビルドすることができます。

squeezeのi386のみビルドしたい場合には以下のコマンドを実行します。:

% make build ARCHITECTURES=i386 CODES=squeeze

buildコマンド以外でも build-package-deb build-repository-debなどのサブタスクでもARCHITECTURES,CODES指定は有効です。

Red Hat系の場合、ARCHITECTURES,DISTRIBUTIONSオプションを明示的に指定することで、特定のリリース、アーキテクチャのみビルドすることができます。

fedoraのi386のみビルドしたい場合には以下のコマンドを実行します。:

% make build ARCHITECTURES=i386 DISTRIBUTIONS=fedora

buildコマンド以外でも build-in-chroot build-repository-rpmなどのサブタスクでもARCHITECTURES,DISTRIBUTIONSの指定は有効です。

centosの場合、CENTOS_VERSIONSを指定することで特定のバージョンのみビルドすることができます。

  パッケージの署名用のパスフレーズを知りたい

パッケージの署名に必要な秘密鍵のパスフレーズについては リリース担当者向けの秘密鍵を復号したテキストの1行目に記載してあります。

  テスト方法

  テスト環境の構築

  Cutterのインストール

groongaは、テストのフレームワークとして Cutter を用いています。

Cutterのインストール方法は プラットフォーム毎のCutterのインストール方法 をご覧下さい。

  lcovのインストール

カバレッジ情報を計測するためには、lcov 1.6以上が必要です。DebianやUbuntuでは以下のようにしてインストールできます。:

% sudo aptitude install -y lcov

  clangのインストール

ソースコードの静的解析を行うためには、clang(scan-build)をインストールする必要があります。DebianやUbuntuでは以下のようにしてインストールできます。:

% sudo aptitude install -y clang

  libmemcachedのインストール

memcachedのバイナリプロトコルのテストを動作させるためには、libmemcachedの導入が必要です。squeeze以降のDebianやKarmic以降のUubntuでは以下の用にしてインストールできます。:

% sudo aptitude install -y libmemcached-dev

  テストの動作

groongaのトップディレクトリで、以下のコマンドを実行します。:

make check

  カバレッジ情報

groongaのトップディレクトリで、以下のコマンドを実行します。:

make coverage

すると、coverageディレクトリ以下に、カバレッジ情報が入ったhtmlが出力されます。

カバレッジには、Lines/Functions/Branchesの3つの対象があります。それぞれ、行／関数／分岐に対応します。Functionsがもっとも重要な対象です。すべての関数がテストされるようになっていることを心がけてください。

テストがカバーしていない部分の編集は慎重に行ってください。また、テストがカバーしている部分を増やすことも重要です。

  様々なテスト

テストは、test/unitディレクトリにおいて、./run-test.shを実行することによっても行えます。run-test.shはいくつかのオプションをとります。詳細は、./run-test.sh --helpを実行しヘルプをご覧ください。

  特定のテスト関数のみテストする

特定のテスト関数(Cutterではテストと呼ぶ)のみをテストすることができます。

実行例:

% ./run-test.sh -n test_text_otoj

  特定のテストファイルのみテストする

特定のテストファイル(Cutterではテストケースと呼ぶ)のみテストすることができます。

実行例:

% ./run-test.sh -t test_string

  不正メモリアクセス・メモリリーク検出

環境変数CUTTER_CHECK_LEAKをyesと設定すると、valgrindを用いて不正メモリアクセスやメモリリークを検出しつつ、テストを動作させることができます。

run-test.shのみならず、make checkでも利用可能です。

実行例:

% CUTTER_CHECK_LEAK=yes make check

  デバッガ上でのテスト実行

環境変数CUTTER_DEBUGをyesと設定すると、テストが実行できる環境が整ったgdbが実行されます。gdb上でrunを行うと、テストの実行が開始されます。

run-test.shのみならず、make checkでも利用可能です。

実行例:

% CUTTER_DEBUG=yes make check

  静的解析

scan-buildを用いて、ソースコードの静的解析を行うことができます。scan_buildというディレクトリに解析結果のhtmlが出力されます。:

% scan-build ./configure --prefix=/usr
% make clean
% scan-build -o ./scan_build make -j4

configureは１度のみ実行する必要があります。

  How to contribute in documentation topics

We use Sphinx for documentation tool.

  C API

We still have C API documentation in include/groonga.h. But we want to move them into doc/source/c-api/*.txt. We welcome to you help us by moving C API documentation.

We will use the C domain markup of Sphinx.

  I18N

We only had documentation in Japanese. We start to support I18N documentation by gettext based Sphinx I18N feature. We'll use English as base language and translate English into other languages such as Japanese. We'll put all documentations into doc/source/ and process them by Sphinx.

But we still use Japanese in doc/source/ for now. We need to translate Japanese documentation in doc/source/ into English. We welcome to you help us by translating documentation.

  Translation flow

After doc/source/*.txt are updated, we can start translation.

Here is a translation flow:

1.  Clone groonga repository.

2.  Update .po files.

3.  Edit .po files.

4.  Generate HTML files.

5.  Confirm HTML output.

6.  Repeat 2.-4. until you get good result.

7.  Send your works to us!

    Here are command lines to do the above flow. Following sections describes details.

    # Please fork https://github.com/groonga/groonga on GitHub
    % git clone https://github.com/${YOUR_GITHUB_ACCOUNT}/groonga.git
    % ./autogen.sh
    % ./configure
    % cd doc/locale/${LANGUAGE}/LC_MESSAGES # ${LANGUAGE} is language code such as 'ja'.
    % make update # *.po are updated
    % editor *.po # translate *.po # you can use your favorite editor
    % cd ..
    % make html
    % browser html/index.html # confirm translation
    % git add LC_MESSAGES/*.po
    % git commit
    % git push

  How to clone groonga repository

First, please fork groonga repository on GitHub. You just access https://github.com/groonga/groonga and press Fork button. Now you can clone your groonga repository:

% git clone https://github.com/${YOUR_GITHUB_ACCOUNT}/groonga.git

Then you need to configure your cloned repository:

% cd groonga
% ./autogen.sh
% ./configure

The above steps are just needed at the first setup.

If you have troubles on the above steps, you can use source files available on http://packages.groonga.org/source/groonga/ .

  How to update .po files

You can update .po files by running make update on doc/locale/${LANGUAGE}/LC_MESSAGES. (Please substitute ${LANGUAGE} with your language code such as 'ja'.):

% cd doc/locale/ja/LC_MESSAGES
% make update

  How to edit .po

There are some tools to edit .po files. .po files are just text. So you can use your favorite editor. Here is a specialized editor for .po file edit list.

Emacs's po-mode
    It is bundled in gettext.

Poedit
    It is a .po editor and works on many platform.

gted
    It is also a .po editor and is implemented as Eclipse plugin.

  How to generate HTML files

You can generate HTML files with updated .po files by running make html on doc/locale/${LANGUAGE}. (Please substitute ${LANGUAGE} with your language code such as 'ja'.):

% cd doc/locale/ja/
% make html

You can also generate HTML files for all languages by running make html on doc/locale:

% cd doc/locale
% make html

Note
    you don't care about .mo files.

  How to confirm HTML output

HTML files are generated in doc/locale/${LANGUAGE}/html/. (Please substitute ${LANGUAGE} with your language code such as 'ja'.) You can confirm HTML output by your favorite browser:

% firefox doc/locale/ja/html/index.html

  How to send your works

We can receive your works via pull request on GitHub or E-mail attachment patch or .po files themselves.

  How to send pull request

Here are command lines to send pull request:

% git add doc/locale/ja/LC_MESSAGES/*.po
% git commit
% git push

Now you can send pull request on GitHub. You just access your repository page on GitHub and press Pull Request button. Help.GitHub - Sending pull requests.

  How to send patch

Here are command lines to create patch:

% git add doc/locale/ja/LC_MESSAGES/*.po
% git commit
% git format-patch origin/master

You can find 000X-YYY.patch files in the current directory. Please send those files to us!

  How to send .po files

Please archive doc/locale/${LANGUAGE}/LC_MESSAGES/ (Please substitute ${LANGUAGE} with your language code such as 'ja'.) and send it to us! We extract and merge them to the groonga repository.

  How to add new language

Here are command lines to add new translation language:

% cd doc/locale
% make add LOCALE=${LANGUAGE} # specify your language code such as 'de'.

Please substitute ${LANGUAGE} with your language code such as 'ja'. Codes for the Representation of Names of Languages.

•   genindex

•   modindex

•   search

AUTHOR
groonga project

COPYRIGHT
2009-2013, Brazil, Inc