In fact, this blog online a large, why also write out this blog?
Online examples are based on the elasticsearch2.x version, not the 5.x version, and there are many are wrong, take it is not directly used to test, there is spring-data no corresponding 5.x version, out of consideration, so use spring boot 2.x to do a demo, share it. If there are errors, please note.
The specific code URL Githup:https://github.com/growup818/springboot-es-search
Actual combat:
ES data Configuration Class
Package Org.githup.es.config;import Java.net.inetaddress;import Org.elasticsearch.client.transport.transportclient;import Org.elasticsearch.common.settings.settings;import Org.elasticsearch.common.transport.inetsockettransportaddress;import Org.elasticsearch.transport.client.prebuilttransportclient;import Org.slf4j.logger;import Org.slf4j.loggerfactory;import Org.springframework.beans.factory.disposablebean;import Org.springframework.beans.factory.factorybean;import Org.springframework.beans.factory.initializingbean;import Org.springframework.beans.factory.annotation.value;import org.springframework.context.annotation.Configuration /** * Data configuration, initialization operation * * @author SDC * */@Configurationpublic class Esconfiguration implements FACTORYBEAN<TRANSPORTCLI Ent>, Initializingbean, Disposablebean {private static final Logger Logger = Loggerfactory.getlogger (esconfiguratio N.class); /** * ES cluster address */@Value ("${elasticsearch.ip}") Private String hostName; /** * Port */@Value ("${elasticsearch.port}") private String port; /** * Cluster Name */@Value ("${elasticsearch.cluster.name}") Private String clustername; /** * Connection Pool */@Value ("${elasticsearch.pool}") Private String poolsize; Private Transportclient client; @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 {try {//config information SEttings essetting = Settings.builder (). Put ("Cluster.name", clustername). Put ("Client.transport.sniff", true)//increase sniffer mechanism , locate the ES cluster. put ("Thread_pool.search.size", Integer.parseint (poolsize))//increase the number of thread pools, temporarily set to 5 . build (); Client = new Prebuilttransportclient (essetting); Inetsockettransportaddress inetsockettransportaddress = new Inetsockettransportaddress (InetAddress.getByName ( HostName), integer.valueof (port)); Client.addtransportaddresses (inetsockettransportaddress); } catch (Exception e) {logger.error ("Elasticsearch transportclient Create Error!!!", e); } }}
DAO layer, data layer, additions and deletions for simple data encapsulation
Package Org.githup.es.dao;import Java.util.map;import Java.util.uuid;import Org.elasticsearch.action.admin.indices.create.createindexresponse;import Org.elasticsearch.action.admin.indices.delete.deleteindexresponse;import Org.elasticsearch.action.admin.indices.exists.indices.indicesexistsrequest;import Org.elasticsearch.action.admin.indices.exists.indices.indicesexistsresponse;import Org.elasticsearch.action.delete.deleteresponse;import Org.elasticsearch.action.get.getrequestbuilder;import Org.elasticsearch.action.get.getresponse;import Org.elasticsearch.action.index.indexresponse;import Org.elasticsearch.action.update.updaterequest;import Org.elasticsearch.action.update.updateresponse;import Org.elasticsearch.client.transport.transportclient;import Org.slf4j.logger;import Org.slf4j.LoggerFactory;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.component;import com.alibaba.fastjson.jsonobject;/** * ES operation data Class * * Note: Some of the operations of ES have been encapsulated to extract someOperation is the traditional DAO layer, data service * * @author SDC * */@Componentpublic class Esrepository {private static final Logger log = Loggerfa Ctory.getlogger (Esrepository.class); @Autowired private Transportclient client; /** * CREATE INDEX * * @param index * @return */public boolean buildindex (String index) {if (!isin Dexexist (Index)) {Log.info ("index is not exits!"); } createindexresponse Buildindexresponse = Client.admin (). Indices (). Preparecreate (Index). Execute (). Actionget (); Log.info ("Flag to create INDEX:" + buildindexresponse.isacknowledged ()); return buildindexresponse.isacknowledged (); }/** * Delete index * * @param index * @return */public boolean deleteindex (String index) {if (!isindexexist (Index)) {log.info ("Index does not exist!!!!!!"); } deleteindexresponse Diresponse = Client.admin (). Indices (). Preparedelete (Index). Execute (). Actionget (); if (diresponse.isacknowledged ()) { Log.info ("Delete Index * * Success * * index->>>>>>>" + index); } else {log.info ("Delete Index * * Failed * * index->>>>>" + index); } return diresponse.isacknowledged (); /** * Query Data * @param index Index <-----> relational database * @param type <-----> Relational datasheet * @param ID number According to id<----->id * * @return * * Public map<string, object> searchdatabyparam (string index, String type, S Tring ID) {if (index = = NULL | | type = = NULL | | id = = NULL) {Log.info ("Unable to query data, missing unique value!!!!!!!"); return null; }//To get query data information getrequestbuilder Getrequestbuilder = client.prepareget (index, type, id); GetResponse GetResponse = Getrequestbuilder.execute (). Actionget (); There is also a specified time to get the return value of the information, if there is a special need can return Getresponse.getsource (); }/** * Update data * @param data added in JSON format * @param index Index <-----> relational database * @param type class Type <-----> Relational Data Sheet * @param ID Data id<----->id * @return */public void Updatedatabyid (jsonobject data, String index, STR ing type, String ID) {if (index = = NULL | | type = = NULL | | id = = NULL) {Log.info ("Unable to update data, missing unique value!!!!!!! "); Return }//Update step updaterequest up = new Updaterequest (); Up.index (Index). Type (type). ID (ID). doc (data); Get the response information//.actionget (Timeoutmillis), you can also use this method, when a certain time has not been the return value, it will automatically return. Updateresponse response = client.update (UP). Actionget (); Log.info ("Update data status information, status{}", Response.Status (). GetStatus ()); }/** * Add data * @param data added in JSON format * @param index Index <-----> relational database * @param type class Type <-----> Relational Data sheet * @param ID data id<----->id * @return */public String Addtargetdataall (jsonobj ECT data, string index, String type, string id) {//Determine if the next ID is empty, if NULL, set an ID if (id = = NULL) {id = Uuid.randomuuid (). tostrING (); }//Formally add data in indexresponse response = Client.prepareindex (index, type, id). SetSource (data). get (); Log.info ("Addtargetdataall Add Data status: {}", Response.Status (). GetStatus ()); return Response.getid (); /** * Delete data by ID * * @param index index, similar database * @param type, similar to table * @param ID Data ID */Publ IC void Deldatabyid (string index, String type, string id) {if (index = = NULL | | type = = NULL | | id = NULL) { Log.info ("Unable to delete data, missing unique value!!!!!!!"); Return }//Start deleting data deleteresponse response = Client.preparedelete (index, type, id). Execute (). Actionget (); Log.info ("Delete data state, status-->>>>{},", Response.Status (). GetStatus ()); }/** * Determines if an index exists * * @param index * @return */public boolean isindexexist (String index) { Indicesexistsresponse IEP = Client.admin (). Indices (). Exists (new Indicesexistsrequest (Index)). Actionget (); if (iep.isexIsts ()) {Log.info ("this index [" + Index + "] already exists in the ES cluster"); } else {Log.info ("does not have this index [" + Index + "]"); } return iep.isexists (); }}
service layer for Interface Data encapsulation:
Package Org.githup.es.service;import java.util.map;import com.alibaba.fastjson.jsonobject;/** * ES service side * * @author SDC * * /public interface Essearchservice {/** * Build index * @param index * @return */public Boolean Buildindex (String index); /** * Delete Index * @param index * @return */public boolean delindex (String index); /** * Query Data * @param index Index <-----> relational database * @param type <-----> Relational datasheet * @param ID data id&l t;----->id * @return */public map<string, object> searchdatabyparam (string index, String type, string ID); /** * Update data * @param data added in JSON format * @param index Index <-----> relational database * @param type < -----> Relational Data sheet * @param ID data id<----->id * @return */public void Updatedatabyid (Jsonobject data, String index, String type, string id); /** * Add data * @param data added in JSON format * @param index Index <-----> relational database * @param type <-----> Relational datasheet * @param ID Data id<----->id * @return */public String AddT Argetdataall (jsonobject data, string index, String type, string id); /** * Delete data by ID * * @param index index, similar database * @param type, similar to table * @param ID Data ID */public VO ID Deldatabyid (string index, String type, string id); /** * Determine if an index exists * * @param index * @return */public boolean isindexexist (String index); Package Org.githup.es.service.impl;import Java.util.map;import Org.githup.es.dao.esrepository;import Org.githup.es.service.essearchservice;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.service;import com.alibaba.fastjson.jsonobject;/** * ES specific implementation class * * Note: Extract the classification information of ES * * @autho R SDC * */@Servicepublic class Essearchserviceimpl implements essearchservice{@Autowired private Esrepository Esrep Ository; @Override public boolean Buildindex (String index){return Esrepository.buildindex (index); @Override public boolean Delindex (String index) {return Esrepository.deleteindex (index); } @Override public map<string, object> searchdatabyparam (string index, String type, string id) {//TOD O auto-generated Method Stub return Esrepository.searchdatabyparam (index, type, id); } @Override public void Updatedatabyid (jsonobject data, string index, String type, string id) {//TODO auto- Generated method stub Esrepository.updatedatabyid (data, index, type, id); } @Override Public String addtargetdataall (jsonobject data, string index, String type, string id) {//TODO A uto-generated Method Stub return Esrepository.addtargetdataall (data, index, type, id); } @Override public void Deldatabyid (string index, String type, string id) {//TODO auto-generated method Stu b Esrepository.deldatabyid (index, type, id); } @Override PublIC boolean isindexexist (String index) {//TODO auto-generated Method stub return Esrepository.isindexexist ( index); }}
Maven Environment:
<?xml version= "1.0" encoding= "UTF-8"? ><project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "http ://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation=" http://maven.apache.org/POM/4.0.0/http Maven.apache.org/xsd/maven-4.0.0.xsd "> <modelVersion>4.0.0</modelVersion> <groupId> Org.githup.es</groupid> <artifactId>springboot-es-sample-search</artifactId> <version> 1.0-snapshot</version> <packaging>jar</packaging> <name>spring-boot-es</name> <d Escription> Search Service Implementation classes </description> <parent> <groupid>org.springframework.boot</groupid> ; <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.0.RELEASE</version> <relativepath/> <!--lookup parent from repository--</parent> <properties> <p Roject.build.sourceencoding>utf-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java .version>1.8</java.version> <elasticsearch.version>5.5.3</elasticsearch.version> <lo G4j2.version>2.6.2</log4j2.version> <fastjson.version>1.2.31</fastjson.version> <com mons.lang3.version>3.4</commons.lang3.version> </properties> <repositories> <reposito Ry> <id>spring-releases</id> <URL>HTTPS://REPO.SPRING.IO/LIBS-RELEASE</URL&G T </repository> </repositories> <!--Elasticsearch 5.x and <dependencies> <DEP Endency> <groupId>org.springframework.boot</groupId> <artifactid>spring-boot-st arter</artifactid> </dependency> <dependency> <groupid>org.springframewor K.boot</groUpid> <artifactId>spring-boot-starter-test</artifactId> <SCOPE>TEST</SCOPE&G T </dependency> <!--Https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web- <dependency> <groupId>org.springframework.boot</groupId> <artifact id>spring-boot-starter-web</artifactid> </dependency> <dependency> <group Id>org.elasticsearch</groupid> <artifactId>elasticsearch</artifactId> <versi on>${elasticsearch.version}</version> </dependency> <dependency> <groupid >org.elasticsearch.client</groupId> <artifactId>transport</artifactId> <vers ion>${elasticsearch.version}</version> </dependency> <dependency> <groupi D>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>${fastjson.version}< ;/version> </dependency> <dependency> <groupid>org.apache.commons</groupi D> <artifactId>commons-lang3</artifactId> <version>${commons.lang3.version}< /version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>${fastjson.version}</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactid>spring-boot-maven-plugin< ;/artifactid> </plugin> <plugin> <groupid>org.apache.maven.plugi Ns</groupid> <artifactId>maven-surefire-plugin</artifactId> <configuration> <skip>true</skip> </configuration> </plugin> </plugins> </build></project>
The specific code URL Githup:https://github.com/growup818/springboot-es-search
Can be downloaded down, familiar with Springboot's small partners can quickly perform demo detection.
Spring Boot 2.X Integrated Elasticsearch 5.x combat additions and deletions