Elasticsearch-Java API操作(一)API基本操作(5)【新建文档(源数据json串-不推荐)】
Posted on 2020-08-14 23:11 MissRong 阅读(155) 评论(0) 收藏 举报大数据技术之Elasticsearch-Java API操作(一)API基本操作
新建文档(源数据json串-不推荐)
当直接在ElasticSearch建立文档对象时,如果索引不存在的,默认会自动创建,映射采用默认方式。
1)源代码
|
@Test public void createIndexByJson() throws UnknownHostException {
// 1 文档数据准备 String json = "{" + "\"id\":\"1\"," + "\"title\":\"基于Lucene的搜索服务器\"," + "\"content\":\"它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口\"" + "}";
// 2 创建文档 IndexResponse indexResponse = client.prepareIndex("blog", "article", "1").setSource(json).execute().actionGet();
// 3 打印返回的结果 System.out.println("index:" + indexResponse.getIndex()); System.out.println("type:" + indexResponse.getType()); System.out.println("id:" + indexResponse.getId()); System.out.println("version:" + indexResponse.getVersion()); System.out.println("result:" + indexResponse.getResult());
// 4 关闭连接 client.close(); } |
2)结果查看

********自己操作********
Java代码:
// 二、新建文档--使用json
@Test
public void createDocByJson() {
// 使用json创建Document
String json = "{" + "\"id\":\"1\"," + "\"title\":\"基于Lucene的搜索服务器\","
+ "\"content\":\"它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口\"" + "}";
// 创建文档
// 注意:这里面的参数id-"1"是ES的ID,和上面的"id"-Json串里的id 不是一个ID
IndexResponse indexResponse = client.prepareIndex("blog", "article", "1").setSource(json).execute().actionGet();
// 打印返回结果
System.out.println("index:" + indexResponse.getIndex());
System.out.println("type:" + indexResponse.getType());
System.out.println("id:" + indexResponse.getId());
System.out.println("version:" + indexResponse.getVersion());
System.out.println("result:" + indexResponse.getResult());
// 关闭连接
client.close();
}
结果:



浙公网安备 33010602011771号