gpt4 book ai didi

java - elasticsearch java api putmapping from json 文件错误

转载 作者:行者123 更新时间:2023-12-02 05:09:47 27 4
gpt4 key购买 nike

我正在尝试使用 Elasticsearch java api 动态创建映射。这很重要,因为我不想更改编译的代码来更改映射。

几乎所有示例都使用 XContentBuilder 来执行此操作,但我想使用文件中的 json 字符串。

代码:

client.admin().indices().preparePutMapping(indexName)
.setType("test")
.setSource(indexMapping)
.execute().actionGet();

文件字符串:

{
"test": {
"dynamic": "strict",
"_id": {
"path": "id"
},
"properties": {
"address": {
"index_analyzer": "ip4-pattern-analyzer",
"store": true,
"type": "string",
"fields": {
"raw": {
"index": "not_analyzed",
"type": "string"
}
}
}
}
}

}

Elasticsearch PutMappingRequest.class 抛出错误:

failed to generate simplified mapping definition

使用 XContentbuilder 定义的相同 json 可以完美运行。

String type = "test";
XContentBuilder jb = XContentFactory.jsonBuilder().
startObject().
startObject(type).
field("dynamic", "strict").
startObject("_id").
field("path", "id").
endObject().
startObject("_all").
field("enabled", "true").
endObject().
startObject("properties").
startObject("address").
field("type", "string").
field("store", "yes").
field("index_analyzer", "ip4-pattern-analyzer").
startObject("fields").
startObject("raw").
field("type","string").
field("index","not_analyzed").
endObject().
endObject().
endObject().
endObject().
endObject().
endObject();

最佳答案

尝试如下操作:

在applicationContext.xml中有类似的内容:

<bean id="indexMapping" class="org.apache.commons.io.IOUtils" factory-method="toString">
<constructor-arg value="classpath:test.json" type="java.io.InputStream" />
</bean>

然后你就可以做

   @Autowired
private String indexMapping;
.
.

要在索引创建期间应用映射,请尝试:

CreateIndexResponse indexResponse = admin.prepareCreate(indexName).setSource(indexMapping).execute().actionGet();

如果您想在之后应用映射,请尝试:

PutMappingRequest putRequest = new PutMappingRequest(indexName); 
putRequest.source(indexMapping);
putRequest.type("test");
try {
PutMappingResponse response = admin.putMapping(putRequest).actionGet();

} catch (Exception e) {
log.warn("Failed to add mapping", e);
throw new RuntimeException(e);
}

关于java - elasticsearch java api putmapping from json 文件错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27427613/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com