ElasticSearch 6.3版本 Java APIs之Index API

Index API

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


生成JSON文档

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

  • 使用本机byte[]或作为一个手动(也就是你自己)String
  • 使用Map它将自动转换为其JSON等效项
  • 使用第三方库序列化您的bean,例如Jackson
  • 使用内置帮助器XContentFactory.jsonBuilder()

在内部,每种类型都转换为byte[](因此String转换为a byte[])。因此,若对象已是这种形式,那么使用它。JSONBuilder是一个高度优化的JSON生成器,可以直接构建一个byte[]。


自己动手

注意,必须根据日期格式对日期进行编码。

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


使用地图

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


序列化您的bean

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

import com.fasterxml.jackson.databind。*;

//实例一个JSON映射器
ObjectMapper mapper = new ObjectMapper(); //创建一次,重用

//生成JSON
byte [] json = mapper.writeValueAsBytes(yourbeaninstance);


使用Elasticsearch帮助程序编辑

Elasticsearch提供内置帮助程序来生成JSON内容。

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

XContentBuilder builder = jsonBuilder()
.startObject()
.field(“用户”,“kimchy”)
.field(“postDate”,new Date())
.field(“message”,“试用Elasticsearch”)
.endObject()

注意,你还可以使用startArray(字符串)和endArray()方法添加数组。顺便说一下,该字段方法接受许多对象类型,你可以直接传递数字,日期甚至其他XContentBuilder对象。

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

import org.elasticsearch.common.Strings;

String json = Strings.toString(builder);


索引文档

以下示例将一个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对象会给你一个报告:

//索引名称
String _index = response.getIndex();
//输入名称
String _type = response.getType();
//文档ID(生成与否)
String _id = response.getId();
//版本(如果这是您第一次索引此文档,您将获得:1)
long _version = response.getVersion();
// status已存储当前实例语句。
RestStatus status = response.status();

猜你喜欢

转载自blog.csdn.net/qingmou_csdn/article/details/80977730