Skip to content

Instantly share code, notes, and snippets.

@rylnd
Created January 12, 2023 05:02
Show Gist options
  • Select an option

  • Save rylnd/a5d63f1405b2a6114a330333874ea394 to your computer and use it in GitHub Desktop.

Select an option

Save rylnd/a5d63f1405b2a6114a330333874ea394 to your computer and use it in GitHub Desktop.
scoring_query
# for each identifier (example with user.name)
GET risk-score-demo/_search
{
"size": 0,
"query": {
"bool": {
"must": [
{
"match": {
"event.category": "risk"
}
},
{
"match": {
"event.type": "reason"
}
},
{
"exists": {
"field": "user.name"
}
}
]
}
},
"aggs": {
"entities": {
"terms": {
"field": "user.name",
"size": 1000
},
"aggs": {
"riskiest_reasons": {
"top_hits": {
"size": 30,
"sort": [
{
"risk.score": {
"order": "desc"
}
}
],
"_source": false
}
},
"normalized_score": {
"scripted_metric": {
"init_script": "state.scores = []",
"map_script": "state.scores.add(doc['risk.score'].value)",
"combine_script": "return state",
"params": {
"p": 1.5,
"risk_cap": 261.2
},
"reduce_script": """
List scores = [];
for (state in states) {
scores.addAll(state.scores)
}
Collections.sort(scores, Collections.reverseOrder());
long max_score = scores[0];
double total_score = 0;
for (int i = 0; i < scores.length; i++) {
total_score += scores[i] / Math.pow(i + 1, params.p)
}
double normalized_score = 100 * total_score / params.risk_cap;
return normalized_score;
"""
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment