分布式搜索 Elasticsearch —— 创建索引、检索一条记录

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);

 

转载于:https://my.oschina.net/exit/blog/805988

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值