分布式搜索Elasticsearch——创建索引
2013-05-09 18:44
357 查看
创建索引的第一步工作,是将你要创建索引的对象转化为Json字符串。
生成Json的方法很多,最直接的是手写,将你的实体转化为Json:
第二种,是使用Map方式:
第三种,是使用Elasticsearch提供的帮助类
第四种是使用jackson技术,你可以导入jackson的jar包,如果是maven管理的项目,则直接在pom.xml中添加:
然后:
接下来便可以创建索引了:
client.prepareIndex的参数可以是0个(其后必须使用index(String)和type(String)方法),两个(client.prepareIndex(index,type))和三个(client.prepareIndex(index,type,id)),其中,index类似于数据库名,type类似于表名,而id则是每条记录的惟一编码,通常情况下,我们会把实体的惟一编码作为ES的ID,当然,不给的时候,由ES自动生成。
response是Elasticsearch创建完成索引后,回馈给你的实体,你可以从这个实体中获得一些有价值的信息:
生成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();
相关文章推荐
- 分布式搜索Elasticsearch——批量创建索引
- 分布式搜索Elasticsearch——创建客户端(二)
- 分布式搜索Elasticsearch——创建客户端(三)
- 开源分布式搜索平台ELK(Elasticsearch+Logstash+Kibana)入门学习资源索引
- [搜索]ElasticSearch Java Api(一) -创建索引
- 分布式搜索Elasticsearch——创建客户端(四)
- 分布式搜索Elasticsearch——创建客户端(六)
- 开源分布式搜索平台ELK(Elasticsearch+Logstash+Kibana)入门学习资源索引
- 分布式搜索Elasticsearch——删除指定索引
- 分布式搜索Elasticsearch——创建客户端(五)
- 分布式搜索Elasticsearch——创建客户端(一)
- 开源分布式搜索平台ELK(Elasticsearch+Logstash+Kibana)入门学习资源索引
- (转)开源分布式搜索平台ELK(Elasticsearch+Logstash+Kibana)入门学习资源索引
- 分布式搜索Elasticsearch——QueryBuilders.matchPhrasePrefixQuery
- 分布式搜索Elasticsearch——检索一条记录
- 分布式搜索Elasticsearch——集成paoding-maping
- 分布式搜索Elasticsearch——配置
- 分布式搜索Elasticsearch——项目过程(二)
- 分布式搜索Elasticsearch——配置
- elasticsearch api 创建索引