如题,在spring web工程中如何集成 elasticsearch 呢 ?
(参考github项目 : https://github.com/spring-projects/spring-data-elasticsearch)
一、spring.xml 中引入 spring-elasticsearch.xml
<!-- spring-elasticsearch.xml引入 --> <import resource="classpath:spring-elasticsearch.xml"/>
二、spring-elasticsearch.xml 配置
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:cache="http://www.springframework.org/schema/cache" xmlns:mongo="http://www.springframework.org/schema/data/mongo" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.3.xsd"> <bean id="transportClient" class="com.tingcream.hplusAdmin.extension.elasticsearch.TransportClientFactoryBean"> <property name="clusterName" value="${elasticsearch.clusterName}"/> <property name="clusterNodes" value="${elasticsearch.clusterNodes}"/> </bean> </beans>TransportClientFactoryBean.java
public class TransportClientFactoryBean implements FactoryBean<TransportClient>, InitializingBean, DisposableBean { private static final Logger logger = Logger.getLogger(TransportClientFactoryBean.class); private String clusterNodes = "127.0.0.1:9300";//可以使用逗号分隔多个节点地址 private String clusterName = "elasticsearch"; private Boolean clientTransportSniff = true; private Boolean clientIgnoreClusterName = Boolean.FALSE; private String clientPingTimeout = "5s"; private String clientNodesSamplerInterval = "5s"; private TransportClient client; private Properties properties; static final String COLON = ":";//分号 static final String COMMA = ",";//逗号 @Override public void destroy() throws Exception { try { logger.info("Closing elasticSearch client"); if (client != null) { client.close(); } } catch (final Exception e) { logger.error("Error closing ElasticSearch client: ", e); } } @Override public TransportClient getObject() throws Exception { return client; } @Override public Class<TransportClient> getObjectType() { return TransportClient.class; } @Override public boolean isSingleton() { return false; } @Override public void afterPropertiesSet() throws Exception { buildClient(); } protected void buildClient() throws Exception { client = new PreBuiltTransportClient(settings()); Assert.hasText(clusterNodes, "[Assertion failed] clusterNodes settings missing."); for (String clusterNode : StringUtils.split(clusterNodes, COMMA)) { String hostName = StringUtils.substringBeforeLast(clusterNode, COLON); String port = StringUtils.substringAfterLast(clusterNode, COLON); Assert.hasText(hostName, "[Assertion failed] missing host name in 'clusterNodes'"); Assert.hasText(port, "[Assertion failed] missing port in 'clusterNodes'"); logger.info("adding transport node : " + clusterNode); client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(hostName), Integer.valueOf(port))); } client.connectedNodes(); } private Settings settings() { if (properties != null) { return Settings.builder().put(properties).build(); } return Settings.builder() .put("cluster.name", clusterName) .put("client.transport.sniff", clientTransportSniff) .put("client.transport.ignore_cluster_name", clientIgnoreClusterName) .put("client.transport.ping_timeout", clientPingTimeout) .put("client.transport.nodes_sampler_interval", clientNodesSamplerInterval) .build(); } public void setClusterNodes(String clusterNodes) { this.clusterNodes = clusterNodes; } public void setClusterName(String clusterName) { this.clusterName = clusterName; } public void setClientTransportSniff(Boolean clientTransportSniff) { this.clientTransportSniff = clientTransportSniff; } public String getClientNodesSamplerInterval() { return clientNodesSamplerInterval; } public void setClientNodesSamplerInterval(String clientNodesSamplerInterval) { this.clientNodesSamplerInterval = clientNodesSamplerInterval; } public String getClientPingTimeout() { return clientPingTimeout; } public void setClientPingTimeout(String clientPingTimeout) { this.clientPingTimeout = clientPingTimeout; } public Boolean getClientIgnoreClusterName() { return clientIgnoreClusterName; } public void setClientIgnoreClusterName(Boolean clientIgnoreClusterName) { this.clientIgnoreClusterName = clientIgnoreClusterName; } public void setProperties(Properties properties) { this.properties = properties; } }
三、 elasticsearch.properties 属性配置
elasticsearch.clusterName=myES elasticsearch.clusterNodes=192.168.1.140:9300
四、pom.xml配置
五、如何使用org.elasticsearch.client transport 5.5.2
@Resource 注入TransportClient tranportClient即可。
@Resource private TransportClient transportClient;
六、elasticsearch基础CRUD封装
ElasticSearchBaseDao.java
/** * elasticsearch 底层CRUD封装dao * @author jelly */ @Component public class ElasticSearchBaseDao { @Resource private TransportClient transportClient ; /** * 索引一个对象 * @param index 索引名称 * @param type 索引类型 * @param id 文档id 可为null, put方式需指定文档id,post无须指定id,服务器自动生成 * @param o * @return String * @author jelly * */ publicString index(String index,String type,String id ,T o){ IndexResponse res=transportClient.prepareIndex(index, type, id).setSource(JSON.toJSONString(o), XContentType.JSON).get(); return res.toString(); } /** * 根据id 查询一个对象 * @param index * @param type * @param id * @param entityClass * @return T * @author jelly * */ public T findById(String index,String type,String id, Class entityClass){ GetResponse res= transportClient.prepareGet(index, type, id).execute().actionGet(); return JSON.parseObject(res.getSourceAsString(), entityClass) ; } /** * 根据id 删除一个对象 * @param index * @param type * @param id * @return String * @author jelly * */ public String deleteById(String index,String type,String id ){ DeleteResponse res = transportClient.prepareDelete(index, type, id).execute().actionGet(); return res.toString(); } /** * 更新一个对象 * @param index * @param type * @param id * @param o * @return * @return String * @author jelly * */ public String update(String index,String type, String id , T o){ UpdateResponse res= transportClient.prepareUpdate(index, type, id).setDoc(JSON.toJSONString(o), XContentType.JSON).get(); return res.toString(); } /** * 查询所有 * @param index * @param type * @param entityClass * @return List * @author jelly * */ public List findAll(String index,String type,Class entityClass){ SearchRequestBuilder srb=transportClient.prepareSearch(index).setTypes(type); SearchResponse sr=srb.setQuery(QueryBuilders.matchAllQuery()) .execute() .actionGet(); SearchHits hits=sr.getHits(); List list =new ArrayList (); for(SearchHit hit:hits){ T o= JSON.parseObject(hit.getSourceAsString(), entityClass); list.add(o); } return list ; } /** * 查询所有分页 * @param index * @param type * @param page * @param entityClass * @return * @return List * @author jelly * */ public List findAllByPage(String index,String type,Page page ,Class entityClass){ SearchRequestBuilder srb=transportClient.prepareSearch(index).setTypes(type); SearchResponse sr=srb.setQuery(QueryBuilders.matchAllQuery()) .setFrom(page.getStartNum()) .setSize(page.getPageSize()) .execute() .actionGet(); SearchHits hits=sr.getHits(); List list =new ArrayList (); for(SearchHit hit:hits){ T o= JSON.parseObject(hit.getSourceAsString(), entityClass); list.add(o); } return list ; } /** * 查询所有 分页排序 * @param index * @param type * @param page * @param entityClass * @return * @return List * @author jelly * */ public List findAllByPageSort(String index,String type,Page page,Class entityClass){ SearchRequestBuilder srb=transportClient.prepareSearch(index).setTypes(type); SearchResponse sr=null; if(page.getSortOrder().equalsIgnoreCase("asc")){//升序 sr=srb.setQuery(QueryBuilders.matchAllQuery()) .addSort(page.getSortName(), SortOrder.ASC) .setFrom(page.getStartNum()) .setSize(page.getPageSize()) .execute() .actionGet(); }else { sr=srb.setQuery(QueryBuilders.matchAllQuery()) .addSort(page.getSortName(), SortOrder.DESC) //降序 .setFrom(page.getStartNum()) .setSize(page.getPageSize()) .execute() .actionGet(); } SearchHits hits=sr.getHits(); List list =new ArrayList (); for(SearchHit hit:hits){ T o= JSON.parseObject(hit.getSourceAsString(), entityClass); list.add(o); } return list ; } /** * 查询 包含指定列 * @param index * @param type * @param page * @param fields * @param entityClass * @return List * @author jelly * */ public List findIncludeFieldByPage(String index,String type,Page page,String[] fields, Class entityClass){ SearchRequestBuilder srb=transportClient.prepareSearch(index).setTypes(type); SearchRequestBuilder builder = srb.setQuery(QueryBuilders.matchAllQuery()) .setFrom(page.getStartNum()) .setSize(page.getPageSize()) .setFetchSource(fields, null); // includes excludes String sortName =page.getSortName(); String sortOrder =page.getSortOrder(); if(sortName!=null && !sortName.equals("")&& sortOrder!=null && !sortOrder.equals("")){ if(sortOrder.equalsIgnoreCase("asc")){ builder.addSort(sortName, SortOrder.ASC); }else{ builder.addSort(sortName, SortOrder.DESC); } } SearchResponse sr = builder.execute().actionGet(); SearchHits hits=sr.getHits(); List list =new ArrayList (); for(SearchHit hit:hits){ T o= JSON.parseObject(hit.getSourceAsString(), entityClass); list.add(o); } return list ; } /** * 查询 排除指定列 * @param index * @param type * @param page * @param fields * @param entityClass * @return List */ public List findExcludeFieldByPage(String index,String type,Page page,String[] fields, Class entityClass){ SearchRequestBuilder srb=transportClient.prepareSearch(index).setTypes(type); SearchRequestBuilder builder = srb.setQuery(QueryBuilders.matchAllQuery()) .setFrom(page.getStartNum()) .setSize(page.getPageSize()) .setFetchSource(null, fields); // includes excludes String sortName =page.getSortName(); String sortOrder =page.getSortOrder(); if(sortName!=null && !sortName.equals("")&& sortOrder!=null && !sortOrder.equals("")){ if(sortOrder.equalsIgnoreCase("asc")){ builder.addSort(sortName, SortOrder.ASC); }else{ builder.addSort(sortName, SortOrder.DESC); } } SearchResponse sr = builder.execute().actionGet(); SearchHits hits=sr.getHits(); List list =new ArrayList (); for(SearchHit hit:hits){ T o= JSON.parseObject(hit.getSourceAsString(), entityClass); list.add(o); } return list ; } /** * 关键字搜索 * @param index * @param type * @param page * @param includes * @param field * @param keyword * @param analyzer * @param entityClass * @return List * @author jelly * */ public List searchByFieldKeyword(String index,String type,Page page ,String[] includes, String field,String keyword,String analyzer ,Class entityClass) { SearchRequestBuilder srb=transportClient.prepareSearch(index).setTypes(type); SearchRequestBuilder builder = srb.setQuery(QueryBuilders.matchQuery(field,keyword) .analyzer(analyzer)) .setFrom(page.getStartNum()) .setSize(page.getPageSize()) .setFetchSource(includes, null); // includes excludes SearchResponse sr = builder.execute().actionGet(); SearchHits hits=sr.getHits(); List list =new ArrayList (); for(SearchHit hit:hits){ T o= JSON.parseObject(hit.getSourceAsString(), entityClass); list.add(o); } return list ; } }
over ~~
Copyright © 叮叮声的奶酪 版权所有
备案号:鄂ICP备17018671号-1