弹性搜索-基于属性的加权

时间:2020-08-21 01:29:05

标签: elasticsearch

Elastic Search中是否有一种方法可以基于除搜索查询所用属性以外的其他属性来加权结果。例如,我们搜索“名称”字段,但是所有将“ with_pictures”归为true的文档的权重都较高。

1 个答案:

答案 0 :(得分:2)

您可以在各个字段上使用boost,这些字段会自动提升-在查询时,使用boost参数

会更多地计入相关性得分-

添加带有索引数据,映射和搜索查询的工作示例

索引映射:

{
  "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: Awith_pictures: false()的得分更高,这是因为with_pictures

您还可以参考function score query,它允许您修改查询检索的文档分数。

相关问题