2

I have a Java program that will dynamically build queries for ElasticSearch given some params. Currently, the way I have this built escapes the strings because the JsonObject as a part of Google's GSON library requires a string to be passed to append JSON.

The output from the below methods is the following:

{
   "query":{
      "bool":{
         "filter":[
            {
               "exists":"{\"field\":\"user_id\"}"
            },
            {
               "exists":"{\"field\":\"campaign_id\"}"
            }
         ]
      }
   }
}

As you can see, the exists values are escapes and ElasticSearch throws a fit about this. How can I achieve this result without having the escapes strings?

JsonObject buildQuery() {
    JsonObject request = new JsonObject();

    // build the terms query
    JsonArray termsArr = new JsonArray();
    termsArr.add(buildFilterQueryForField("user_id"));
    termsArr.add(buildFilterQueryForField("campaign_id"));
    JsonObject terms = JsonHelper.createObject("bool.filter", termsArr);
    request.add("query", terms);

    return request;
}

Below is the code for the buildFilterQueryForField(*). In this method, i've tried to use a regex to remove these, however this regex doesn't give me the result i'm after.

static JsonObject buildFilterQueryForField(String fieldName) {
    JsonObject builder = new JsonObject();
    JsonObject nestedObj = new JsonObject();
    nestedObj.addProperty("field", fieldName);
    builder.addProperty("exists", nestedObj.toString().replaceAll("\\\\", ""));
    return builder;
}

The end goal for this is the following:

{
   "query":{
      "bool":{
         "filter":[
            {
                "exists": { "field": "user_id" }
            },
            {
                "exists": { "field": "campaign_id" }
            },
         ]
      }
   }
}
0

1 Answer 1

1

those escapes are required because you are actually embedding another json object inside the string value for the exists field. instead of using addProperty, you should be using builder.add("exists", nestedObj) just like you do elsewhere.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.