I am trying to parse following json i am getting from elastic-search api in groovy using jsonslurper . I need to create a list of _id out of this json. Tried multiple variation of code but no success
please suggest , any help appreciated.
Scanner s = new Scanner(responseStream).useDelimiter("\\A")
String response = s.hasNext() ? s.next() : ""
def jsonSlurper = new JsonSlurper()
def json = jsonSlurper.parseText(response)
def _id = []
_id = json.getAt("hits").getAt("hits")
for(def id:_id){
//id.getAt("_id")
System.out.println(id.getAt("_id"))
}
{
"took" : 2535,
"timed_out" : false,
"_shards" : {
"total" : 384,
"successful" : 384,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 10000,
"relation" : "gte"
},
"max_score" : null,
"hits" : [
{
"_index" : "X",
"_type" : "_doc",
"_id" : "310165903526204",
"_score" : null,
"sort" : [
"310165903526204"
]
},
{
"_index" : "X",
"_type" : "_doc",
"_id" : "310165903698515",
"_score" : null,
"sort" : [
"310165903698515"
]
},
{
"_index" : "X",
"_type" : "_doc",
**"_id" : "310165903819494"**,
"_score" : null,
"sort" : [
"310165903819494"
]
}
]
}
}
PS: I tried using multiple clients provided by elasticsearch to search ES and parse data but i am facing another issue with that, so had to switch to HTTP client and do manual parse . this is link for client issue RestHighLevelClient with Elasticsearch client error
CodePudding user response:
def _id = json.hits.hits.collect{ it._id }
_id.each{println it}
CodePudding user response:
Basic Groovy's object navigation is here to help:
import groovy.json.*
String response = '''\
{
"took" : 2535,
"timed_out" : false,
"_shards" : {
"total" : 384,
"successful" : 384,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 10000,
"relation" : "gte"
},
"max_score" : null,
"hits" : [
{
"_index" : "X",
"_type" : "_doc",
"_id" : "310165903526204",
"_score" : null,
"sort" : [
"310165903526204"
]
},
{
"_index" : "X",
"_type" : "_doc",
"_id" : "310165903698515",
"_score" : null,
"sort" : [
"310165903698515"
]
},
{
"_index" : "X",
"_type" : "_doc",
"_id" : "310165903819494",
"_score" : null,
"sort" : [
"310165903819494"
]
}
]
}
}'''
def json = new JsonSlurper().parseText response
List ids = json.hits.hits*._id
assert ids.toString() == '[310165903526204, 310165903698515, 310165903819494]'