This is the 28th day of my participation in the August Text Challenge.More challenges in August

| author: jiangxia

| CSDN:blog.csdn.net/qq_41153943

| the nuggets: juejin. Cn/user / 651387…

| zhihu: www.zhihu.com/people/1024…

| GitHub:github.com/JiangXia-10…

This article is about 6,532 words and takes 18 minutes to read

What is ElasticSearch

Let’s talk about search engines before we talk about ElasticSearch. A Search Engine, also known as a Search Engine, is a computer program that helps users Search for what they need by matching the information stored in the computer with the user’s information needs and presenting the matching results. Simply put, the search engine is the world Wide Web environment in order to make the speed of Internet users to search information faster, accurate information retrieval system. Common search engines are Baidu, Google, Sogou and so on.

Elasticsearch is a distributed, scalable, real-time search and analysis engine that builds on Apache Lucene(TM), a full-text search engine that provides distributed, multi-user capabilities based on RESTful Web interfaces. It can achieve real-time search, stability, reliability, fast, easy to install and use. Not only does it include full-text search, it also does the following:

  • Distributed real-time file storage and indexing every field so that it can be searched.

  • Distributed search engine for real-time analysis.

  • Scalable to hundreds of servers, processing petabytes of structured or unstructured data.

Elasticsearch, developed in the Java language and released as open source under the Apache license, is a popular enterprise-level search engine.

This article will document the integration of SpringBoot with ElasticSearch.

Install ElasticSearch

Elasticsearch is developed in Java, so you need to install and configure the Java environment before installing Elasticsearch.

And then go to www.elastic.co/cn/download… Select the appropriate system environment to download the package, which should be slow.

This section describes how to install ElasticSearch on a Mac, Linux, and Windows OPERATING systems. Install ElasticSearch on Mac

Install ElasticSearch on MacOS

First download the corresponding MacOS installation package.

Homebrew is installed

brew install elasticsearch
Copy the code

run

  • Check the status

    $ brew services list

  • Start the

    $ brew services start elasticsearch

  • restart

    $ brew services restart elasticsearch

  • stop

    $ brew services stop elasticsearch

Enter http://localhost:9200 to check whether ES is running

Install ElasticSearch on Linux

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.

Create /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

Then 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

Example Modify the configuration file elasticSearch. yml.

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

Modify the following:

/data/es-data path.data: /data/es-data path.data: /data/es-data path.data /data/es-data # set path to /log/es-log path.logs 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 9200 # to add new parameters, in order to let the elasticsearch - head plug-in can access elasticsearchhttp. Cors. Enabled: true HTTP. Cors. Allow - origin: "*"Copy the code

Start the elasticsearch.

systemctl start elasticsearch
Copy the code

Check the status

systemctl status elasticsearch
Copy the code

Setting boot

systemctl enable elasticsearch
Copy the code

After successful startup, test whether the service is enabled, or browser access.

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

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

{ "name": "pYAFJhz", "cluster_name": "my ElasticSearch", "cluster_uuid": "oC28y-cNQduGItC7qq5W8w", "version": {" number ":" 6.8.2 ", "build_flavor" : "the oss," "build_type" : "tar", "build_hash" : "b506955", "build_date" : "The 2020-07-07 T20: comest. 545295 z", "build_snapshot" : false, "lucene_version" : "Minimum_index_compatibility_version ": "5.6.0", "minimum_index_compatibility_version": "5.0.0"}, "tagline": "You Know, for Search" }Copy the code

Install ElasticSearch on Windows

Download the installation package, decompress it, and double-click bin/ ElasticSearch. bat to install it.

Run the command prompt when the installation is complete

elasticsearch.bat -d
Copy the code

Or double-click elasticSearch.bat to execute elasticSearch.bat

Enter http://localhost:9200 to check whether ES is running.

Do you want to use cURL?

curl ‘http://localhost:9200/? pretty’

If the same result is displayed, the installation is successful.

