大数据技术之Elasticsearch-Java API操作(一)API基本操作

新建文档(源数据es构建器添加json

1)源代码

@Test

public void createIndex() throws Exception {

 

// 1 通过es自带的帮助类,构建json数据

XContentBuilder builder = XContentFactory.jsonBuilder().startObject().field("id", 3).field("title", "基于Lucene的搜索服务器").field("content", "它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。")

.endObject();

 

// 2 创建文档

IndexResponse indexResponse = client.prepareIndex("blog", "article", "3").setSource(builder).get();

 

// 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代码:

// 四、新建文档--使用es
    @Test
    public void createDocByXContent() throws Exception {
        // 源数据es构建器添加json
        XContentBuilder builder = XContentFactory.jsonBuilder().startObject().field("id", 3)
                .field("title", "基于Lucene的搜索服务器").field("content", "它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口").endObject();
        // 创建文档
        // 注意:这里没有传第三个数-ID,但是ES依然会自动产生ID的
        IndexResponse indexResponse = client.prepareIndex("blog", "article").setSource(builder).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