LoginSignup
0
2

More than 5 years have passed since last update.

Elasticsearch 6.2.4 で More Like This Query を利用する際にデータを絞り込む

Posted at

Elasticsearch で More Like This Query を利用して類似文書検索を行う際に、データを絞り込む必要があった場合の方法になります。
More Like This Query の使い方自体は以下のドキュメントにまとまっています。
More Like This Query

手元の環境は以下になります。

  • Ubuntu 16.04 LTS
  • Elasticsearch 6.2.4
  • ICU Analysis Plugin、Japanese (kuromoji) Analysis Plugin

Elasticsearch 6系 からインデックスにはひとつのタイプとなったので、親子関係のデータを実現している場合は類似文書検索でもデータのタイプを指定する必要があります。
その場合は Bool Query と filter を使えば絞り込むことが可能です。

この記事 のデータを引き続き活用して試すため、以下のデータを追加します。

{"index": {"_index": "shop", "_type": "_doc","_id": "goods_id.3"}}
{"type": "goods","name": "原酒三岳","text": "もののけ姫のモデルにもなった、鹿児島県屋久島の焼酎です。こちらは原酒になります。屋久島は水が美味しく、その水を
使って作られています。ロックで飲むことをオススメします。","my_join_field": "goods"}

そして、以下のように実行します。( jq コマンドで整形してます。)
便宜上、min_term_freq (出現頻度の最低値)をゼロにしています。

$ curl -X POST 'localhost:9200/shop/_search' -H 'Content-Type: application/json' -d'
{
    "size": 5,
    "query": {
        "bool": {
            "must": {
                "more_like_this": {
                    "fields": ["text"],
                    "like":[
                    {
                        "_index" : "shop",
                        "_type" : "_doc",
                        "_id" : "goods_id.1"
                    }
                    ],
                    "min_term_freq": 0
                }
            },
            "filter": { "term": { "type": "goods" } }
        }
        }
    }
}
' | jq

すると、以下のような結果が返ってきます。

{
  "took": 41,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": 1,
    "max_score": 0.19518803,
    "hits": [
      {
        "_index": "shop",
        "_type": "_doc",
        "_id": "goods_id.3",
        "_score": 0.19518803,
        "_source": {
          "type": "goods",
          "name": "原酒三岳",
          "text": "もののけ姫のモデルにもなった、鹿児島県屋久島の焼酎です。こちらは原酒になります。屋久島は水が美味しく、その水を使って作られています。ロックで飲むことをオススメします。",
          "my_join_field": "goods"
        }
      }
    ]
  }
}

パラメータもいくつかあるので、チューニング次第では面白い結果が出せるかもしれません。

参考になった記事

More_like_this query with a filter

0
2
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
0
2