ElasticSearch (SpringBoot

It’s all about preparation. Once ElasticSearch is installed, SpringBoot will be used to integrate ElasticSearch. SpringBoot provides ElasticSearch libraries. You only need to add a dependency package, which is very easy to access through JPA.

Start by creating a SpringBoot project. I’m using IDEA here. If you don’t already know how to create a SpringBoot project, you can refer to this article: Getting Started with SpringBoot: Building your first SpringBoot project using IDEA and Eclipse.

After creating the SpringBoot project, add the ElasticSearch and JPA dependencies to pop.xml as follows:

<! -- 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

Create a new application.properties file and add the ElasticSearch configuration:

Spring. Data. Elasticsearch. Cluster - name = my elasticsearch spring. Data. Elasticsearch. Cluster nodes = 192.168.5.229: - 9200Copy the code

Here I create a user table in the database and insert the data.

Construction sentences:

CREATE TABLE `user` (
 `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
 `email` varchar(255) NOT NULL COMMENT '邮箱',
 `password` varchar(255) NOT NULL COMMENT '密码',
 `username` varchar(255) NOT NULL COMMENT '姓名',
 PRIMARY KEY (`id`),
 UNIQUE KEY `email` (`email`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

Copy the code

Insert data:

INSERT INTO 'user' VALUES ('1', '[email protected]', '123456', '123456'); INSERT INTO 'user' VALUES ('2', '[email protected]', '234567'); INSERT INTO ` user ` VALUES (' 3 ', '3 @qq.com', '345678', 'Cathy');Copy the code

The front is some preparatory work, behind the formal start some background code. First, create a new entity class named User with the following code:

@data @accessors (chain = true) // indexName @document (indexName = "user", type = "person") public class user {@id private String Id; private String email; private String password; private String username; }Copy the code

JPA is used as the data persistence layer, the interface inherits from ElasticsearchRepository, and two custom query methods are added. For more information about the use of JPA, see: SpringBoot integrates JPA for data access.

public interface userRepository extends ElasticsearchRepository<Student, String> {
    List<User> findUserByName(String username);
}
Copy the code

Create the control layer, the core logic code is as follows:

@RestController @RequestMapping("/user") public class UserController { @Autowired private UserRepository userRepository;  @Autowired private ElasticsearchTemplate elasticsearchTemplate; @getMapping ("/get/{ID}") public Object getById(@pathVariable String ID){if(stringutils.isempty (ID)){ return Result.error(); } Optional<User> studentOptional = userRepository.findById(id); if(userOptional.isPresent()){ return userOptional.get(); } return null; } @getMapping ("/search/username") public Object searchName(String username){List<User> users = userRepository.findByName(username); return users; }}Copy the code

Then start writing the front end page to display the results. Create a new index.html file under webApp with the following code:

<! DOCTYPE HTML > < HTML > <head> <meta charset="UTF-8"> <title>SSMDemo</title> </head> <script> //selectUser function selectUser() { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("test").innerHTML = xmlhttp.responseText; } } xmlhttp.open("POST", "/get/{id}", true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send("id=2"); Function SearchUser() {var XMLHTTP = new XMLHttpRequest(); xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("test").innerHTML = xmlhttp.responseText; } } xmlhttp.open("POST", "/search/username", true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); XMLHTTP. Send (" username = fifty "); } </script> <body> <p id="test">Hello World</p> <button type="button" onclick="selectUser()" </button> </body> </ HTML >Copy the code

Run the project and the test results are as follows:

4, Ending

Elasticsearch is a distributed, scalable, real-time search and data analysis engine. It makes it easy to search, analyze and explore large amounts of data. So where Elasticsearch is really powerful and where the company is using it a lot is with massive data queries. If you have any questions about Elasticsearch, please leave a comment below or in the background. If you have any questions about Elasticsearch, please leave a comment below.

Phase to recommend

  • SpringBoot integrates JPA for data access

  • SpringBoot integration Mybatis(top) : Annotated edition

  • SpringBoot integration Mybatis(below) : configuration version