elasticsearch java API------批量添加索引
elasticsearch java API------批量添加索引
1.
public void bulkupdate(){
BulkRequestBuilder bulkRequest = client.prepareBulk();
try {
bulkRequest.add(client.prepareIndex("productindex", "productindex", "2")
.setSource(XContentFactory.jsonBuilder()
.startObject()
.field("user", "kimchy2")
.field("postDate", new Date())
.field("message", "trying out Elastic Search")
.endObject()
)
);
bulkRequest.add(client.prepareIndex("productindex", "productindex", "3")
.setSource(XContentFactory.jsonBuilder()
.startObject()
.field("user", "kimchy3")
.field("postDate", new Date())
.field("message", "another post")
.endObject()
)
);
BulkResponse bulkResponse = bulkRequest.execute().actionGet();
if (bulkResponse.hasFailures()) {
//处理错误
}
bulkRequest.request().requests().clear();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
2.
- public void testBulkIndex() throws Exception {
- NodeBuilder builder = NodeBuilder.nodeBuilder();
- String clusterName = PropertyManager.getContextProperty("cluster.name");
- builder.clusterName(clusterName);
- Node node = builder.node();
- Client client = node.client();
- ObjectMapper mapper = new ObjectMapper();
- List<Person> persons = new ArrayList<Person>();
- List<IndexRequest> requests = new ArrayList<IndexRequest>();
- for (int i = 0; i < 10; i++) {
- Person person = new Person();
- person.setAge(20 + i);
- person.setId(UUID.randomUUID().toString());
- person.setIsStudent(true);
- person.setName("张三" + i);
- person.setSex("男");
- persons.add(person);
- String index = "user"; // 相当于数据库名
- String type = "tb_person"; // 相当于表名
- String json = mapper.writeValueAsString(person);
- IndexRequest request = client
- .prepareIndex(index, type, person.getId()).setSource(json)
- .request();
- requests.add(request);
- }
- BulkRequestBuilder bulkRequest = client.prepareBulk();
- for (IndexRequest request : requests) {
- bulkRequest.add(request);
- }
- BulkResponse bulkResponse = bulkRequest.execute().actionGet();
- if (bulkResponse.hasFailures()) {
- Assert.fail("批量创建索引错误!");
- }
- }
已有 0 人发表留言,猛击->> 这里<<-参与讨论
ITeye推荐