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

Elasticsearch5.3 用JAVA创建索引

2017-06-30 19:46 567 查看
                                                                            创建索引1,首先我们要有已经搭建好的Elasticsearch 并且是没问题的!废话不多说直接上代码了
import com.google.gson.Gson;import org.elasticsearch.action.index.IndexRequestBuilder;import org.elasticsearch.action.index.IndexResponse;import org.elasticsearch.client.transport.TransportClient;import org.elasticsearch.common.settings.Settings;import org.elasticsearch.common.transport.InetSocketTransportAddress;import org.elasticsearch.rest.RestStatus;import org.elasticsearch.transport.client.PreBuiltTransportClient;import org.junit.After;import org.junit.Before;import org.junit.Test;import java.io.IOException;import java.net.InetAddress;import java.net.UnknownHostException;import java.util.HashMap;import java.util.Map;//import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;/*** Created by 启才 on 2017/4/25.*/public class BookRepositoryTest {TransportClient client;@Beforepublic void setup() throws UnknownHostException {System.out.println("create TransportClient...");client = new PreBuiltTransportClient(Settings.EMPTY).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("....."), 9300));}@Afterpublic void clearup() {System.out.println("close TransportClient...");if (client != null) {client.close();}}@Testpublic void doIndex() throws IOException {Gson gson = new Gson();Map map = new HashMap();map.put("title", "hello test");map.put("description", "你好世界");map.put("price", 25.3);map.put("onSale", "asdasdasda");map.put("type", "testtypesssss");map.put("createDate", "2017.0000");String json = gson.toJson(map);IndexRequestBuilder indexRequestBuilder = client.prepareIndex("wang", "test", "10").setSource(json);IndexResponse response = indexRequestBuilder.get();// Index nameString _index = response.getIndex();// Type nameString _type = response.getType();// Document ID (generated or not)String _id = response.getId();// Version (if it's the first time you index this document, you will get: 1)long _version = response.getVersion();// status has stored current instance statement.RestStatus status = response.status();}}我们会发现这种创建方式与其他版本的创建方式有那么一点不同,尤其是创建client的时候!并不是所有的创建方式都是一样的!创建完成后我们可以通过kibana来查看过几天我还会有ES的 JAVA API 的各种查询希望能帮助大家!
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: