您的位置:首页 > 编程语言 > Java开发

ElasticSearch(2)--使用Java客户端创建文档

2018-02-05 19:40 337 查看
创建maven工程:

引入依赖:

<dependencies>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- Jackson Json处理工具包 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.2</version>
</dependency>
</dependencies>
创建文档(没有映射创建,自动创建索引

映射):

package com.es.demo;

import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;

import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.fasterxml.jackson.databind.ObjectMapper;

public class TestES {
private static final String HOST = "127.0.0.1";
private static final int PORT = 9300;

private static final ObjectMapper MAPPER = new ObjectMapper();
private TransportClient client = null;

// 创建文档,数据源使用的是json
@Test
public void createDocumentByJson() throws Exception{
Map<String, Object> source = new HashMap<String,Object>();
source.put("name", "APPLE手机");
source.put("price", 13999);

// 也可以转化java的bean
String json = MAPPER.writeValueAsString(source);
IndexResponse response = this.client.prepareIndex("eshop", "product")
.setSource(json)
.execute()
.actionGet();

// 获取结果
String index = response.getIndex();
String type = response.getType();
String id = response.getId();
long version = response.getVersion();
boolean created = response.isCreated();

System.out.println("索引是: " + index);
System.out.println("类型是: " + type);
System.out.println("文档id是: " + id);
System.out.println("版本是: " + version);
System.out.println("是否创建: " + created);
}

// 创建文档,数据源使用的是map
@Test
public void createDocumentByMap(){
Map<String, Object> source = new HashMap<String,Object>();
source.put("name", "华为手机");
source.put("price", 3999);
IndexResponse response = this.client.prepareIndex("eshop", "product")
.setSource(source)
.execute()
.actionGet();

// 获取结果
String index = response.getIndex();
String type = response.getType();
String id = response.getId();
long version = response.getVersion();
boolean created = response.isCreated();

System.out.println("索引是: " + index);
System.out.println("类型是: " + type);
System.out.println("文档id是: " + id);
System.out.println("版本是: " + version);
System.out.println("是否创建: " + created);
}

// 获取客户端
@Before
public void getClient() throws Exception{
client = TransportClient.builder()
.build()
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(HOST), PORT));
}

// 关闭客户端
@After
public void closeClient(){
if (this.client != null){
this.client.close();
}
}
}查看插入的结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: