dak ブログ

python、rubyなどのプログラミング、MySQL、サーバーの設定などの備忘録。レゴの写真も。

Elastcisearch でフィールド毎に重みづけしたスコアリング

2022-12-10 23:43:00 | elasticsearch
Elastcisearch でフィールド毎に重みづけして検索を行う方法のメモ。
■検索クエリパターン
title、body の各フィールドに対して、スコアにそれぞれ title_boost、body_boost を掛け、その結果を加算したものが最終的なスコアとなります。
{
  "query": {
    "function_score": {
      "query": {
        "bool": {
          "should": [
            {"match": {"title": {"query": "abc", "boost": 【title_boost】}}},
            {"match": {"body": {"query": "abc", "boost": 【body_boost】}}}
          ]
        }
      },
      "score_mode": "sum",
      "boost_mode": "sum"
    }
  }
}

■title_boost: 0.0、body_boost: 0.0 での検索結果
スコアは 0.0 となっています。
    "hits" : [
      {
        "_index" : "idx1",
        "_id" : "doc_01",
        "_score" : 0.0,
        "_source" : {
          "id" : "doc_01",
          "title" : "商品 abc"
        }
      }
    ]

■title_boost: 1.0、body_boost: 0.0 での検索結果
スコアは 1.540445 となっていて、これが title にマッチした場合のスコアとなります。
    "hits" : [
      {
        "_index" : "idx1",
        "_id" : "doc_01",
        "_score" : 1.540445,
        "_source" : {
          "id" : "doc_01",
          "title" : "商品 abc"
        }
      }
    ]

■title_boost: 0.0、body_boost: 1.0 での検索結果
スコアは 1.4916282 となっていて、これが body にマッチした場合のスコアとなります。
    "hits" : [
      {
        "_index" : "idx1",
        "_id" : "doc_01",
        "_score" : 1.4916282,
        "_source" : {
          "id" : "doc_01",
          "title" : "商品 abc"
        }
      }
    ]

■title_boost: 10.0、body_boost: 0.0 での検索結果
スコアは 15.404451 で、title_boost: 1.0 の場合(1.540445)の 10倍の値となっています。
    "hits" : [
      {
        "_index" : "idx1",
        "_id" : "doc_01",
        "_score" : 15.404451,
        "_source" : {
          "id" : "doc_01",
          "title" : "商品 abc"
        }
      }
    ]

■title_boost: 10.0、body_boost: 1.0 での検索結果
スコアは 16.89608 で、title_boost: 10.0、body_boost: 0.0 の場合のスコア(15.404451)と、title_boost: 0.0、body_boost: 1.0 の場合のスコア(1.4916282)の和となっています。
    "hits" : [
      {
        "_index" : "idx1",
        "_id" : "doc_01",
        "_score" : 16.89608,
        "_source" : {
          "id" : "doc_01",
          "title" : "商品 abc"
        }
      }
    ]