Elasticsearch检查对象中是否存在密钥

时间:2018-04-05 18:20:10

标签: elasticsearch groovy elasticsearch-2.0 elasticsearch-query

我对其中一个索引的部分映射:

{
  "title": { "type": "string"},
  "seasons": {
    "type": "object",
    "dynamic": true,
    "properties": {}
  }
}

目前,我有4个文件如下:

Doc 1

{
  "title": "abc",
  "seasons": null
}

Doc 2

{
  "title": "xyz",
  "seasons": {
    "201809": 23,
    "201902": 45
  }
}

Doc 3

{
  "title": "xyz",
  "seasons": {
    "201811": 23,
    "201910": 23,
    "201809": 45,
    "201805": 35,
  }
}

Doc 4

{
  "title": "xyz",
  "seasons": {
    "201802": 23,
    "201902": 45
  }
}

seasons对象将始终为nullkey=>val对。

我想在其中搜索所有包含season字段及密钥201809(此处为doc2和doc3 qualify)的文档,然后对该文档进行进一步处理。

要求 - 我需要仅使用groovy脚本来运行此搜索。在我的groovy脚本中,我确实有:

if (doc["seasons.201809"].value) {
   ....more processing after finding the document.....
}

但是对于这次检查,我得到了"TransportError(500, 'search_phase_execution_exception', 'no_class_def_found_error: java/lang/Throwable')"。 我确信这一行不是正确的检查

if (doc["seasons.201809"].value) {

任何人都可以让我知道如何解决检查密钥存在的问题吗?

1 个答案:

答案 0 :(得分:1)

对于Groovy部分,您可以执行以下操作:

// (1) More verbose approach
if (doc.containsKey('seasons') && doc.seasons.containsKey('201802')) {
    println "Key seasons.201802 exists!"
}

或:

// (2) Shorter version
if (doc?.seasons?.containsKey('201802')) {
    println "Key seasons.201802 exists!"
}

这里有一些Groovy完整样本:

import groovy.json.JsonSlurper

String json = '''{
  "title": "xyz",
  "seasons": {
    "201802": 23,
    "201902": 45
  }
}'''

Map doc = new JsonSlurper().parseText(json)

// (1) More verbose approach
if (doc.containsKey('seasons') && doc.seasons.containsKey('201802')) {
    println "(1) Key seasons.201802 exists!"
}

// (2) Shorter version
if (doc?.seasons?.containsKey('201802')) {
    println "(2) Key seasons.201802 exists!"
}

输出

(1) Key seasons.201802 exists!
(2) Key seasons.201802 exists!