ElasticSearch6.X版本Java Api中文详解(一)之Index Api解析

Inde API允许将类型化JSON文档索引到特定索引中,并使其可搜索。

生成JSON文档有几种不同的方法:

1.手动(也就是自己使用)使用本机字节[]或作为字符串。

2.使用将自动转换为其JSON等效的映射。

3.使用第三方库序列化您的bean,如Jackson。

4.使用内置的助手XContentFactory.jsonBuilder()

在内部,每个类型转换为byte[](因此一个字符串被转换为一个字节[])。因此,如果对象已经在这个表单中,那么就使用它。jsonBuilder是高度优化的JSON生成器,它直接构造一个字节[]。

这里没有什么真正困难的,但是注意您必须按照日期格式编码日期。

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

使用Map

Map是一个键:值对集合。它表示一个JSON结构:

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

序列化你beans

您可以使用Jackson将您的beans序列化为JSON。请将Jackson Databind添加到您的项目中。然后,您可以使用ObjectMapper来序列化您的bean.

import com.fasterxml.jackson.databind.*;

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

// generate json
byte[] json = mapper.writeValueAsBytes(yourbeaninstance);

使用Elasticsearch helpers

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

注意,您还可以使用startArray(String)和endArray()方法添加数组。顺便说一下,字段方法接受许多对象类型。您可以直接通过数字、日期甚至其他XContentBuilder对象。

如果需要查看生成的JSON内容,可以使用string()方法。

String json = builder.string();
下面的示例将一个JSON文档索引为一个名为twitter的索引,其类型为tweet, id为1:
import static org.elasticsearch.common.xcontent.XContentFactory.*;

IndexResponse response = client.prepareIndex("twitter", "tweet", "1")
        .setSource(jsonBuilder()
                    .startObject()
                        .field("user", "kimchy")
                        .field("postDate", new Date())
                        .field("message", "trying out Elasticsearch")
                    .endObject()
                  )
        .get();

请注意,您还可以将文档作为JSON字符串进行索引,而不必给出ID:

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

IndexResponse response = client.prepareIndex("twitter", "tweet")
        .setSource(json, XContentType.JSON)
        .get();
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();
// status has stored current instance statement.
RestStatus status = response.status();

仅供参考。

猜你喜欢

转载自blog.csdn.net/zhou_shaowei/article/details/80046144