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

ElasticSearch(6)--使用Java客户端创建索引和映射

2018-02-07 09:34 423 查看
手动创建映射(包含创建映射和文档):

package com.es.querydemo;

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

import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.client.Requests;
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.es.bean.Product;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
* 查询
*
* @author Beck
* @date 2018年2月6日
*/
public class TestESQuery {
private static final String HOST = "127.0.0.1";
private static final int PORT = 9300;

private static final String INDEX = "eshop";
private static final String TYPE = "product";

private static final ObjectMapper MAPPER = new ObjectMapper();

private TransportClient client = null;

// 创建索引
private void createIndex(){
this.client.admin().indices().prepareCreate(INDEX).get();
}

// 删除索引
private void deleteIndex(){
this.client.admin().indices().prepareDelete(INDEX).get();
}

// 新增一个文档
private void createDocument() throws JsonProcessingException{
Product product = new Product();
product.setId(5);
product.setTitle("三星(SAMSUNG)UA78KU6900JXXZ 78英寸 曲面 4K 超高清 智能电视 黑色");

String source = MAPPER.writeValueAsString(product);
// 新增
this.client.prepareIndex(INDEX, TYPE).setSource(source).get();
}

// 创建映射
private void createMapping() throws Exception{
// 配置映射关系
Map<String,Object> mappings = new HashMap<>();

Map<String,Object> type = new HashMap<>();
mappings.put(TYPE, type);
type.put("dynamic", false);

Map<String,Object> properties = new HashMap<>();
type.put("properties", properties);

// 文档的id映射
Map<String,Object> idProperties = new HashMap<>();
idProperties.put("type", "integer");
idProperties.put("store", "yes");
properties.put("id", idProperties);

// 文档的title映射
Map<String,Object> titleProperties = new HashMap<>();
titleProperties.put("type", "string");
titleProperties.put("store", "yes");
titleProperties.put("analyzer", "ik");
properties.put("title", titleProperties);

String json = MAPPER.writeValueAsString(mappings);
System.out.println(json);

PutMappingRequest request = Requests.putMappingRequest(INDEX).type(TYPE).source(json);
this.client.admin().indices().putMapping(request).get();
}
@Test
public void execute(){
try {
createDocument();
} catch (Exception e) {
e.printStackTrace();
}
}

// 获取客户端
@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();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: