@Test
public void batchAddIndex() throws IOException {
BulkRequestBuilder bulkRequest = client .prepareBulk();
bulkRequest.add( client .prepareIndex( “batch_test1” , “batch” , “1” )
.setSource( jsonBuilder ()
.startObject()
.field( “user” , “lzq” )
.field( “postDate” , new Date())
.field( “message” , “trying out Elasticsearch” )
.endObject()
)
);
bulkRequest.add( client .prepareIndex( “batch_test2” , “batch” , “2” )
.setSource( jsonBuilder ()
.startObject()
.field( “user” , “zx” )
.field( “postDate” , new Date())
.field( “message” , “another post” )
.endObject()
)
);
BulkResponse bulkResponse = bulkRequest.get();
if (bulkResponse.hasFailures()) {
System. out .println( “failures…:” +bulkResponse.buildFailureMessage()
);
}
}
如图所示:批量创建的两个索引,在es系统里面都可以找到,所以说明索引创建是成功的。
这里需要注意的是,索引的名称不能大写,必须是小写或者下划线之类的。还有buildFailureMessage函数返回的是批量操作错误的失败信息,hasFailures返回的是批量操作是否正确。
2.批量修改索引
/**
* 批量修改索引
* @throws IOException
*/
@Test
public void batchUpdateIndex() throws IOException {
BulkRequestBuilder bulkRequest = client .prepareBulk();
bulkRequest.add( client .prepareUpdate( “batch_test1” , “batch” , “1” ).setDoc( jsonBuilder ()
.startObject()
.field( “user” , “修改lzq” )
.field( “postDate” , new Date())
.field( “message” , “batch_test1被我修改了” )
.endObject()));
bulkRequest.add( client .prepareUpdate( “batch_test2” , “batch” , “2” ).setDoc( jsonBuilder ()
.startObject()
.field( “user” , “修改zx” )
.field( “postDate” , new Date())
.field( “message” , “batch_test1被我修改了” )
.endObject()));
BulkResponse bulkResponse = bulkRequest.get();
if (bulkResponse.hasFailures()) {
System. out .println( “failures…:” +bulkResponse.buildFailureMessage()
);
}
}
如图所示,表示批量修改已经成功。这边需要注意的是索引是什么类型的数据,修改的时候传入的数据类型就必须是什么类型的数据。
3.批量删除索引
/**
* 批量删除索引
* @throws IOException
*/
@Test
public void batchDeleteIndex() throws IOException {
BulkRequestBuilder bulkRequest = client .prepareBulk();
bulkRequest.add( client .prepareDelete( “batch_test1” , “batch” , “1” ));
bulkRequest.add( client .prepareDelete( “batch_test2” , “batch” , “2” ));
BulkResponse bulkResponse = bulkRequest.get();
= client .prepareBulk();
bulkRequest.add( client .prepareDelete( “batch_test1” , “batch” , “1” ));
bulkRequest.add( client .prepareDelete( “batch_test2” , “batch” , “2” ));
BulkResponse bulkResponse = bulkRequest.get();