编辑
索引API允许将类型化的JSON文档索引到特定索引中并使其可搜索。
生成JSON文档
编辑
使用native byte []或String作为手动(也就是自己动手)
使用将自动转换为其JSON等效项的Map
使用第三方库序列化您的bean,例如Jackson
使用内置帮助器XContentFactory.jsonBuilder()
在内部,每种类型都转换为byte [](因此String转换为byte [])。 因此,如果对象已经是这种形式,那么使用它。 jsonBuilder是高度优化的JSON生成器,可直接构造byte []。
这里没什么难的,但请注意,您必须根据日期格式对日期进行编码。
String json = "{" + "\"user\":\"kimchy\"," + "\"postDate\":\"2013-01-30\"," + "\"message\":\"trying out Elasticsearch\"" + "}";
Map是关键:值对集合。 它代表一个JSON结构:
Mapjson = new HashMap (); json.put("user","kimchy"); json.put("postDate",new Date()); json.put("message","trying out Elasticsearch");
您可以使用Jackson将bean序列化为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提供内置帮助程序来生成JSON内容。
import static org.elasticsearch.common.xcontent.XContentFactory.*; XContentBuilder builder = XContentFactory.jsonBuilder() .startObject() .field("user", "kimchy") .field("postDate", new Date()) .field("message", "trying out Elasticsearch") .endObject()
请注意,您还可以使用startArray(String)和endArray()方法添加数组。 顺便说一下,field方法接受许多对象类型。 您可以直接传递数字,日期甚至其他XContentBuilder对象。
如果需要查看生成的JSON内容,可以使用string()方法。
以下示例将一个JSON文档索引到名为twitter的索引中,该索引名为tweet,id为1:
import static org.elasticsearch.common.xcontent.XContentFactory.*; IndexResponse response = client.prepareIndex("twitter", "tweet", "1") .setSource(XContentFactory.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) .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();