大数据技术之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();
    }

结果:

 

 

 

 

 

 

 

博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3