首页 > 代码库 > 4:elasticsearch服务实现
4:elasticsearch服务实现
import java.util.List; import java.util.Map; import org.elasticsearch.action.bulk.BulkRequestBuilder; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.delete.DeleteRequestBuilder; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.action.update.UpdateRequestBuilder; import org.elasticsearch.client.Client; import org.elasticsearch.index.engine.DocumentMissingException; import org.elasticsearch.index.engine.VersionConflictEngineException; public class IIndexServiceIml implements IIndexService<SearchBean> { @Override public boolean insertOne(SearchBean t) { // TODO Auto-generated method stub try { Client client = ClientHelper.getClient(); IndexRequestBuilder inserter = client.prepareIndex(t.getIndexName(),t.getType(),t.getId()); inserter.setSource(SearchBeanUtil.toInsertMap(t)); inserter.execute().actionGet(); return true; } catch (Exception e) { // TODO: handle exception } return false; } @Override public boolean insertList(List<SearchBean> lists) { try { Client client = ClientHelper.getClient(); BulkRequestBuilder bulk = new BulkRequestBuilder(client); for (SearchBean b : lists) { IndexRequestBuilder inserter = client.prepareIndex(b.getIndexName(), b.getType(),b.getId()); inserter.setSource(SearchBeanUtil.toInsertMap(b)); bulk.add(inserter); } BulkResponse actionGet = bulk.execute().actionGet(); if (actionGet.hasFailures()) { return false; } return true; } catch (Exception e) { } return false; } @Override public boolean deleteOne(SearchBean t) { Client client = ClientHelper.getClient(); try { DeleteRequestBuilder deleter = client.prepareDelete(t.getIndexName(), t.getType(),t.getId()); DeleteResponse actionGet = deleter.execute().actionGet(); if (!actionGet.isFound()) { return true; } } catch (Exception e) { return false; } return true; } @Override public boolean deleteList(List<SearchBean> lists) { try { Client client = ClientHelper.getClient(); BulkRequestBuilder bulk = new BulkRequestBuilder(client); for (SearchBean t : lists) { DeleteRequestBuilder deleter = client.prepareDelete(t.getIndexName(), t.getType(),t.getId()); bulk.add(deleter); } BulkResponse actionGet = bulk.execute().actionGet(); if (actionGet.hasFailures()) { return false; } return true; } catch (Exception e) { } return false; } @Override public boolean updateOne(SearchBean t) { Client client = ClientHelper.getClient(); try { client.prepareUpdate(t.getIndexName(),t.getType(), t.getId()) .setId( t.getId()).setDoc(SearchBeanUtil.toUpdateMap(t)).execute() .actionGet(); return true; } catch (DocumentMissingException e) {// 文档不存在,直接返回true e.printStackTrace(); return true; } catch (VersionConflictEngineException e) { } catch (Exception e) { e.printStackTrace(); } return false; } @Override public boolean udateList(List<SearchBean> lists) { try { Client client = ClientHelper.getClient(); BulkRequestBuilder bulk = new BulkRequestBuilder(client); for (SearchBean t : lists) { UpdateRequestBuilder update=client.prepareUpdate(t.getIndexName(),t.getType(), t.getId()) .setId( t.getId()).setDoc(SearchBeanUtil.toUpdateMap(t)); bulk.add(update); } BulkResponse actionGet = bulk.execute().actionGet(); if (actionGet.hasFailures()) { return false; } return true; } catch (Exception e) { } return false; } @Override public List search(String jsonQuery, String indexName, int page, int size) { try { int start = page < 1 ? 0 : (page - 1) * size; Client client = ClientHelper.getClient(); SearchResponse response = client .prepareSearch(indexName) .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) .setQuery(jsonQuery).setFrom(start).setSize(size) .setExplain(false).execute().actionGet(); return SearchBeanUtil.buildSearchSource(response.getHits()); } catch (Exception e) { } return null; } @Override public List searchField(String jsonQuery, String indexName, int page,int size, String... fields) { try { int start = page < 1 ? 0 : (page - 1) * size; Client client = ClientHelper.getClient(); SearchRequestBuilder request = client .prepareSearch(indexName) .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) .setQuery(jsonQuery).setFrom(start).setSize(size); for (String field : fields) { request.addField(field); } SearchResponse response = request.setExplain(false).execute().actionGet(); return SearchBeanUtil.buildSearchFields(response.getHits()); } catch (Exception e) { } return null; } @Override public boolean checkDocExisted(String indexName,String type,String id) { try { Client client = ClientHelper.getClient(); GetResponse response = client .prepareGet(indexName,type,id) .execute().actionGet(); boolean result = response.isExists(); return result; } catch (Exception e) { return false; } } @Override public boolean updateFields(String id, String indexName, String type,String script, Map<String, Object> maps) { boolean fa=false; try { Client client = ClientHelper.getClient(); UpdateRequest resuest=new UpdateRequest(indexName, type,id); resuest.script(script); resuest.scriptParams(maps); client.update(resuest).actionGet(); fa=true; } catch (Exception e) { fa=false; } return fa; } } public class SearchBean { public SearchBean(String indexName, String type, String id) { super(); this.indexName = indexName; this.type = type; this.id = id; } private String indexName;//索引名称 private String type;//索引类型 private String id;//索引ID private String name; private String password; public String getIndexName() { return indexName; } public void setIndexName(String indexName) { this.indexName = indexName; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; public class SearchBeanUtil { /** * 根据filedName获取get方法 * * @param fildeName * @return * @throws Exception */ private static String getMethodName(String fildeName) throws Exception { byte[] items = fildeName.getBytes(); if (((char) items[0]) >= ‘a‘ && ((char) items[0]) <= ‘z‘) { items[0] = (byte) ((char) items[0] - 32); } return new String(items); } public static Map<String, Object> toUpdateMap(SearchBean bean) { Class<?> type = bean.getClass(); Map<String, Object> returnMap = new HashMap<String, Object>(); try { Field[] fields = type.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { Field filed = fields[i]; String filedName = filed.getName(); if (!filedName.equals("serialVersionUID")) { Method m = type.getMethod("get" + getMethodName(filedName)); Object val = m.invoke(bean); if (val != null) { returnMap.put(filedName, val); } } } } catch (Exception e) { } return returnMap; } public static Map<String,Object> toInsertMap(SearchBean bean){ Map<String, Object> returnMap = new HashMap<String, Object>(); try { Class<?> type = bean.getClass(); BeanInfo beanInfo = Introspector.getBeanInfo(type); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (int i = 0; i < propertyDescriptors.length; i++) { PropertyDescriptor descriptor = propertyDescriptors[i]; String propertyName = descriptor.getName(); if (!propertyName.equals("class")) { Method readMethod = descriptor.getReadMethod(); Object result = readMethod.invoke(bean); returnMap.put(propertyName, result); } } } catch (Exception e) { // TODO: handle exception } return returnMap; } public static List buildSearchSource(SearchHits result){ List<Map<String, Object>> lists=new ArrayList<>(); for(SearchHit hit:result.getHits()){ lists.add(hit.getSource()); } return lists; } public static List buildSearchFields(SearchHits result){ List<Map<String, Object>> lists=new ArrayList<>(); for(SearchHit hit:result.getHits()){ Map<String, Object> map=new HashMap<>(); for(String key:hit.getFields().keySet()){ map.put(key, hit.getFields().get(key)); } lists.add(map); } return lists; } public static void main(String[] args){ SearchBean bean =new SearchBean("index", "user", "sss"); Map<String, Object> returnMap = toUpdateMap(bean); System.out.println(returnMap); } }
本文出自 “陈砚羲” 博客,请务必保留此出处http://chenyanxi.blog.51cto.com/4599355/1575265
4:elasticsearch服务实现
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。