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

创建maven工程:

引入依赖:


		
			org.elasticsearch
			elasticsearch
			2.4.0
		
		
			junit
			junit
			4.12
		
		
		
			com.fasterxml.jackson.core
			jackson-databind
			2.4.2
		
	

创建文档(没有映射创建,自动创建索引 映射):

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 source = new HashMap();
		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 source = new HashMap();
		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();
		}
	}
}
查看插入的结果:

ElasticSearch(2)--使用Java客户端创建文档_第1张图片



你可能感兴趣的:(ElasticSearch)