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

本文介绍了如何在Elasticsearch中创建索引,包括将实体转换为JSON字符串的不同方法,如手写、使用Map、利用Elasticsearch的帮助类及jackson技术等。此外还详细解释了如何使用client.prepareIndex来创建索引。

        创建索引的第一步工作,是将你要创建索引的对象转化为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();
       

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值