R
R
ruboss2015-10-03 23:51:02
Java
ruboss, 2015-10-03 23:51:02

How to write a Groovy script in elasticsearch sripts?

Hello! There is a "table" in ES that looks like
{"fields": [{"id":[{"innerField":[value]}]}]}}
or
object("fields", array( object( "ids" , array( object( "innerFields", array( value) ) ) ) ) )
or

IndexResponse response = client
          .prepareIndex(index, type, id)
          .setSource(
              jsonBuilder()
                .startObject()
                  .startArray("fields")
                    .startObject()
                      .startArray(filmId).
                        startObject().array("ids",val).endObject()
                      .endArray()
                    .endObject()
                  .endArray()
                .endObject())
          .execute().actionGet();

How can you make an Update request in a Groovy script
if you need to add an entry to the ids array and inside it already add an entry to the innerFields array. It is
necessary that the entries are not duplicated.
So far I have come to this, but it gives out exceptions
if (ctx._source.fields.contains(\""+id1+"\")) {
  if(!ctx._source.fields[\""+id1+"\"].innerFields.contains(\""+val1+"\")){
    ctx._source.fields[\""+id1+"\"].innerFields = [\""+val1+"\"]
  };
} else {
  ctx._source.fields += \""+id1+"\"
  ctx._source.fields[\""+id1+"\"].innerFields =  [\""+val1+"\"]
}

Sori, there is a problem with markup.
I would be very grateful if you tell me where to dig or how to change the code!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
ruboss, 2015-10-04
@ruboss

import groovy.json.JsonBuilder
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

def someJSONString = '{"films":[{"5":[5,3,4,5,6]}, {"4":[1,2]}]}}'
def slurper = new JsonSlurper()
def doc = slurper.parseText(someJSONString)

for(films in doc.films){
  if(setFilm || setSec)
    break
  def secs = films.get(cfid)
  if(secs != null){
    setFilm = true
    setSec = true
    for(sec in secs){
      if(sec == csec)
        setSec = false
    }
    if(setSec)
      secs.add(csec)
  }
}
if(!setFilm){
  def lhm = new LinkedHashMap();
  def al = new ArrayList();
  al.add(csec)
  lhm.put(cfid,al)
  doc.films += lhm;
}

def out= new File('ex.txt'); out.createNewFile(); out << doc;

println doc

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question