获取动态密钥值时出现Elasticsearch错误

时间:2018-06-15 00:22:20

标签: elasticsearch elasticsearch-query elasticsearch-6 elasticsearch-painless

我的一个索引的部分映射如下:

"schools": {
  "type": "object",
  "dynamic": true,
  "properties": {}
}

现有文档的示例schools对象是:

"schools": {
  "8291": {
    "max": 11,
    "min": 11
  },
  "3546": {
    "max": 12,
    "min": 10
  },
  "3896": {
    "max": 18,
    "min": 12
  }
}

我在ES6.2中有无痛脚本,其中动态key(例如3896)在运行时计算并作为参数传递给脚本

"script": {
  "params": {
    "key": key
  },
  "source": {
    if (doc.containsKey('schools') && doc.schools.containsKey(key)){
      String dynamic_key = "schools."+key+".min";
      return doc[dynamic_key].value;
    } else {
      return 0;
  }
}

因此,如果传递key值为3896,那么这应该返回12.但是我收到一条错误消息

No field found for [schools.3896.min] in mapping with types [myindexname]

我做错了什么?访问动态对象的正确方法是什么,在动态对象上运行时计算键名以获取其值?

1 个答案:

答案 0 :(得分:0)

这是获取嵌套对象的价值的方法:

PUT intstitutes
{
  "mappings": {
    "log": {
      "properties": {
        "schools": {
          "type": "object",
          "dynamic": true,
          "properties": {}
        }
      }
    }
  }
}

PUT /intstitutes/log/1?refresh
{
  "schools": {
    "3546": {
      "max": 12,
      "min": 10
    },
    "3896": {
      "max": 18,
      "min": 12
    },
    "8291": {
      "max": 11,
      "min": 11
    }
  }
}

POST intstitutes/_search
{
  "query": {
    "match": {
      "_id": "1"
    }
  },
  "script_fields": {
    "script_score": {
      "script": {
        "params": {
          "key": "3896"
        },
        "source": "if (params._source.containsKey('schools') && params._source.schools.containsKey(params.key)) { return params._source.schools.get(params.key).min } else { return 0 }"
      }
    }
  }
}
DELETE intstitutes