In this article before you begin, you need to install a ElasticSearch first, if you’re a MAC or Linux can refer to www.jianshu.com/p/e47b45137… , if Windows can customize baidu.

Here’s the official introduction to 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. Developed in Java and distributed as open source under the Apache license, Elasticsearch is a popular enterprise search engine. Designed for cloud computing, can achieve real-time search, stable, reliable, fast, easy to install and use. We build a website or application and add a search function, but it is very difficult to complete the search creation. We want to search for solutions to run faster, we hope to have a zero configuration and a completely free search pattern, we hope to be able to simply use JSON over HTTP to index data, we hope that our search server available all the time, we hope to be able to start with a and extend to the hundreds of, we want to live search, We want simple multi-tenancy, we want to build a cloud solution. So we use Elasticsearch to solve all of these problems and possibly many more.

For details on ElasticSearch, go to the Elastic Community.

This article will show you how SpringBoot can easily integrate ElasticSearch.

1. Start ElasticSearch. Create a new project and add elasticSearch dependencies to the POM file. The complete 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 - the SNAPSHOT < / version > < packaging > jar < / packaging > < name > springboot_elasticsearch < / name > <description>springboot_elasticsearch</description> <parent> <groupId>org.springframework.boot</groupId> The < artifactId > spring - the 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>
Copy the code

The configuration file is as follows:

# # the port number
server.port=8888

# # es addressSpring. Data. Elasticsearch. Cluster nodes = 127.0.0.1: - 9300Copy the code

Create a new product entity class, GoodsInfo. Note: indexName: The index name Can be understood as the database name Must be lowercase Or you will quote org. Elasticsearch. Indices. InvalidIndexNameException exception 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 [email protected]
 * @date 2018/5/4
 */
@Document(indexName = "testgoods".type = "goods") / / indexName index name Can be understood as the database name Must be lowercase Or you will quote org. Elasticsearch. Indices. InvalidIndexNameException / /typePublic class GoodsInfo Implements Serializable {private Long ID; private String name; private String description; public LonggetId() {
        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() {}}Copy the code

Create a GoodsRepository and inherit ElasticsearchRepository as follows:

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 [email protected]
 * @date 2018/5/4
 */
@Component
public interface GoodsRepository extends ElasticsearchRepository<GoodsInfo,Long> {
}
Copy the code

Finally, create a new controller to test, which contains simple add, delete, modify and search and a search, add, delete and modify and I won’t explain here. Notice that the first page 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 [email protected]
 * @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(),
                "Goods"+System.currentTimeMillis(),"This is a test product.");
        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);
        returngoodsInfo; } // Number of pages per page private Integer PAGESIZE=10; //http://localhost:8888/getGoodsList? Query = goods / / http://localhost:8888/getGoodsList? Query = commodity &pageNumber=1 // according to keyword"Goods"To query the list, either name or description contains @getMapping ()."getGoodsList")
    public List<GoodsInfo> getList(Integer pageNumber,String query){
        if(pageNumber==null) pageNumber = 0; / / es on the default page number is 0 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))/weight/set points sum model. ScoreMode ("sum") // Set the lowest weight score. SetMinScore(10); Pageable = new PageRequest(pageNumber, pageSize);return new NativeSearchQueryBuilder()
                .withPageable(pageable)
                .withQuery(functionScoreQueryBuilder).build(); }}Copy the code

Start the project, first call http://localhost:8888/save method, insert a few data, then go to es management page, http://localhost:9200/_plugin/head/, the following figure

Go to http://localhost:8888/getGoodsList? Query = commodity, as shown in figure:

Source download: Old Yang code cloud

Personal website: www.dalaoyang.cn