本文集主要是总结自己在项目中使用ES 的经验教训,包括各种实战和调优。
/**
* 通过prepareIndex增加文档,参数为json字符串
*/
@Test
public void testIndexJson()
{
String source = "{\"name\":\"will\",\"age\":18}";
IndexResponse indexResponse = transportClient
.prepareIndex(index, type, "3").setSource(source).get();
System.out.println(indexResponse.getVersion());
}
/**
* 通过prepareIndex增加文档,参数为Map<String,Object>
*/
@Test
public void testIndexMap()
{
Map<String, Object> source = new HashMap<String, Object>(2);
source.put("name", "Alice");
source.put("age", 16);
IndexResponse indexResponse = transportClient
.prepareIndex(index, type, "4").setSource(source).get();
System.out.println(indexResponse.getVersion());
}
/**
* 通过prepareIndex增加文档,参数为javaBean
*
* @throws ElasticsearchException
* @throws JsonProcessingException
*/
@Test
public void testIndexBean() throws ElasticsearchException, JsonProcessingException
{
Student stu = new Student();
stu.setName("Fresh");
stu.setAge(22);
ObjectMapper mapper = new ObjectMapper();
IndexResponse indexResponse = transportClient
.prepareIndex(index, type, "5").setSource(mapper.writeValueAsString(stu)).get();
System.out.println(indexResponse.getVersion());
}
/**
* 通过prepareIndex增加文档,参数为XContentBuilder
*
* @throws IOException
* @throws InterruptedException
* @throws ExecutionException
*/
@Test
public void testIndexXContentBuilder() throws IOException, InterruptedException, ExecutionException
{
XContentBuilder builder = XContentFactory.jsonBuilder()
.startObject()
.field("name", "Avivi")
.field("age", 30)
.endObject();
IndexResponse indexResponse = transportClient
.prepareIndex(index, type, "6")
.setSource(builder)
.execute().get();
//.execute().get();和get()效果一样
System.out.println(indexResponse.getVersion());
}
网友评论