使用java api配置elasticsearch映射

在索引之前,我有一些我不想分析的弹性搜索字段。 我已经读过,正确的方法是改变索引映射。 现在我的映射看起来像这样:

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

我希望它看起来像这样:

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

我一直试图通过改变设置

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

getGrantSettings()的位置如下:

 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; } 

我已成功使用Java API将映射应用于Elasticsearch索引,如下所示:

  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(); 

希望这可以帮助。

为未来的读者添加这个。 请注意,您需要在创建实际索引之前执行映射,否则您将获得exception。 请参阅以下代码。

 client.admin().indices().create(new CreateIndexRequest("indexname")).actionGet(); PutMappingResponse putMappingResponse = client.admin().indices() .preparePutMapping("indexname") .setType("indextype") .setSource(jsonBuilder().prettyPrint() .startObject() .startObject("indextype") .startObject("properties") .startObject("country").field("type", "string").field("index", "not_analyzed").endObject() .endObject() .endObject() .endObject()) .execute().actionGet(); IndexResponse response1 = client.prepareIndex("indexname", "indextype") .setSource(buildIndex()) .execute() .actionGet(); // Now "Sri Lanka" considered to be a single country :) SearchResponse response = client.prepareSearch("indexname" ).addAggregation(AggregationBuilders.terms("countryfacet").field("country")).setSize(30).execute().actionGet(); 

请仔细阅读权威指南 :

虽然您可以添加到现有映射,但无法更改现有字段映射。 如果字段已存在映射,则该字段中的数据可能已编入索引。 如果要更改字段映射,则索引数据将出错并且无法正确搜索。

资料来源: https : //www.elastic.co/guide/en/elasticsearch/guide/current/mapping-intro.html#updating-a-mapping

因此,您只需在创建字段时执行此操作。 这就是为什么这个答案的代码没有问题。

因此,弹性搜索文档在该主题上已经过时了。 not_analyzed不再存在,字符串现在是文本。 经过一些试验和错误,我想出了这个:

 CreateIndexRequest createIndexRequest = new CreateIndexRequest("yourIndexName"); XContentBuilder mapping = jsonBuilder() .startObject() .startObject("properties") .startObject("yourProperty") .field("type", "keyword") .endObject() .endObject() .endObject(); createIndexRequest.mapping("yourEntityName", mapping); client.indices().create(createIndexRequest); 

现在只需使用术语查询即可查询yourProperty的确切值。