elasticsearch - Elasticsearch 中的加权随机抽样

标签 elasticsearch random weighted

我需要从 ElasticSearch 索引中获取随机样本,即发出一个查询,以加权概率 Wj/ΣWi 从给定索引中检索一些文档(其中 Wj 是行 j 的权重,Wj/ΣWi 是该查询中所有文档的权重之和。

目前,我有以下查询:

GET products/_search?pretty=true

{"size":5,
  "query": {
    "function_score": {
      "query": {
        "bool":{
          "must": {
            "term":
              {"category_id": "5df3ab90-6e93-0133-7197-04383561729e"}
          }
        }
      },
      "functions":
        [{"random_score":{}}]
    }
  },
  "sort": [{"_score":{"order":"desc"}}]
}

它随机返回所选类别中的 5 个项目。 每个项目都有一个字段 weight。所以,我可能不得不使用

"script_score": {
  "script": "weight = data['weight'].value / SUM; if (_score.doubleValue() > weight) {return 1;} else {return 0;}"
}

描述here .

我有以下问题:

  • 执行此操作的正确方法是什么?
  • 我需要启用 Dynamic Scripting 吗? ?
  • 如何计算查询的总和?

非常感谢您的帮助!

最佳答案

如果对任何人有帮助,以下是我最近实现加权洗牌的方法。

在这个例子中,我们洗牌公司。每家公司都有一个介于 0 和 100 之间的“company_score”。通过这种简单的加权洗牌,得分为 100 的公司出现在首页的可能性是得分为 20 的公司的 5 倍。

json_body = {
    "sort": ["_score"],
    "query": {
        "function_score": {
            "query": main_query,  # put your main query here
            "functions": [
                {
                    "random_score": {},
                },
                {
                    "field_value_factor": {
                        "field": "company_score",
                        "modifier": "none",
                        "missing": 0,
                    }
                }
            ],
            # How to combine the result of the two functions 'random_score' and 'field_value_factor'.
            # This way, on average the combined _score of a company having score 100 will be 5 times as much
            # as the combined _score of a company having score 20, and thus will be 5 times more likely
            # to appear on first page.
            "score_mode": "multiply",
            # How to combine the result of function_score with the original _score from the query.
            # We overwrite it as our combined _score (random x company_score) is all we need.
            "boost_mode": "replace",
        }
    }
}

关于elasticsearch - Elasticsearch 中的加权随机抽样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34128770/

相关文章:

python - 根据 NetworkX 中出现的次数计算边的权重

Elasticsearch REST API : search by particular field only

php - 使用 PHP 5.6 生成范围内的安全随机整数

elasticsearch - 如何在 Elasticsearch 中聚合数组中匹配的字段

java - 在二维数组中生成唯一的行和列

java - 获取一个重复操作的按钮

python - 如何在 python 中加权站以订购最小二乘法?

java - 当我尝试打印加权有向图(调整列表)的内容时输出错误

php - Elasticsearch。嵌套查询嵌套

elasticsearch - 如何在Grafana量规中显示最后一个值