您的位置:首页 > 其它

分布式搜索Elasticsearch——创建索引

2013-05-09 18:44 357 查看
创建索引的第一步工作,是将你要创建索引的对象转化为Json字符串。

生成Json的方法很多,最直接的是手写,将你的实体转化为Json:

String json = "{" +
""user":"kimchy"," +
""postDate":"2013-01-30"," +
""message":"trying out Elastic Search"," +
"}";


第二种,是使用Map方式:

Map<String, Object> json = new HashMap<String, Object>();
json.put("user","kimchy");
json.put("postDate",new Date());
json.put("message","trying out Elastic Search");


第三种,是使用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技术,你可以导入jackson的jar包,如果是maven管理的项目,则直接在pom.xml中添加:

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.1.3</version>
</dependency>


然后:

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的参数可以是0个(其后必须使用index(String)和type(String)方法),两个(client.prepareIndex(index,type))和三个(client.prepareIndex(index,type,id)),其中,index类似于数据库名,type类似于表名,而id则是每条记录的惟一编码,通常情况下,我们会把实体的惟一编码作为ES的ID,当然,不给的时候,由ES自动生成。

response是Elasticsearch创建完成索引后,回馈给你的实体,你可以从这个实体中获得一些有价值的信息:

// 索引名称
String _index = response.index();
// type名称
String _type = response.type();
// 文档ID
String _id = response.id();
// 索引版本
long _version = response.version();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: