Configure elasticsearch mapping with java api

user3618259 picture user3618259 · May 8, 2014 · Viewed 20.5k times · Source

I have a few elasticsearch fields that I don't want to analyze before indexing. I have read that the right way to do this is by altering the index mapping. Right now my mapping looks like this:

{
  "test" : {
   "general" : {
      "properties" : {
        "message" : {
          "type" : "string"
        },
        "source" : {
          "type" : "string"
        }
      }
    }
  }
}

And I would like it to look like this:

{
  "test" : {
   "general" : {
      "properties" : {
        "message" : {
          "type" : "string",
          "index" : "not_analyzed"
        },
        "source" : {
          "type" : "string"
        }
      }
    }
  }
}

I have been trying to change the settings via

client.admin().indices().prepareCreate("test")
        .setSettings(getGrantSettings());

Where getGrantSettings() looks like:

static Settings getGrantSettings(){
    JSONObject settingSource = new JSONObject();
    try{
        settingSource.put("mapping", new JSONObject()
        .put("message", new JSONObject()
            .put("type", "string")
            .put("index", "not_analyzed")
        ));
    } catch (JSONException e){
        e.printStackTrace();
    }


    Settings set = ImmutableSettings.settingsBuilder()
            .loadFromSource(settingSource.toString()).build();
    return set;
}

Answer

Paige Cook picture Paige Cook · May 9, 2014

I have successfully applied mappings to an Elasticsearch index using the Java API like the following:

 XContentBuilder mapping = jsonBuilder()
                              .startObject()
                                   .startObject("general")
                                        .startObject("properties")
                                            .startObject("message")
                                                .field("type", "string")
                                                .field("index", "not_analyzed")
                                             .endObject()
                                             .startObject("source")
                                                .field("type","string")
                                             .endObject()
                                        .endObject()
                                    .endObject()
                                 .endObject();

  PutMappingResponse putMappingResponse = client.admin().indices()
                .preparePutMapping("test")
                .setType("general")
                .setSource(mapping)
                .execute().actionGet();

Hope this helps.