SpringBoot integration with elasticsearch
Before this one article begins, You need to first install aElasticSearch, If you aremac perhapslinux You can refer tohttps://www.jianshu.com/p/e47b451375ea , if it's windows you can customize it to Baidu.
Here is the official set of words introducing elasticsearch.
ElasticSearch is a Lucene based search server. It provides a distributed multi-user capable full-text search engine, based on a RESTful web interface. Elasticsearch, developed in Java and released as open source under the terms of the Apache license, is a popular enterprise-class search engine today. Designed for use in the cloud, it is capable of achieving real-time search, stability, reliability, speed, and ease of installation and use. We build a website or application and want to add search functionality, but it is very difficult to get the search job created. We want the search solution to run fast, we want a zero-configuration and a completely free search model, we want to be able to index data simply using JSON over HTTP, we want our search servers to be always available, we want to be able to start with one and scale to hundreds, we want real-time search, we want simple multi-tenancy, and we want to build a cloud solution. So we use Elasticsearch to solve all these problems and many more that may arise.
For specific elasticsearch-related questions, you can go to elastic Chinese Community View.
This post will describe how springboot can simply integrate with elasticsearch.
1.Start elasticsearch. 2.Create a new project, add the elasticsearch dependency to the pom file, and the full pom is as follows.
<?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>com.dalaoyang</groupId> <artifactId>springboot_elasticsearch</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>springboot_elasticsearch</name> <description>springboot_elasticsearch</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.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> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
The configuration file is as follows.
## Port number server.port=8888 ##es address spring.data.elasticsearch.cluster-nodes = 127.0.0.1:9300
Create a new merchandise physical categoryGoodsInfo, Among the things to note: indexName: index name can be understood as database name, must be lowercase, otherwise it will report org.elasticsearch.indices.InvalidIndexNameException type: type can be understood as a table name
package com.dalaoyang.entity; import org.springframework.data.elasticsearch.annotations.Document; import java.io.Serializable; /** * @author dalaoyang * @Description * @project springboot_learn * @package com.dalaoyang.entity * @email yangyang@dalaoyang.cn * @date 2018/5/4 */ @Document(indexName = "testgoods",type = "goods") //indexName Index Name can be understood as the database name Must be lowercase Otherwise it will reportorg.elasticsearch.indices.InvalidIndexNameException anomaly //type types can be understood as the name of the table public class GoodsInfo implements Serializable { private Long id; private String name; private String description; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public GoodsInfo(Long id, String name, String description) { this.id = id; this.name = name; this.description = description; } public GoodsInfo() { } }
Create a GoodsRepository that inherits the ElasticsearchRepository with the following code.
package com.dalaoyang.repository; import com.dalaoyang.entity.GoodsInfo; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import org.springframework.stereotype.Component; /** * @author dalaoyang * @Description * @project springboot_learn * @package com.dalaoyang.repository * @email yangyang@dalaoyang.cn * @date 2018/5/4 */ @Component public interface GoodsRepository extends ElasticsearchRepository<GoodsInfo,Long> { }
Finally, create a new controller for testing, which contains a simple add, delete, and a search, add, delete, and search is not explained here. Note that the first page number of es is 0
package com.dalaoyang.controller; import com.dalaoyang.entity.GoodsInfo; import com.dalaoyang.repository.GoodsRepository; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder; import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.data.elasticsearch.core.query.SearchQuery; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * @author dalaoyang * @Description * @project springboot_learn * @package com.dalaoyang.controller * @email yangyang@dalaoyang.cn * @date 2018/5/4 */ @RestController public class GoodsController { @Autowired private GoodsRepository goodsRepository; //http://localhost:8888/save @GetMapping("save") public String save(){ GoodsInfo goodsInfo = new GoodsInfo(System.currentTimeMillis(), " merchandise"+System.currentTimeMillis()," This is a test item."); goodsRepository.save(goodsInfo); return "success"; } //http://localhost:8888/delete?id=1525415333329 @GetMapping("delete") public String delete(long id){ goodsRepository.delete(id); return "success"; } //http://localhost:8888/update?id=1525417362754&name= modify&description= modify @GetMapping("update") public String update(long id,String name,String description){ GoodsInfo goodsInfo = new GoodsInfo(id, name,description); goodsRepository.save(goodsInfo); return "success"; } //http://localhost:8888/getOne?id=1525417362754 @GetMapping("getOne") public GoodsInfo getOne(long id){ GoodsInfo goodsInfo = goodsRepository.findOne(id); return goodsInfo; } // Number per page private Integer PAGESIZE=10; //http://localhost:8888/getGoodsList?query= merchandise //http://localhost:8888/getGoodsList?query= merchandise&pageNumber=1 // Based on keywords" merchandise" Go to search list,name perhapsdescriptionContains all queries @GetMapping("getGoodsList") public List<GoodsInfo> getList(Integer pageNumber,String query){ if(pageNumber==null) pageNumber = 0; //es The default page number for the first page of the search is0 SearchQuery searchQuery=getEntitySearchQuery(pageNumber,PAGESIZE,query); Page<GoodsInfo> goodsPage = goodsRepository.search(searchQuery); return goodsPage.getContent(); } private SearchQuery getEntitySearchQuery(int pageNumber, int pageSize, String searchContent) { FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery() .add(QueryBuilders.matchPhraseQuery("name", searchContent), ScoreFunctionBuilders.weightFactorFunction(100)) .add(QueryBuilders.matchPhraseQuery("description", searchContent), ScoreFunctionBuilders.weightFactorFunction(100)) // Set weight score summation model .scoreMode("sum") // Set weighted score minimum .setMinScore(10); // Setting up paging Pageable pageable = new PageRequest(pageNumber, pageSize); return new NativeSearchQueryBuilder() .withPageable(pageable) .withQuery(functionScoreQueryBuilder).build(); } }
Start the project, first call http://localhost:8888/save approach, insert a few pieces of data, and then go to the es admin pagehttp://localhost:9200/_plugin/head/ The figure below
interviewshttp://localhost:8888/getGoodsList?query= merchandise as shown in the figure.
Source Code Download : Big Old Yang Code Cloud
Personal website: https://www.dalaoyang.cn