翻譯水準有限,僅供參考
Java API [2.3] » Document APIs » Index API
Index API
Index API讓我們能夠把一個特定類型的JSON文檔索引到特定的index中,以供我們搜尋
産生JSON文檔
有四種方法産生一個JSON文檔:
1、利用位元組數組byte[]或字元數String手動産生
2、利用Map類型,Map類會自動轉換成内容相同的JSON
3、利用第三方庫來序列化實體,如jackson
4、利用内置的XContentFactory.jsonBuilder()
在ES内部,上面的方法都會轉換到位元組數組byte[]。是以,如果對象已經是位元組數組,直接使用即可。
jsonBuilder是一個高度優化的JSON産生器,能夠直接構造位元組數組byte
1、利用位元組數組byte[]或字元數String手動産生
下面這個例子中,需要注意把date手動編碼成日期格式
String json = "{" +
"\"user\":\"kimchy\"," +
"\"postDate\":\"2013-01-30\"," +
"\"message\":\"trying out Elasticsearch\"" +
"}";
2、利用Map類型,Map類會自動轉換成内容相同的JSON
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");
3、利用第三方庫來序列化實體,如jackson
ES已經使用了jackson,是以你可以用它來序列化實體
import com.fasterxml.jackson.databind.*;
// instance a json mapper
ObjectMapper mapper = new ObjectMapper(); // create once, reuse
// generate json
byte[] json = mapper.writeValueAsBytes(yourbeaninstance);
4、利用内置的XContentFactory.jsonBuilder()
ES提供了内置的助手來産生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和endArray來添加數組。而且,field()可以接受多種
對象類型,包括JSON。
如果你需要看JSON的内容,可以使用string()方法。
String json = builder.string();
建立索引
下面是一個例子,把一個JSON文檔索引到index為twitter,type為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();
你也可以利用String生成JSON建立索引,并不給定ID
String json = "{" +
"\"user\":\"kimchy\"," +
"\"postDate\":\"2013-01-30\"," +
"\"message\":\"trying out Elasticsearch\"" +
"}";
IndexResponse response = client.prepareIndex("twitter", "tweet")
.setSource(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();
// isCreated() is true if the document is a new one, false if it has been updated
boolean created = response.isCreated();
想看更多索引操作,可以看REST的index文檔
網頁連結https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-docs-index.html