set field data = true on java elasticsearch

☆樱花仙子☆ 提交于 2019-12-02 02:24:48

You must modify index mapping properties:

try (XContentBuilder jsonBuilder = XContentFactory.jsonBuilder()) {
    final XContentBuilder builder = jsonBuilder
            .startObject()
              .startObject("your_type")
                .startObject("properties")
                  .startObject("your_field")
                    .field("type", "text")
                    .field("fielddata", true)/*setting fielddata*/
                  .endObject()
                .endObject()
              .endObject()
            .endObject();

    client.admin().indices().preparePutMapping("your_index")
            .setType("your_type")
            .setSource(builder)/*also there are overloads for setSource()*/
            .get();
}

OR

String source = "{\"your_type\":{\"properties\":{\"your_field\":{\"type\":\"text\",\"fielddata\":true}}}}";
client.admin().indices().preparePutMapping("your_index)
        .setType("your_type")
        .setSource(source, XContentType.JSON)
        .get();

Result:

{
  "your_index": {
    "aliases": {},
    "mappings": {
      "your_type": {
        "properties": {
          ...
          ...
          "your_field": {
            "type": "text",
            "fielddata": true,
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          }
          ...
          ...
        }
      }
    }
  }
}

In Elasticsearch 5.0, String fields were broken into two - Text and Keyword. If the property is supposed to be Analyzed, you'd want to migrate your String fields to Text, if not then migrate them to Keyword.

Look into your type mapping - If you had a property like this -

{
  "your_field": {
    "type" "string",
    "index": "not_analyzed"
  }
}

You'd want to convert it to this -

{
  "your_field": {
    "type" "keyword",
    "index": true
  }
}

Similarly, if your property was supposed to be analyzed and you had it like this-

{
  "your_field": {
    "type" "string",
    "index": "analyzed"
  }
}

then you'd want to convert it to this-

{
  "your_field": {
    "type" "text",
    "index": true
  }
}

Details on Elasticsearch official page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!