Thomas Kagan
Thomas Kagan

Reputation: 438

How to write multiline Elasticsearch scripts with Postman

I'm trying to do an Elasticsearch GET query with a very simple script using Postman. When the script is all on one line it works but if I try to do multiple lines I get an error

I'm sening the data as JSON with Content-Type: application/json in the header

Example - Works:

{
    "query":{
        "match_all": {}
    },
    "script_fields": {
        "my_custom_field":{
            "script": {
                "lang": "painless",
                "source": "int count = 1; return count;"
            }
        }
    }
}

Example - Produces Error:

{
    "query":{
        "match_all": {}
    },
    "script_fields": {
        "my_custom_field":{
            "script": {
                "lang": "painless",
                "source": """
                   int count = 1;
                   return count;
                """
            }
        }
    }
}

The error:

 "Unexpected character ('\"' (code 34)): was expecting comma to separate Object entries\n at [Source: org.elasticsearch.transport.netty4.ByteBufStreamInput@20493763; line: 9, column: 18]"

I think postman may be adding line breaks in behind the scenes.

Upvotes: 2

Views: 3795

Answers (1)

Joe - Check out my books
Joe - Check out my books

Reputation: 16925

Triple-quotes in JSON are technically not valid -- see this thread for more info.

You've essentially got 3 options:

  • Write a script which takes in a multiline "JSON" text and produces a \n-separated, valid JSON (what I often did before multiline backtick strings were a thing in JavaScript, and still do in php):
function compactifyMultilineString( $input_string )
{
    return str_replace( array( "\r", "\n", "\t" ), " ", $input_string );
}
  • Use postman's own pre-request scripts
  • Or, probably the most reasonable option, set up Kibana right next to your ElasticSearch server. Kibana is great for testing out queries and it also supports a postman-ready copy feature:

enter image description here

Upvotes: 3

Related Questions