This paper is mainly introduced into the following parts:

  • Install ElasticSearch. Install ElasticSearch- Head
  • The second part: SpringBoot integration ElasticSearch development
  • Part THREE: CRUD test

Install ElasticSearch

To be consistent with the real world, we used CentOS7 to deploy the ElasticSearch service.

You are advised to manually download the ElasticSearch installation package from the Internet because it takes a snail to download the ElasticSearch installation package. , very slow ~ ~, may be the domestic network reason!

Log on to www.elastic.co/cn/download…

2.1, install JDK (already installed, can skip)

Elasticsearch is developed in The Java language, so you will need to install the JDK before installing it

Yum -y install Java -- 1.8.0 comes with itsCopy the code

Check the Java installation

java -version
Copy the code

Install ElasticSearch

Go to the uploaded folder and install ElasticSearch

The RPM - the ivh elasticsearch - 6.1.0. RPMCopy the code

Finding the installation path

rpm -ql elasticsearch
Copy the code

Is generally installed in/usr/share/elasticsearch.

2.3. Set the directory of data

Create the /data/es-data directory to store ElasticSearch data

mkdir -p /data/es-data
Copy the code

Change the owner of this directory to ElasticSearch

chown -R elasticsearch:elasticsearch /data/es-data
Copy the code

2.4. Set the log directory

mkdir -p /log/es-log
Copy the code

Change the owner of this directory to ElasticSearch

chown -R elasticsearch:elasticsearch /log/es-log
Copy the code

2.5. Modify the elasticSearch. yml configuration file

vim /etc/elasticsearch/elasticsearch.yml
Copy the code

Modify the following:

Data: /data/es-data: /data/es-data: /data/es-data: /data/es-data: /data/es-data Memory_lock is set to true, but 9200 will not be listened on, for unknown reasons. Host: 0.0.0.0 # enable listening on port 9200 http.port: 0.0.0.0 Http.coron. enabled: true http.coron. allow-origin: "*"Copy the code

2.6 start ElasticSearch

Start the

systemctl start elasticsearch
Copy the code

Check the status

systemctl status elasticsearch
Copy the code

Setting boot

systemctl enable elasticsearch
Copy the code

After the service is successfully started, test whether the service is started

curl -X GET http://localhost:9200
Copy the code

If the following information is displayed, the installation and startup are successful

You can also test remotely, and if the network is rejected, check whether the firewall is enabled

Firewall-cmd --stateCopy the code

If the status is Active, it indicates that it is enabled. You can disable it

Systemctl stop firewalld. ServiceCopy the code

If you do not want to start the system, run the following command

Disable systemctl disable firewalld.serviceCopy the code

Let’s test whether the remote is accessible, and the result is as follows:

It is already accessible.

Install ElasticSearch-head

ElasticSearch can only be used to query data through an interface.

ElasticSearch-head is a plugin for ElasticSearch that provides a visual interface. It is developed using Html5 and is essentially a nodeJS project, so nodeJS is required before using it.

3.1. Install nodeJs

Download nodeJS

Wget HTTP: / / https://nodejs.org/dist/v10.9.0/node-v10.9.0-linux-x64.tar.gzCopy the code

Decompress the download package

The tar - ZXVF node - v10.9.0 - Linux - x64. Tar. GzCopy the code

Move the decompressed folder to /usr/local

Node - mv v10.9.0 - Linux - x64 / usr/local/nodejsCopy the code

Create soft links so that the NPM and node commands take effect globally

ln -s /usr/local/nodejs/bin/node /usr/bin/node
ln -s /usr/local/nodejs/bin/npm /usr/bin/npm
Copy the code

Check whether nodeJS is installed successfully

node -v
npm -v
Copy the code

Install elasticSearch-head

If you have not installed Git, install the Git tool first

Yum install - y gitCopy the code

Check git installation

git --version
Copy the code

Select elasticSearch -head from gitHub

git clone https://github.com/mobz/elasticsearch-head.git
Copy the code

The elasticSearch -head folder is displayed

cd elasticsearch-head
Copy the code

Because NPM installation is very slow, so here to install taobao source address, the command is as follows:

npm install cnpm -g --registry=https://registry.npm.taobao.org
Copy the code

Create a CNPM soft link. Otherwise, an error occurs when you run the following command

ln -s /usr/local/nodejs/bin/cnpm /usr/local/bin/cnpm
Copy the code

Use the CNPM command to download the plug-ins needed to install the project

cnpm install
Copy the code

It will be installed in about 2 minutes. After installation, modify the configuration information

vim _site/app.js
Copy the code

Change localhost to elasticSearch server address (197.168.24.207)

After that, run the following command in the elasticSearch-head directory to go to the boot directory

cd node_modules/grunt/bin
Copy the code

Use the following command to start the elasticSearch-head service in the background!

nohup ./grunt server &
Copy the code

You can access the elasticSearch-head page from the browser. The default IP address is 9100.

Elasticsearch is now installed with the elasticSearch head visual interface plugin!

