elasticsearch 创建索引,以及检索一条数据

elasticsearch的重要概念

我们可以把elasticsearch当做数据库来理解:

  • index:索引库名称,相当于关系型数据库中的表名,一个elasticsearch集群中可以有多个索引库。
  • type:索引库中索引数据类型,为索引类型,是用来区分同索引库下不同类型的数据的,一个索引库下可以有多个索引类型。
  • id:索引库中索引数据主键,唯一。

创建json document

elasticsearch有多种创建json document的方式

1. 手写,比如

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

2. 使用map

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

3. 序列化bean

For example,use jackson

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

然后我们可以使用jackson来序列化我们的bean

import com.fasterxml.jackson.databind.*;

// instance a json mapper
ObjectMapper mapper = new ObjectMapper(); // create once, reuse

// generate json
String json = mapper.writeValueAsString(yourbeaninstance);

4.使用elasticsearch的帮助类

Elasticsearch 提供帮助类来生成JSON.

import static org.elasticsearch.common.xcontent.XContentFactory.*;

XContentBuilder builder = jsonBuilder()
    .startObject()
        .field("user", "kimchy")
        .field("postDate", new Date())
        .field("message", "trying out Elasticsearch")
    .endObject()

创建索引

举个例子,比如索引名字叫blog,type是post,id为1

IndexResponse response = client.prepareIndex("blog", "post", "1")
                .setSource(XContentFactory.jsonBuilder().startObject()
                                .field("title", "test")
                                .field("content", "here is content")
                                .field("tag", "test")
                                .endObject()

                ).execute().actionGet();

如果我们不指定id,ES会为我们生成id,setSource方法有几种形式,可以传入json字符串,map等,差不多就是上面指出的几种形式
IndexResponse返回一些信息:

// Index name
String _index = response.getIndex();
// Type name
String _type = response.getType();
// Document ID (generated or not)
String _id = response.getId();
// Version (if it's the first time you index this document, you will get: 1)
long _version = response.getVersion();
//是否创建成功
boolean isCreated = response.isCreated()

检索一条记录

在创建索引时,我们根据IndexResponse,得到了index、type和id,检索一条记录的方法很简单,它可以用来判断指定index,type,id的索引是否存在

GetResponse getResponse = client.prepareGet("blog", "post","1")
                .execute()
                .actionGet();

GetResponse中常用的方法有isExists(),getSourceAsString()等,前者判断指定索引是否存在,后面用来得到返回的json。我们可以根据json反序列化得到我们要的对象

Post post = mapper.readValue(getResponse.getSourceAsString(),Post.class);
原文地址:https://www.cnblogs.com/hupengcool/p/4031543.html