概要:
1.使用Eclipse搭建Elasticsearch详情参考下面链接
3.ElasticSearch Java Api(一) -添加数据创建索引
转载:http://blog.csdn.net/napoay/article/details/51707023
ElasticSearch JAVA API官网文档:https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-docs-index.html
创建索引的第一步是要把对象转换为JSON字符串.官网给出了四种创建JSON文档的方法:
1 String json = "{" +
2 "\"user\":\"kimchy\"," +
3 "\"postDate\":\"2013-01-30\"," +
4 "\"message\":\"trying out Elasticsearch\"" +
5 "}";
手写方式很简单,但是要注意日期格式:Date Formate
集合是key:value数据类型,可以代表json结构.
1 Map<String, Object> json = new HashMap<String, Object>();
2 json.put("user","kimchy");
3 json.put("postDate","2013-01-30");
4 json.put("message","trying out Elasticsearch");
ElasticSearch已经使用了jackson,可以直接使用它把javabean转为json.
1 // instance a json mapper
2 ObjectMapper mapper = new ObjectMapper(); // create once, reuse
3
4 // generate json
5 byte[] json = mapper.writeValueAsBytes(yourbeaninstance);
1 import static org.elasticsearch.common.xcontent.XContentFactory.*;
2
3 XContentBuilder builder = jsonBuilder()
4 .startObject()
5 .field("user", "kimchy")
6 .field("postDate", new Date())
7 .field("message", "trying out Elasticsearch")
8 .endObject()
9
10 String json = builder.string();
下面的例子把json文档写入所以,索引库名为twitter、类型为tweet,id为1:
1 import static org.elasticsearch.common.xcontent.XContentFactory.*;
2
3 IndexResponse response = client.prepareIndex("twitter", "tweet", "1")
4 .setSource(jsonBuilder()
5 .startObject()
6 .field("user", "kimchy")
7 .field("postDate", new Date())
8 .field("message", "trying out Elasticsearch")
9 .endObject()
10 )
11 .get();
也可以直接传人JSON字符串:
1 String json = "{" +
2 "\"user\":\"kimchy\"," +
3 "\"postDate\":\"2013-01-30\"," +
4 "\"message\":\"trying out Elasticsearch\"" +
5 "}";
6
7 IndexResponse response = client.prepareIndex("twitter", "tweet")
8 .setSource(json)
9 .get();
可以调用response对象的方法获取返回信息:
1 // 索引名称
2 String _index = response.getIndex();
3 // 类型名称
4 String _type = response.getType();
5 // 文档id
6 String _id = response.getId();
7 // 版本(if it's the first time you index this document, you will get: 1)
8 long _version = response.getVersion();
9 // 是否被创建is true if the document is a new one, false if it has been updated
10 boolean created = response.isCreated();
更简单的可以直接System.out.println(response)
查看返回信息.
新建一个java项目,导入elasticsearch-2.3.3/lib目录下的jar文件.新建一个Blog类:
1 package com.cn.test.exaple1;
2
3 public class Blog {
4
5 private Integer id;
6 private String title;
7 private String posttime;
8 private String content;
9
10 public Blog() {
11 }
12
13 public Blog(Integer id, String title, String posttime, String content) {
14 this.id = id;
15 this.title = title;
16 this.posttime = posttime;
17 this.content = content;
18 }
19
20 public Integer getId() {
21 return id;
22 }
23
24 public void setId(Integer id) {
25 this.id = id;
26 }
27
28 public String getTitle() {
29 return title;
30 }
31
32 public void setTitle(String title) {
33 this.title = title;
34 }
35
36 public String getPosttime() {
37 return posttime;
38 }
39
40 public void setPosttime(String posttime) {
41 this.posttime = posttime;
42 }
43
44 public String getContent() {
45 return content;
46 }
47
48 public void setContent(String content) {
49 this.content = content;
50 }
51
52
53 }
创建java实体类转json工具类:
1 package com.cn.test.exaple1;
2
3 import java.io.IOException;
4
5 import org.elasticsearch.common.xcontent.XContentBuilder;
6 import org.elasticsearch.common.xcontent.XContentFactory;
7
8 /**
9 * @ClassName: JsonUtil
10 * @Description: java实体类转json工具类
11 * @author JinXing
12 * @date 2017年12月1日 下午1:48:25
13 *
14 */
15 public class JsonUtil {
16
17 // Java实体对象转json对象
18 public static String model2Json(Blog blog) {
19 String jsonData = null;
20 try {
21 XContentBuilder jsonBuild = XContentFactory.jsonBuilder();
22 jsonBuild.startObject().field("id", blog.getId()).field("title", blog.getTitle())
23 .field("posttime", blog.getPosttime()).field("content",blog.getContent()).endObject();
24
25 jsonData = jsonBuild.string();
26 System.out.println(jsonData);
27
28 } catch (IOException e) {
29 e.printStackTrace();
30 }
31
32 return jsonData;
33 }
34
35 }
添加数据,返回一个list:
1 package com.cn.test.exaple1;
2
3 import java.util.ArrayList;
4 import java.util.List;
5
6 /**
7 * @ClassName: DataFactory
8 * @Description: 添加数据,返回一个list:
9 * @author JinXing
10 * @date 2017年12月1日 下午3:08:02
11 *
12 */
13 public class DataFactory {
14
15 public static DataFactory dataFactory = new DataFactory();
16
17 private DataFactory() {
18 }
19
20 public DataFactory getInstance() {
21 return dataFactory;
22 }
23
24 //List 数据集
25 public static List<String> getInitJsonData() {
26 List<String> list = new ArrayList<String>();
27 String data1 = JsonUtil.model2Json(new Blog(1, "git简介", "2016-06-19", "SVN与Git最主要的区别..."));
28 String data2 = JsonUtil.model2Json(new Blog(2, "Java中泛型的介绍与简单使用", "2016-06-19", "学习目标 掌握泛型的产生意义..."));
29 String data3 = JsonUtil.model2Json(new Blog(3, "SQL基本操作", "2016-06-19", "基本操作:CRUD ..."));
30 String data4 = JsonUtil.model2Json(new Blog(4, "Hibernate框架基础", "2016-06-19", "Hibernate框架基础..."));
31 String data5 = JsonUtil.model2Json(new Blog(5, "Shell基本知识", "2016-06-19", "Shell是什么..."));
32 list.add(data1);
33 list.add(data2);
34 list.add(data3);
35 list.add(data4);
36 list.add(data5);
37 return list;
38 }
39
40 }
创建索引、添加数据:
1 package com.cn.test.exaple1;
2
3 import java.io.IOException;
4 import java.net.InetAddress;
5 import java.net.UnknownHostException;
6 import java.util.List;
7
8 import org.elasticsearch.action.index.IndexResponse;
9 import org.elasticsearch.client.Client;
10 import org.elasticsearch.client.transport.TransportClient;
11 import org.elasticsearch.common.transport.InetSocketTransportAddress;
12
13 public class ElasticSearchHandler {
14
15 public static void main(String[] args) {
16 try {
17 /* 创建客户端 */
18 // client startup
19 Client client = TransportClient.builder().build()
20 .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
21
22 //数据源
23 List<String> jsonData = DataFactory.getInitJsonData();
24
25 for (int i = 0; i < jsonData.size(); i++) {
26
27 //JSON文档写入索引,索引库名为blog、类型为article
28 IndexResponse response = client.prepareIndex("blog", "article")
29 //写入JSON字符串
30 .setSource(jsonData.get(i)).get();
31 if (response.isCreated()) {//是否被创建is true if the document is a new one, false if it has been updated
32 System.out.println("创建成功!");
33 }
34 }
35
36 client.close();
37 } catch (UnknownHostException e) {
38 e.printStackTrace();
39 } catch (@SuppressWarnings("hiding") IOException e) {
40 e.printStackTrace();
41 }
42
43 }
44
45
46 }
查看插入的数据:
下面的插件为谷歌sense插件,下载参考地址:http://www.cnplugins.com/search/context-sense/download.html