1、创建索引
要将索引的对象转换成JSON字符串。
生成JSON方法很多,拼接或者其他,我们着重点使用 Elasticsearch 提供的帮助类:
import static org.elasticsearch.common.xcontent.XContentFactory.*;
XContentBuilder builder = jsonBuilder()
.startObject()
.field("user", "kimchy")
.field("postDate", new Date())
.field("message", "trying out Elastic Search")
.endObject();
String json = builder.string();
使用jackson生成json
import com.fasterxml.jackson.databind.*;
// instance a json mapper
ObjectMapper mapper = new ObjectMapper(); // create once, reuse
// generate json
String json = mapper.writeValueAsString(yourbeaninstance);
下面创建索引
IndexResponse response = client.prepareIndex("twitter", "tweet")
.setSource(json)
.execute()
.actionGet();
client.prepareIndex() 的参数 index类似于数据库名,type类似于表名,而id相当于每条记录的唯一编码,通常情况下我们会把实体的唯一编码作为 ES的ID,当然,也可以由 ES 自动生成
- 无参数 ,那么(其后必须使用 index(String) 和 type(String) 方法);
- 两个参数(client.prepareIndex(index,type) );
- 三个参数 ( client.prepareIndex(index,type,id) );
response 是 Elasticsearch 创建完索引后,返回给应用的相应,可以从中获取有价值的信息:
//索引名称
String _index = response.index();
//type 名称
String _type = response.type();
//文档ID
String _id = response.id();
//索引版本
long _version = response.version();
2、检索一条记录
在 创建索引中我们可以获取到 创建完索引的 index 、type、id、version;
那么我们在获取一条记录也很简单
GetResponse getResponse = client.prepareGet(index, type, id).execute().actionGet();
那么,在Get得到Response后,也使用Jackson将Json字符串转化为你的实体:
Person newPerson = mapper.readValue(getResponse.getSourceAsString(), Person.class);