Elasticsearch Painless从嵌套元素计算分数 [英] Elasticsearch Painless calculate score from nested elements

查看:465
本文介绍了Elasticsearch Painless从嵌套元素计算分数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:我最初发布此问题的方式有所不同,因此不值得更新,因为阅读后我学到了更多信息.

Note: I had originally posted this question a little differently and it wasn't worth updating as after reading I learned a bit more.

搜索文档并根据文档中的嵌套元素计算自定义分数.

Search for documents and calculate a custom score based on nested elements within the document.

{
  "mappings": {
    "book": {
      "properties": {
        "title":        { "type": "string", "index": "not_analyzed" },
        "topics": {
          "type": "nested",
          "properties": {
            "title":   { "type": "string", "index": "not_analyzed" },
            "weight":  { "type": "int" }
          }
        }
      }
    }
  }
}

样本查询

{
  "query": {
    "function_score": {
      "query": {
        "term": { "title": "The Magical World of Spittle" }
      },
      "script_score": {
        "script": {
          "lang": "painless",
          "inline": "int score = 0; for(int i = 0; i < doc['topics'].values.length; i++) { score += doc['topics'][i].weight; } return score;",
          "params": {
            "default_return_value": 100
          }
        }
      }
    }
  }
}

孤立无痛

int score = 0;
for(int i = 0; i < doc['topics'].values.length; i++) {
  score += doc['topics'][i].weight;
}
return score;

错误

在类型为[book]的映射中找不到[topics]的字段

No field found for [topics] in mapping with types [book]

问题

  • 怎么了?
  • 该怎么办?
  • The Questions

    • What's wrong?
    • What to do?
    • 推荐答案

      嵌套文档存储在索引中的不同文档中,因此您无法通过父文档中的doc值来访问它们.您需要使用源文档并导航到topics.weight属性,如下所示:

      Nested documents are stored in different documents in the index, so you cannot access them via doc values from the parent document. You need to use the source document and navigate to the topics.weight property, like this:

      无痛隔离:

      int score = 0; 
      for(int i = 0; i < params._source['topics'].size(); i++) { 
          score += params._source['topics'][i].weight; 
      }
      return score;
      

      完整查询:

      {
        "query": {
          "function_score": {
            "query": {
              "term": { "title": "Book 1" }
            },
            "script_score": {
              "script": {
                "lang": "painless",
                "inline": "int score = 0; for(int i = 0; i < params._source['topics'].size(); i++) { score += params._source['topics'][i].weight; } return score;",
                "params": {
                  "default_return_value": 100
                }
              }
            }
          }
        }
      }
      

      PS:还请注意,类型int不存在,它是integer

      PS: Also note that the type int doesn't exist, it's is integer

      这篇关于Elasticsearch Painless从嵌套元素计算分数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