1、先创建客户端对象
2、创建索引的5种方法
第一种: 插入json格式的索引数据
@Test
public void createIndex(){//定义json字符串
String json = “{” +
“”user”:”kimchy”,” +
“”postDate”:”2013-01-30″,” +
“”message”:”travelying out Elasticsearch”” +
“}” ;//创建索引,设置索引名称、索引类型以及索引id
IndexResponse indexResponse = client . prepareIndex ( “myindex1” , “article” , “1” ). setSource (json, XContentType. JSON ) //传入json数据源
.get();
//关闭
client .close();
}
第二种:使用map创建索引
@Test
public void index2() throws Exception {//先创建hashmap对象
HashMap<String, String> jsonMap = new HashMap<String, String>();//设置HashMap的值
jsonMap.put( “name” , “zhangsan” );
jsonMap.put( “sex” , “1” );
jsonMap.put( “age” , “18” );
jsonMap.put( “address” , “bj” );//创建索引,设置索引名称、索引类型和id
IndexResponse indexResponse = client . prepareIndex ( “myindex1” , “article” , “2” )
. setSource (jsonMap) //传入hashmap对象
.get();
client .close();
}
第三种:XcontentBuilder实现创建索引
@Test
public void index3() throws IOException {//创建索引,设置索引名称、索引类型和id
IndexResponse indexResponse = client. prepareIndex (“myindex1”, “article”, “3”)
. setSource (new XContentFactory ().jsonBuilder()
. startObject ()
. field (“name”, “lisi”)
.field(“age”, “18”)
.field(“sex”, “0”)
.field(“address”, “bj”)
. endObject ())
.get();
client.close();
}
第四种:将java对象转换为json格式字符串进行创建索引
需先创建pojo对象Person类;(此处略)
@Test
public void objToIndex(){
Person person = new Person();
person.setAge( 18 );
person.setId( 20 );
person.setName( “张三丰” );
person.setAddress( “武当山” );
person.setEmail( “zhangsanfeng@163.com” );
person.setPhone( “18588888888” );
person.setSex( 1 );
String json = JSONObject . toJSONString (person);
System. out .println(json);
client . prepareIndex ( “myindex1” , “article” , “32” ). setSource (json,XContentType. JSON ).get();
client .close();
}
第五种:批量创建索引
@Test
public void index4() throws IOException {//创建对象
BulkRequestBuilder bulk = client . prepareBulk();//批量添加索引到该对象中
bulk. add ( client . prepareIndex (“myindex1”, “article”, “4”)
.setSource(new XContentFactory(). jsonBuilder ()
.startObject()
.field(“name”, “wangwu”)
.field(“age”, “18”)
.field(“sex”, “0”)
.field(“address”, “bj”)
.endObject()));
bulk.add( client .prepareIndex(“news”, “article”, “5”)
.setSource(new XContentFactory(). jsonBuilder ()
.startObject()
.field(“name”, “zhaoliu”)
.field(“age”, “18”)
.field(“sex”, “0”)
.field(“address”, “bj”)
.endObject()));
BulkResponse bulkResponse = bulk.get();
System. out .println(bulkResponse);
client .close();
}