ElasticSearch JAVA API
一、生成JSON
建立索引的第一步是要把對象轉換為JSON字元串.官網給出了四種建立JSON文檔的方法:
1.1手寫方式生成
String json = "{" +
"\"user\":\"kimchy\"," +
"\"postDate\":\"2013-01-30\"," +
"\"message\":\"trying out Elasticsearch\"" +
"}";
手寫方式很簡單,但是要注意日期格式:Date Formate
1.2使用集合
集合是key:value資料類型,可以代表json結構.
Map<String, Object> json = new HashMap<String, Object>();
json.put("user","kimchy");
json.put("postDate","2013-01-30");
json.put("message","trying out Elasticsearch");
1.3使用JACKSON序列化
ElasticSearch已經使用了jackson,可以直接使用它把javabean轉為json.
// instance a json mapper
ObjectMapper mapper = new ObjectMapper(); // create once, reuse
// generate json
byte[] json = mapper.writeValueAsBytes(yourbeaninstance);
1.4使用ElasticSearch 幫助類
import static org.elasticsearch.common.xcontent.XContentFactory.*;
XContentBuilder builder = jsonBuilder()
.startObject()
.field("user", "kimchy")
.field("postDate", new Date())
.field("message", "trying out Elasticsearch")
.endObject()
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字元串:
String json = "{" +
"\"user\":\"kimchy\"," +
"\"postDate\":\"--\"," +
"\"message\":\"trying out Elasticsearch\"" +
"}";
IndexResponse response = client.prepareIndex("twitter", "tweet")
.setSource(json)
.get();
可以調用response對象的方法擷取傳回資訊:
// 索引名稱
String _index = response.getIndex();
// 類型名稱
String _type = response.getType();
// 文檔id
String _id = response.getId();
// 版本(if it's the first time you index this document, you will get: )
long _version = response.getVersion();
// 是否被建立is true if the document is a new one, false if it has been updated
boolean created = response.isCreated();
更簡單的可以直接
System.out.println(response)
檢視傳回資訊.
三、java實作
建立一個java項目,導入elasticsearch-2.3.3/lib目錄下的jar檔案.建立一個Blog類:
public class Blog {
private Integer id;
private String title;
private String posttime;
private String content;
public Blog() {
}
public Blog(Integer id, String title, String posttime, String content) {
this.id = id;
this.title = title;
this.posttime = posttime;
this.content = content;
}
//setter and getter
}
建立java實體類轉json工具類:
import java.io.IOException;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
public class JsonUtil {
// Java實體對象轉json對象
public static String model2Json(Blog blog) {
String jsonData = null;
try {
XContentBuilder jsonBuild = XContentFactory.jsonBuilder();
jsonBuild.startObject().field("id", blog.getId()).field("title", blog.getTitle())
.field("posttime", blog.getPosttime()).field("content",blog.getContent()).endObject();
jsonData = jsonBuild.string();
//System.out.println(jsonData);
} catch (IOException e) {
e.printStackTrace();
}
return jsonData;
}
}
添加資料,傳回一個list:
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class DataFactory {
public static DataFactory dataFactory = new DataFactory();
private DataFactory() {
}
public DataFactory getInstance() {
return dataFactory;
}
public static List<String> getInitJsonData() {
List<String> list = new ArrayList<String>();
String data1 = JsonUtil.model2Json(new Blog(, "git簡介", "2016-06-19", "SVN與Git最主要的差別..."));
String data2 = JsonUtil.model2Json(new Blog(, "Java中泛型的介紹與簡單使用", "2016-06-19", "學習目标 掌握泛型的産生意義..."));
String data3 = JsonUtil.model2Json(new Blog(, "SQL基本操作", "2016-06-19", "基本操作:CRUD ..."));
String data4 = JsonUtil.model2Json(new Blog(, "Hibernate架構基礎", "2016-06-19", "Hibernate架構基礎..."));
String data5 = JsonUtil.model2Json(new Blog(, "Shell基本知識", "2016-06-19", "Shell是什麼..."));
list.add(data1);
list.add(data2);
list.add(data3);
list.add(data4);
list.add(data5);
return list;
}
}
建立索引、添加資料:
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.List;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import static org.elasticsearch.common.xcontent.XContentFactory.*;
public class ElasticSearchHandler {
public static void main(String[] args) {
try {
/* 建立用戶端 */
// client startup
Client client = TransportClient.builder().build()
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), ));
List<String> jsonData = DataFactory.getInitJsonData();
for (int i = ; i < jsonData.size(); i++) {
IndexResponse response = client.prepareIndex("blog", "article").setSource(jsonData.get(i)).get();
if (response.isCreated()) {
System.out.println("建立成功!");
}
}
client.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
檢視插入的資料:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsICM2gzMwUjMzITOxYDM2EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
2016.12.12 日更新
使用5.X版本的移步到這裡:Elasticsearch 5.0下Java API使用指南