ElasticSearch (SpringBoot

ElasticSearch is a middleware application that provides an efficient search service for ElasticSearch. SpringBoot also provides a dependency library for ElasticSearch, which is easy to access through JPA. The integration process is as follows!

4.1 create a SpringBoot project

In pom.xml, add the dependency library ElasticSearch dependency package

<! -- JPA support --> <dependency> <groupId>org.springframework.boot > <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <! --elasticsearch--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency>Copy the code

Add the configuration in application.properties, where node name cluster-name must be the same as the configuration above!

Spring. Data. Elasticsearch. Cluster - name = my - es spring. Data. Elasticsearch. Cluster nodes = 197.168.24.207: - 9300Copy the code

4.1. Write CURD

Let’s start by writing an entity class named Student that performs basic CRUD functionality.

  • New entity class Student where indexName represents index and type represents index category

    @Data @Accessors(chain = true) @Document(indexName = “student”, type = “school”) public class Student {

    private static final long serialVersionUID = 1l;
    
    @Id
    private String id;
    
    private String name;
    
    private String gender;
    
    private Integer age;
    Copy the code

    }

Note that the ID field is required and you don’t need to annotate @id!

  • JPA is used as the data persistence layer, the interface inherits from ElasticsearchRepository, and two custom query methods are added

    public interface StudentRepository extends ElasticsearchRepository<Student, String> {

    List<Student> findByNameLike(String keyword); /** * findByNameLike(String keyword); Fixed matching / * * * a custom Query, Query student information * @ param @ the return keyword * * / @ Query (" {\ "match_phrase \" : {\ "name \" : \ "? 0\"}}") List<Student> findByNameCustom(String keyword);Copy the code

    }

  • Create the control layer and write the basic CRUD functionality

    @RestController @RequestMapping(“/student”) public class StudentController {

    @Autowired private StudentRepository studentRepository; @Autowired private ElasticsearchTemplate elasticsearchTemplate; Public void add(@requestBody List<Student>) public void add(@requestBody List<Student>) students){ studentRepository.saveAll(students); } /** * add * @param student * @return */ @postmapping ("/add") public void add(@requestBody student student){ studentRepository.save(student); } /** * modify * @param student * @return */ @postmapping ("/update") public void updateById(@requestBody student student){ studentRepository.save(student); } /** * delete * @param id * @return */ @postmapping ("/delete/{id}") public void deleteById(@pathVariable String id){ studentRepository.deleteById(id); } @getMapping ("/get") public Object getAll(){Iterable<Student> Iterable = studentRepository.findAll(); List<Student> list = new ArrayList<>(); iterable.forEach(list :: add); return list; } @getMapping ("/get/{ID}") public Object getById(@pathVariable String ID){ if(StringUtils.isEmpty(id)){ return Result.error(); } Optional<Student> studentOptional = studentRepository.findById(id); if(studentOptional.isPresent()){ return studentOptional.get(); } return null; } /** * @keyword * @return */ @getMapping ("/search/name") public Object searchName(String keyword){ List<Student> students = studentRepository.findByNameLike(keyword); return students; } /** * Custom matching * common search * @param keyword * @return */ @getMapping ("/search/name/custom") public Object searchTitleCustom(String keyword){ List<Student> students = studentRepository.findByNameCustom(keyword); return students; } /** * advanced search, * @param keyword * @return */ @getMapping ("/top/search/name") Public Object topSearchTitle(String keyword){ SearchQuery searchQuery = new NativeSearchQueryBuilder() .withQuery(queryStringQuery(keyword)) .build();Copy the code

    / / using searchQuery search List. Students = elasticsearchTemplate queryForList (searchQuery, Student class); return students; }}

4.2. CRUD test

Once CRUD is written, let’s verify that it works, start the SpringBoot project, and test using Postman.

  • Batch new, new functional tests

After execution, log in to the visual interface query screen, select index Student, and you can clearly see that the data has been entered

  • To modify a functional test, you need to pass in an ID

Change Wang Xiaojian from 26 years old to 30 years old, login visual interface query data has also been modified successfully!

  • To remove functional tests, simply pass in the ID

Delete Li Si, login visual interface query data has been deleted successfully!

  • Query functional tests, query all data

  • To query a function test, run the following command

  • Select * from ElasticSearch; select * from ElasticSearch; select * from ElasticSearch; select * from ElasticSearch

  • Query function test, advanced query, this is the use of the official API provided by the query entry, you can do custom search in the method

Five, the summary

Elasticsearch is a very efficient way to query data from a large number of databases. This section describes how to query data from a large number of databases.

For beginners who want to learn ElasticSearch, it can be quite difficult to install it, so it takes a lot of time to write it, and it’s easy to integrate it. The real power of ElasticSearch is the efficient information search. Elasticsearch is a search engine for elasticSearch that you can use to search for the most advanced version of the elasticSearch service.

Three things to watch ❤️

If you find this article helpful, I’d like to invite you to do three small favors for me:

  1. Like, forward, have your “like and comment”, is the motivation of my creation.

  2. Follow the public account “Java rotten pigskin” and share original knowledge from time to time.

  3. Also look forward to the follow-up article ing🚀

  4. [666] Scan the code to obtain the learning materials package