Spring Boot integrated elasticsearch for simple additions, deletions and changes to the interface

Source: Internet
Author: User

Springboot Integrated Elasticsearch

In the Pom.xml file, the following versions of the jar packages are dependent:

<parent> <groupId>org.springframework.boot</groupId> <artifactId> Spring-boot-starter-parent</artifactid> <version>2.0.3.RELEASE</version> <relativePath/> <!--lookup parent from repository--></parent><properties> <project.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.2</elasticsearch.version></properties><dependencies> <dependency> <groupid>org .springframework.boot</groupid> <artifactId>spring-boot-starter-web</artifactId> </dependen cy> <dependency> <groupId>org.projectlombok</groupId> <artifactid>lombok</a rtifactid> <optional>true</optional> </dependency> <dEpendency> <groupId>org.springframework.boot</groupId> <artifactid>spring-boot-starter- test</artifactid> <scope>test</scope> </dependency> <dependency> <gro Upid>org.elasticsearch.client</groupid> <artifactId>transport</artifactId> <version& Gt;${elasticsearch.version}</version> </dependency></dependencies>

The

Creates a new config package in the project, in which a Esconfig configuration class is created to construct the client instance object for ES. The code is as follows:

Package Org.zero01.elasticsearch.demo.config;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.springframework.context.annotation.bean;import Org.springframework.context.annotation.configuration;import Java.net.inetaddress;import java.net.unknownhostexception;/** * @program: Es-demo * @description: ES configuration class * @author: * @c Reate:2018-06-28 22:32 **/@Configurationpublic class Esconfig {@Bean public transportclient client () throws Unknow                nhostexception {///9300 is the TCP service port for ES inetsockettransportaddress node = new Inetsockettransportaddress (        Inetaddress.getbyname ("192.168.190.129"), 9300); Set the configuration information for the ES node Settings Settings = Settings.builder (). Put ("Cluster.name", "es"). Bui        LD (); The client that instantiates ESLike transportclient client = new prebuilttransportclient (settings);        Client.addtransportaddress (node);    return client; }}
Query interface Development

I now have a structured index as follows:

There are some document data in the index, as follows:

Create a new controller package in the project, and create a new Bookcrudcontroller class in the package to demonstrate the ES Add and remove check and change interface demo. Let's start by developing a query interface with the following code:

Package Org.zero01.elasticsearch.demo.controller;import Org.elasticsearch.action.get.getresponse;import Org.elasticsearch.client.transport.transportclient;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.http.httpstatus;import Org.springframework.http.responseentity;import Org.springframework.web.bind.annotation.getmapping;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.requestparam;import org.springframework.web.bind.annotation.restcontroller;/** * @program: Es-demo * @description: Es additions and Deletions Check the interface demo * @author: * @create: 2018-07-01 10:42 **/@RestController @requestmapping ("/es/demo") public class Bookcrudcontroller {@Autowire    D Private Transportclient client; /** * Query by ID * @param ID * @return */@GetMapping ("/get/book/novel") public responseentity Searchbyid (@RequestParam ("id") String ID) {if (Id.isempty ()) {return new responseentity (HttpSTatus.        Not_found);        }//Query data by index, type, id to es GetResponse response = client.prepareget ("book", "novel", id). get ();        if (!response.isexists ()) {return new responseentity (Httpstatus.not_found);    }//Return the query to the data return new Responseentity (Response.getsource (), Httpstatus.ok); }}

Start the Springboot project and test with Postman, with the following query results:

New Interface Development

To develop new interfaces in the Bookcrudcontroller class, the code is as follows:

/** * Add Book Data * * @param title Book title * @param author book author * @param wordCount book Words * @param publishdate release time * @                          return */@PostMapping ("/add/book/novel") public responseentity Add (@RequestParam ("title") String title,                          @RequestParam ("author") String author, @RequestParam ("Word_count") int wordCount,                                  @RequestParam ("Publish_date") @DateTimeFormat (pattern = "Yyy-mm-dd HH:mm:ss") Date publishdate) {try {///to build a parameter into a JSON object xcontentbuilder content = XC Ontentfactory.jsonbuilder (). StartObject (). Field ("title", title). Field ("Aut                Hor ", author). field (" Word_count ", WordCount). Field (" Publish_date ", Publishdate.gettime ())        . EndObject ();              Indexresponse response = Client.prepareindex ("book", "novel"). SetSource (content)  . get ();    return new Responseentity (Response.getid (), Httpstatus.ok);        } catch (IOException e) {e.printstacktrace ();    return new responseentity (Httpstatus.internal_server_error); }}

Restart the Springboot project, test with postman, and the test results are as follows:

Using the returned ID to query the book data we just added, the results are as follows:

Remove interface Development

The code is as follows:

/** * 按id删除数据 * * @param id * @return */@DeleteMapping("/delete/book/novel")public ResponseEntity delete(@RequestParam("id") String id) {    DeleteResponse response = client.prepareDelete("book", "novel", id).get();    return new ResponseEntity(response.getResult(), HttpStatus.OK);}

Restart the Springboot project, test with postman, and delete the data successfully:

Update interface Development

The code is as follows:

/** * Update data for a document based on document ID * * @param ID * @param title * @param author * @param wordCount * @param publishdate * @return * * @Pu Tmapping ("/update/book/novel") Public responseentity Update (@RequestParam ("id") String ID, @Req Uestparam (value = "title", Required = False) String title, @RequestParam (value = "Author", req Uired = False) String author, @RequestParam (value = "Word_count", required = false) Integer wo Rdcount, @RequestParam (value = "Publish_date", required = False) @ DateTimeFormat (pattern = "Yyy-mm-dd HH:mm:ss") Date publishdate) {updaterequest up    Date = new Updaterequest ("book", "novel", id);        try {xcontentbuilder builder = Xcontentfactory.jsonbuilder (). StartObject ();        if (title = null) {Builder.field ("title", title);           } if (author! = null) { Builder.field ("author", author);        } if (WordCount! = null) {Builder.field ("Word_count", WordCount);        } if (publishdate! = null) {Builder.field ("Publish_date", Publishdate.gettime ());        } builder.endobject ();        Update.doc (builder);        Updateresponse response = client.update (update). get ();    return new Responseentity (Response.getresult (). toString (), Httpstatus.ok);        } catch (Exception e) {e.printstacktrace ();    return new responseentity (Httpstatus.internal_server_error); }}

For example, we want to modify the book data with the document ID Awq-n_xewwbfsfqzkrth:

Modify the title of the book and

Modification succeeded:

Complex query Interface Development

The code is as follows:

/** * Composite Query interface * * @param title * @param author * @param wordCount * @param publishdate * @param gtwordcount * @param ltword Count * @return */@PostMapping ("/query/book/novel") public responseentity query (@RequestParam (value = "title", required                            = False) string title, @RequestParam (value = "Author", required = False) string author, @RequestParam (value = "Word_count", required = False) Integer WordCount, @R Equestparam (value = "Publish_date", required = false) @DateTimeFormat (pattern = "Yyy-mm-dd hh:m M:ss ") Date publishdate, @RequestParam (value =" Gt_word_coun T ", DefaultValue =" 0 ") Integer gtwordcount, @RequestParam (value =" Lt_word_count ", required =    False) Integer Ltwordcount) {//Assembly query condition Boolquerybuilder boolquery = Querybuilders.boolquery (); if (title = null) {Boolquery.must (QUerybuilders.matchquery ("title", title));    } if (author! = null) {Boolquery.must (Querybuilders.matchquery ("author", author));    } if (WordCount! = null) {Boolquery.must (Querybuilders.matchquery ("Word_count", WordCount));    } if (publishdate! = null) {Boolquery.must (Querybuilders.matchquery ("Publish_date", publishdate));    }//With Word_count as the condition range rangequerybuilder rangequery = querybuilders.rangequery ("Word_count"). from (Gtwordcount);    if (ltwordcount! = null && ltwordcount > 0) {rangequery.to (ltwordcount);    } boolquery.filter (Rangequery); Assemble the query request Searchrequestbuilder Requestbuilder = Client.preparesearch ("book"). Settypes ("novel"). Setsearchtype (Searchtype.dfs_query_then_fetch). Setquery (Boolquery). Setfrom (0). SetSize (    10);    Send Query Request SearchResponse response = Requestbuilder.get (); Assemble the query to the dataset list<map<string, object>> result = new ARraylist<> ();    For (Searchhit searchHitFields:response.getHits ()) {Result.add (Searchhitfields.getsource ()); } return new Responseentity (result, Httpstatus.ok);}

Restart the Springboot project, test with postman, and the test results are as follows:

Spring Boot integrated elasticsearch for simple additions, deletions and changes to the interface

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.