本文只是一个springboot整合es的案例,es在版本控制上极差,每个大版本之间兼容性很差,api也很多不一样,所以我这里只是一个简单的demo。
项目结构:
1. 导入依赖
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.7.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <dependencies> <!--web--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--elasticsearch 整合 springboot两个依赖--> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.2.1</version> </dependency> <dependency> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> <version>7.2.1</version> </dependency> <!--添加fastjson依赖--> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.7</version> </dependency> </dependencies>
2. es配置类
import org.apache.http.HttpHost; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class EsConfig { @Bean(destroyMethod = "close") public RestHighLevelClient client() { return new RestHighLevelClient(RestClient.builder( new HttpHost("192.168.209.100", 9200, "http") )); } }
3. 没有整合mysql,这里直接准备好需要操作的数据
import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Random; public class User { private int id; private int age; private String name; private Date startTime; private Date endTime; public static List<User> getAll() { List<User> list = new ArrayList<User>(); try { Calendar no = Calendar.getInstance(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time = "2019-09-25 19:12:32"; User user = null; for(int i=1;i<11;i++) { no.setTime(format.parse(time)); no.set(Calendar.DATE, no.get(Calendar.DATE) -new Random().nextInt(15)); Date startTime = no.getTime(); no.set(Calendar.DATE, no.get(Calendar.DATE) +new Random().nextInt(30)); Date endTime = no.getTime(); user = new User(i, new Random().nextInt(100), "吴磊"+i, startTime, endTime); list.add(user); } } catch (Exception e) { } return list; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } public User(int id, int age, String name, Date startTime, Date endTime) { super(); this.id = id; this.age = age; this.name = name; this.startTime = startTime; this.endTime = endTime; } public User() { super(); } @Override public String toString() { return "User [id=" + id + ", age=" + age + ", name=" + name + ", startTime=" + startTime + ", endTime=" + endTime + "]"; } }
4. 编写操作es的javaApi
import java.io.IOException; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.elasticsearch.action.delete.DeleteRequest; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.get.GetRequest; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cglib.beans.BeanMap; import org.springframework.stereotype.Service; import com.alibaba.fastjson.JSONObject; import com.wulei.entity.User; @Service public class ESService { // 索引名称 (可以理解成数据库的表名) private static final String index_name = "user"; // es对象 @Autowired private RestHighLevelClient client; public int add() { int count = 0; try { // 从数据库拿到数据 List<User> list = User.getAll(); for(User u : list) { addIndex(u, String.valueOf(u.getId())); count += 1; } } catch (Exception e) { // TODO: handle exception } return count; } /** * 添加索引 * @param user * @param id * @throws IOException */ public void addIndex(User user, String id) throws IOException{ // 创建一个索引,指定文档id,source是文档内容 IndexRequest request = new IndexRequest(index_name).id(id).source(beanToMap(user)); IndexResponse response = client.index(request, RequestOptions.DEFAULT); System.out.println(response); } /** * 查询 * @param id * @return * @throws IOException */ public Object get(String id) throws IOException{ GetRequest getRequest = new GetRequest(index_name,id); GetResponse response = client.get(getRequest,RequestOptions.DEFAULT); Map<String, Object> source = response.getSource(); System.out.println(response); return JSONObject.toJSON(source); } /** * 删除 * @param id * @return * @throws IOException */ public boolean del(String id) throws IOException{ DeleteRequest request = new DeleteRequest(index_name,id); DeleteResponse res = client.delete(request, RequestOptions.DEFAULT); System.out.println(res); return true; } /** * 改 * @param id * @return * @throws IOException */ public boolean edit(User user,String id) throws IOException{ UpdateRequest request = new UpdateRequest(index_name,id).doc(beanToMap(user)); UpdateResponse name = client.update(request,RequestOptions.DEFAULT); System.out.println(name); return true; } /** * 条件搜索 * @param key * @param value * @return * @throws IOException */ public List<User> select(String key,String value,int start, int end,int type) throws IOException { // 指定索引,类似于数据库的表 SearchRequest searchRequest = new SearchRequest(index_name); // 创建查询对象,相当于写查询sql SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); if(type==1) { // matchQuery是模糊查询,会对key进行分词 searchSourceBuilder.query(QueryBuilders.matchQuery(key,value)); }else if(type==2) { // termQuery是精准查询 searchSourceBuilder.query(QueryBuilders.termQuery(key,value)); } // 指定从哪条开始查询 searchSourceBuilder.from(start); // 需要查出的总记录条数 searchSourceBuilder.size(end); searchRequest.source(searchSourceBuilder); SearchResponse response = client.search(searchRequest,RequestOptions.DEFAULT); System.out.println(JSONObject.toJSON(response)); SearchHit[] hits = response.getHits().getHits(); List<User> list = new LinkedList<>(); for(SearchHit hit: hits){ User user = JSONObject.parseObject(hit.getSourceAsString(),User.class); list.add(user); } return list; } /** * 对象转map * @param bean * @param <T> * @return */ public <T> Map<String, Object> beanToMap(T bean) { Map<String, Object> map = new HashMap<>(); if (bean != null) { BeanMap beanMap = BeanMap.create(bean); for (Object key : beanMap.keySet()) { if(beanMap.get(key) != null){ map.put(key + "", beanMap.get(key)); } } } return map; } }
5. 写测试接口
@RestController public class ESController { @Autowired private ESService service; @RequestMapping("/add") public int add() { return service.add(); } @RequestMapping("/get") public Object get(String id) throws IOException{ return service.get(id); } @RequestMapping("/getAll") public List<User> getAll() throws IOException{ List<User> list = new ArrayList<User>(); for(int i=1;i<11;i++) { Object json = service.get(String.valueOf(i)); list.add(JSONObject.parseObject(json.toString(), User.class)); } return list; } @RequestMapping("/del") public boolean del(String id) throws IOException{ return service.del(id); } @RequestMapping("/edit") public boolean edit(User user,String id) throws IOException{ return service.edit(user, id); } @RequestMapping("/select") public List<User> select(String key,String value,int start, int end,int type) throws IOException { return service.select(key, value, start, end, type); } }