[Turn] Spring Boot Secret and Combat (ii) data storage-ElasticSearch

Source: Internet
Author: User
Tags iterable

[From] Http://www.tuicool.com/articles/JBvQrmj

This article explains how to use ElasticSearch to achieve full-text search based on spring boot.

Version notes

The version of Spring data ElasticSearch needs to match the spring boot, elasticSearch version.

Spring Boot Version (x) Spring Data Elasticsearch Version (y) Elasticsearch Version (z)
X <= 1.3.5 Y <= 1.3.4 Z <= 1.7.2
X >= 1.4.x 2.0.0 <=y <5.0.0 2.0.0 <= Z < 5.0.0
Environmental dependency

Modify the POM file to add spring-boot-starter-data-elasticsearch dependencies.

<dependency>    <groupid>org.springframework.boot</<artifactid> Spring-boot-starter-data-elasticsearch</artifactid></dependency>  
Data source Scenario One uses Spring Boot default configuration

Configure the data source information in Src/main/resources/application.properties.

Spring.  data.elasticsearch.properties.host = 127.0.0.1spring.  Data.elasticsearch.properties.port = 9300  

Create Elasticsearchconfig with Java Config.

@Configuration@EnableElasticsearchRepositories ("Com.lianggzone.springboot.action.data.elasticsearch") public class Elasticsearchconfig {} 
Scenario two manually created

Create Elasticsearchconfig with Java Config.

@Configuration@EnableElasticsearchRepositories ("Com.lianggzone.springboot.action.data.elasticsearch")PublicClassElasticsearchConfig2 {Private String hostname =  "127.0.0.1"; private int port = 9300;  @Bean public elasticsearchoperations elasticsearchtemplate () {return new elasticsearchtemplate (Client ()); }  @Bean public Client client () {transportclient client = new Transportclient (); transportaddress address = new inetsockettransportaddress (hostname, port); Client.addtransportaddress (address); return client;}            
Business Operation Entity Object
@Document (IndexName ="Springbootdb",Type ="News") publicClassNews {@IdPrivateString ID; private String title; private String content; @JsonFormat (shape = jsonformat.  Shape. STRING, pattern = "YyyyMMdd ' T ' hhmmss.sss ' Z '") @Field (type = FieldType.  Date, format = dateformat.basic_date_time, index = fieldindex.not_analyzed) @CreatedDate Private C19>date createdDateTime; //Get and Set methods}                 
DAO related
elasticsearchrepository<list<news> findbytitle (String title);}
Service-related

Let's define the implementation class, the service layer calls the DAO layer method, this is a typical routine.

@ServicePublicClassNewsservice {@AutowiredPrivate Newsrepository newsrepository;Public iterable<news>FindAll(){return Newsrepository.findall (); }Public iterable<news>Search(QueryBuilder query) {return Newsrepository.search (query); }Public List <News> Findbytitle (String title) {ReturnThis.newsRepository.findByTitle (title); }Publicvoid deleteAll(String id) { this.newsRepository.delete (ID);} public void init() {for (int i = 0; i < i++) {News news = New News (); new S.setid (i+""); News.settitle (i + ". Liang unit Test Case"), News.setcontent ("Liang unit test Case" +i+"xxxxx"); News.setcreateddatetime ( new Date ()); This.newsRepository.save (news);} }}
Controller related

To demonstrate the effect, we first define a simple set of RESTful API interfaces for testing.

@RestController@RequestMapping (value="/data/elasticsearch/news") publicClassNewscontroller {@Autowired private Newsservice Newsservice;/*** Initialization* @param request*/@RequestMapping (value ="/init", method = requestmethod.post) publicvoid init (HttpServletRequest request) {This.newsService.init (); }/*** FINDALL* @param request* @return*/@RequestMapping (value ="/", method = Requestmethod.get) publicmap<String,Object> findlist (HttpServletRequest request) {map<String,object> params =New hashmap<String,Object> (); Params.put ("Items",This.newsService.findAll ());return params; }/*** Find* @param request* @return* /@RequestMapping (value = "/{title}", method = requestmethod.get) public map<String, Object > Search (@PathVariable String title) { //Build query condition QueryBuilder QueryBuilder = querybuilders.querystring ( title); map<string, object> params = new hashmap<string, object> (); Params.put (  "Items", This.newsService.search (QueryBuilder)); return params;}}                 
Summarize

In this simple case, let's see the Spring Boot integration ElasticSearch process so simple.

[Turn] Spring Boot Secret and Combat (ii) data storage-ElasticSearch

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.