Elasticsearch搜索出现NAN异常

原因分析

  • Elasticsearch默认的打分,一般是不会出现异常的
  • 之所以会出现NAN异常,往往是因为我们重新计算了打分,使用了function_score
  • 核心原因是在function_score中,出现了计算异常,比如 0/0,比如log1p(x),x为负数等

真实案例分析

测试索引

bash 复制代码
PUT tx
POST tx/_mapping
{
      "properties" : {
        "age" : {
          "type" : "long"
        },
        "time" : {
          "type" : "date",
          "format" : "yyyy-MM-dd"
        },
        "title" : {
          "type" : "text",
          "analyzer" : "ik_smart"
        }
      }
}
POST tx/_doc/19
{
  "title":"中古",
   "time" : "1969-10-12",
   "age":12
}

搜索query示例

bash 复制代码
POST /tx/_search
{
  "query": {
    "function_score": {
      "query": {
          "match_all": {}
      },
      "field_value_factor": {
        "field": "time",
        "modifier": "log1p"
      }
    }
  }
}
- 其实modifier.log1p和如下搜索是完全一样的
POST /tx/_search
{
  "query": {
    "function_score": {
      "query": {
        "match_all": {}
      },
      "script_score": {
        "script": "_score * Math.log1p(1+doc['time'].value.toInstant().toEpochMilli())"
      }
    }
  }
}

搜索异常返回值

bash 复制代码
{
  "error" : {
    "root_cause" : [
      {
        "type" : "exception",
        "reason" : "function score query returned an invalid score: NaN for doc: 0"
      }
    ],
    "type" : "search_phase_execution_exception",
    "reason" : "all shards failed",
    "phase" : "query",
    "grouped" : true,
    "failed_shards" : [
      {
        "shard" : 0,
        "index" : "tx",
        "node" : "aPOBCVYkRA-a0R9FR4eDzQ",
        "reason" : {
          "type" : "exception",
          "reason" : "function score query returned an invalid score: NaN for doc: 0"
        }
      }
    ]
  },
  "status" : 500
}

搜索异常原因分析

  • 搜索使用了function_score重新打分,并且使用了log1p函数
  • 但是由于数据中的时间是"1969-10-12",但是es计算时间是从1970年计算开始,这个值换算成毫秒就是负数,导致log1p异常
  • 所以最终得分异常,出现是NAN
相关推荐
lqlj223331 分钟前
Linux常用命令
linux·运维·服务器
itachi-uchiha1 小时前
深入理解 Linux 中的 last 和 lastb 命令
java·linux·服务器
还有几根头发呀2 小时前
Ubuntu中dpkg命令和apt命令的关系与区别
linux·运维·ubuntu
浪子西科2 小时前
【Elasticsearch】(Java 版)
java·大数据·elasticsearch
applebomb2 小时前
ubuntu下r8125网卡重启丢失修复案例一则
linux·ubuntu·驱动·r8125
AF012 小时前
Ubuntu系统上部署Node.js项目的完整流程
linux·ubuntu·node.js
吃汤圆的抹香鲸3 小时前
PhpStorm 绿色版 安装包 Win/Mac/Linux 商业的PHP集成开发环境 2025全栈开发终极指南:从零配置到企业级实战
linux·ide·windows·macos·php·intellij-idea·phpstorm
我是唐青枫4 小时前
Linux 下使用tracepath进行网络诊断分析
linux·运维·网络
s_little_monster4 小时前
【Linux】进程间通信之匿名管道
linux·运维·服务器·数据库·经验分享·笔记·学习