Elasticsearch对来自多个索引的结果进行排序,以便一个索引具有优先级



我有6个网站,让我们称它们为A,B,C,D,E和M.M是主网站,因为您可以从中搜索其他人的内容,我已经通过在搜索查询中将所有索引用逗号分隔来轻松完成。

但是我现在有一个新的要求,您可以从每个网站搜索所有网站(很容易做到,将解决方案从 M 应用到所有(,但优先考虑当前网站的结果。

因此,如果我从 C 搜索,首先的结果应该是来自 C,然后是根据分数从其他结果中搜索的。

现在,如何给出一个索引优先级高于其他索引的结果?

提升查询可以很好地达到此目的:

示例数据

POST /_bulk
{"index":{"_index":"a"}}
{"message":"First website"}
{"index":{"_index":"b"}}
{"message":"Second website"}
{"index":{"_index":"c"}}
{"message":"Third website"}
{"index":{"_index":"d"}}
{"message":"Something irrelevant"}

查询

POST /a,b,c,d/_search
{
  "query": {
    "boosting": {
      "positive": {
        "match": {
          "message": "website"
        }
      },
      "negative": {
        "terms": {
          "_index": ["b", "c", "d"]
        }
      }, 
      "negative_boost": 0.2
    }
  }
}

响应

{
  ...
  "hits" : {
    "total" : {
      "value" : 3,
      "relation" : "eq"
    },
    "max_score" : 0.2876821,
    "hits" : [
      {
        "_index" : "a",
        "_type" : "_doc",
        "_id" : "sx-DkWsBHWmGEbsYwViS",
        "_score" : 0.2876821,
        "_source" : {
          "message" : "First website"
        }
      },
      {
        "_index" : "b",
        "_type" : "_doc",
        "_id" : "tB-DkWsBHWmGEbsYwViS",
        "_score" : 0.05753642,
        "_source" : {
          "message" : "Second website"
        }
      },
      {
        "_index" : "c",
        "_type" : "_doc",
        "_id" : "tR-DkWsBHWmGEbsYwViS",
        "_score" : 0.05753642,
        "_source" : {
          "message" : "Third website"
        }
      }
    ]
  }
}

笔记

  1. 你做的negative_boost越小,"活跃指数"的结果就越有可能胜过其他指数
  2. 如果将negative_boost设置为 0 ,您将保证"活动站点"结果首先排序,但您将丢弃所有其他站点的所有分数,因此其余排序将是任意的。

我认为像negative_boost: 0.1这样的东西,这是对相关性的一个数量级调整,应该能让你得到你想要的东西。

最新更新