我正在创建一个新索引,然后映射json数据
CreateIndexRequest request = new CreateIndexRequest("demoreport");
request.mapping(
"{\n" +
" \"properties\": {\n" +
" \"Identifier code\": {\n" +
" \"type\": \"char(3)\"\n" +
" },\n" +
" \"User ID\": {\n" +
" \"type\": \"char(38)\"\n" +
" },\n" +
" }\n" +
"}",XContentType.JSON);
HttpPost post = new HttpPost("http://localhost:9200/demoreport/_doc/5");
我的JSON文件:
[
{
"IDENTIFIER_CD": "PT ",
"USER_ID": "123458
}
{
"IDENTIFIER_CD": "SR ",
"USER_ID": "12345678
}
]
我收到错误提示:
java.lang.IllegalArgumentException:映射源必须是一对字段名称和属性定义。
这里是完整的代码:在这里,我试图将数据库生成的Json文件发布到elasticsearch服务器。
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
public class MyScheduler {
public static void send() {
CreateIndexRequest request = new CreateIndexRequest("kibanareport");
request.settings(Settings.builder()
.put("index.number_of_shards", 20)
.put("index.number_of_replicas", 10)
);
request.mapping(
"{\n" +
" \"properties\": {\n" +
" \"user_ID\": {\n" +
" \"type\": \"text\"\n" +
" },\n" +
" \"doc_ID\": {\n" +
" \"type\": \"text\"\n" +
" },\n" +
" }\n" +
"}", XContentType.JSON);
Map<String, Object> message = new HashMap<>();
message.put("type", "text");
Map<String, Object> properties = new HashMap<>();
properties.put("message", message);
Map<String, Object> mapping = new HashMap<>();
mapping.put("properties", properties);
XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject();
{
builder.startObject("properties");
{
builder.startObject("message");
{
builder.field("type", "text");
}
builder.endObject();
}
builder.endObject();
}
builder.endObject();
String fileName = "downloads/JSONFile.json";
File jsonFile = new File(fileName);
HttpEntity entity = new FileEntity(jsonFile);
HttpPost post = new
HttpPost("http://localhost:9200/kibanareport/_doc");
post.setEntity(entity);
HttpClient client = new DefaultHttpClient();
post.addHeader("content-type", "application/json");
post.addHeader("Accept", "application/json");
HttpResponse response = client.execute(post);
System.out.println("Response: " + response);
}
}
您在CreateIndexRequest
中使用的数据类型char(3)是错误的。请参阅此Elasticsearch文档以获取Elasticsearch https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-types.html
当前用于您的映射,因为text
是字符串,所以Identifier code
数据类型是字符串,Integer
字段是User ID
。您可以根据需要进行更改。
这里,是更新的CreateIndexRequest
:
CreateIndexRequest request = new CreateIndexRequest("demoreport");
request.mapping(
"{\n" +
" \"properties\": {\n" +
" \"Identifier code\": {\n" +
" \"type\": \"text\"\n" +
" },\n" +
" \"User ID\": {\n" +
" \"type\": \"integer\"\n" +
" }\n" +
" }\n" +
"}",XContentType.JSON);