5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

groongaで複数のカラムのスコアを別々に扱う方法

Last updated at Posted at 2013-05-23

いよいよ、gihyo.jpさんでgroongaの隔週更新連載が始まりました!!
第4回の記事も公開されたので、一読をおすすめします。

連載は始まりましたが、利用事例をどんどん紹介していきたいです。(利用事例のストックが尽きたら終了してしまいます。)
groongaやmroonga、rroongaを実際に使っていて利用事例記事を書いてもいいよ、という人をまだまだ募集しています。
詳細はgroonga普及のための協力のお願いを参照してください。

はじめに

オープンソースのカラムストア機能付き全文検索エンジンgroongaを公開しています。

この記事を書いたときの最新のバージョンは2013年4月29日にリリースした3.0.3です。

今回は、複数カラムのスコアを別々に扱う方法を紹介します。

複数カラムのスコアリング

groongaでは検索結果がどれだけマッチしているかというのはスコアの値の大きさで判断します。
このスコアは検索クエリを実行するごとに_scoreカラムへと反映されます。

例えば、本にコメントをつけているときのことを考えてみましょう。
Books テーブルがあって、Books テーブルにはタイトルを保持する title カラムとコメントを記録するための comment カラムがあるとします。

サンプルのスキーマ定義は以下のようになるでしょう。

table_create  Books         TABLE_NO_KEY
column_create Books title   COLUMN_SCALAR ShortText
column_create Books comment COLUMN_SCALAR ShortText

table_create  Terms             TABLE_PAT_KEY ShortText --default_tokenizer TokenBigram
column_create Terms index_books COLUMN_INDEX|WITH_POSITION|WITH_SECTION Books title,comment

上記サンプルのためのサンプルデータを用意します。

load --table Books
[
{"title": "groonga入門", "comment": "groongaの初歩的な内容のみ。"},
{"title": "実践groonga", "comment": "入門の次に読むべき本。"},
{"title": "mroonga入門", "comment": "mroongaの初歩的な内容のみ。groongaについても触れている。"}
]

titleもしくはcommentカラムからgroongaを検索してみましょう。

select Books --match_columns 'title||comment' --query groonga --output_columns title,_score

この結果は以下のようになります。

[
  [
    [3],
    [
      ["_key","UInt32"],
      ["title","ShortText"],
      ["_score","Int32"]
    ],
    ["groonga入門",2],
    ["実践groonga",1],
    ["mroonga入門",1]
  ]
]

「groonga入門」はtitleにもcommentカラムにもgroongaが含まれているので、他よりもスコアが高くなっています。

groongatitlecommentのどちらかに含まれていれば良いので、そういうときはスコアを同じにしたいという場合にはどうすればいいでしょうか。

groongaではカラムごとの重みづけができるので、重みづけを利用して複数のカラムのスコアを別々に扱うことができます。

titleカラムを10の位に、commentカラムを1の位に割り当てることにしましょう。
これを利用するとクエリは以下のように書くことができます。

select Books --match_columns 'title * 10 || comment' --query groonga --scorer '_score = max(_score / 10, _score % 10)' --output_columns title,_score

この結果は以下のようになります。

[
  [
    [3],
    [
      ["_key","UInt32"],
      ["title","ShortText"],
      ["_score","Int32"]
    ],
    ["groonga入門",1],
    ["実践groonga",1],
    ["mroonga入門",1]
  ]
]

複数のカラムのスコアを別々に扱うことで、どちらかにgroongaが含まれている場合はスコアが一緒になるようにすることができました。

まとめ

今回は、groongaで複数のカラムのスコアを別々に扱う方法を紹介しました。

groongaに興味を持ったなら、まずはインストールして試してみてください。

groongaの基本的な動作を知るためのチュートリアルもあります。インストールしたら試してみてください。

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?