ElasticSearch-属性に基づく重み付け

Aug 21 2020

Elastic Searchに、検索クエリに使用された属性以外の属性に基づいて結果に重みを付ける方法はありますか?たとえば、フィールド「name」を検索しますが、「with_pictures」がtrueに関連付けられているすべてのドキュメントの重みが高くなります。

回答

2 ESCoder Aug 21 2020 at 09:08

個々のフィールドでブーストを使用できます。ブーストパラメーターを使用すると、クエリ時に自動的にブーストされます(関連性スコアにカウントされます)。

インデックスデータ、マッピング、検索クエリを使用した実例の追加

インデックスマッピング:

{
  "mappings": {
    "properties": {
      "with_pictures": {
        "type": "boolean",
        "boost": 2 
      },
      "name": {
        "type": "keyword"
      }
    }
  }
}

インデックスデータ:

{
    "name": "A",
    "with_pictures": false
}

{
    "name": "A",
    "with_pictures": true
}
{
    "name": "B",
    "with_pictures": true
}

検索クエリ:

{
  "query": {
    "bool": {
      "minimum_should_match": 1,
      "should": [
        {
          "bool": {
            "should": [

              {
                "term": {
                  "name": "A"
                }
              },
              {
                "term": {
                  "with_pictures": true
                }
              }
            ]
          }
        }
      ]
    }
  }
}

検索結果:

 "hits": [
      {
        "_index": "fd_cb1",
        "_type": "_doc",
        "_id": "1",
        "_score": 1.4100108,
        "_source": {
          "name": "A",
          "with_pictures": true
        }
      },
      {
        "_index": "fd_cb1",
        "_type": "_doc",
        "_id": "3",
        "_score": 0.9400072,
        "_source": {
          "name": "B",
          "with_pictures": true
        }
      },
      {
        "_index": "fd_cb1",
        "_type": "_doc",
        "_id": "2",
        "_score": 0.4700036,
        "_source": {
          "name": "A",
          "with_pictures": false
        }
      }
    ]

両方の条件を満たしたドキュメントのスコアnamewith_properties最高のスコアを持っています。しかし、文書が持つname: Bwith_pictures: trueより高いスコアを持っているname: Aし、with_pictures: falseために適用されるブーストの(with_pictures

クエリによって取得されたドキュメントのスコアを変更できる関数スコアクエリを参照することもできます。