一、生成JSON
建立索引的第一步是要把对象转换为JSON字符串
二、建立索引
把json文档写入索引
三、java完成新建一个Java项目
细致代码以下:
import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Date; import java.util.List; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.client.Client; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.common.xcontent.XContentBuilder; import cn.com.bropen.entity.DataFactory; import static org.elasticsearch.common.xcontent.XContentFactory.*; public class ElasticSearchHandler { public static void main(String[] args) { try { /* 建立客户端 */ // client startup Client client = TransportClient.builder().build() .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300)); List<String> jsonData = DataFactory.getInitJsonData(); for (int i = 0; i < jsonData.size(); i++) { IndexResponse response = client.prepareIndex("blog", "article").setSource(jsonData.get(i)).get(); if (response.isCreated()) { System.out.println("建立胜利!"); } } client.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
以上就是java中怎样建立索引的细致内容,更多请关注ki4网别的相干文章!